gtls.c 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2014, 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 http://curl.haxx.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. ***************************************************************************/
  22. /*
  23. * Source file for all GnuTLS-specific code for the TLS/SSL layer. No code
  24. * but vtls.c should ever call or use these functions.
  25. *
  26. * Note: don't use the GnuTLS' *_t variable type names in this source code,
  27. * since they were not present in 1.0.X.
  28. */
  29. #include "curl_setup.h"
  30. #ifdef USE_GNUTLS
  31. #include <gnutls/gnutls.h>
  32. #include <gnutls/x509.h>
  33. #ifdef USE_GNUTLS_NETTLE
  34. #include <gnutls/crypto.h>
  35. #include <nettle/md5.h>
  36. #else
  37. #include <gcrypt.h>
  38. #endif
  39. #include "urldata.h"
  40. #include "sendf.h"
  41. #include "inet_pton.h"
  42. #include "gtls.h"
  43. #include "vtls.h"
  44. #include "parsedate.h"
  45. #include "connect.h" /* for the connect timeout */
  46. #include "select.h"
  47. #include "rawstr.h"
  48. #include "warnless.h"
  49. #define _MPRINTF_REPLACE /* use our functions only */
  50. #include <curl/mprintf.h>
  51. #include "curl_memory.h"
  52. /* The last #include file should be: */
  53. #include "memdebug.h"
  54. /*
  55. Some hackish cast macros based on:
  56. http://library.gnome.org/devel/glib/unstable/glib-Type-Conversion-Macros.html
  57. */
  58. #ifndef GNUTLS_POINTER_TO_INT_CAST
  59. #define GNUTLS_POINTER_TO_INT_CAST(p) ((int) (long) (p))
  60. #endif
  61. #ifndef GNUTLS_INT_TO_POINTER_CAST
  62. #define GNUTLS_INT_TO_POINTER_CAST(i) ((void*) (long) (i))
  63. #endif
  64. /* Enable GnuTLS debugging by defining GTLSDEBUG */
  65. /*#define GTLSDEBUG */
  66. #ifdef GTLSDEBUG
  67. static void tls_log_func(int level, const char *str)
  68. {
  69. fprintf(stderr, "|<%d>| %s", level, str);
  70. }
  71. #endif
  72. static bool gtls_inited = FALSE;
  73. #if defined(GNUTLS_VERSION_NUMBER)
  74. # if (GNUTLS_VERSION_NUMBER >= 0x020c00)
  75. # undef gnutls_transport_set_lowat
  76. # define gnutls_transport_set_lowat(A,B) Curl_nop_stmt
  77. # define USE_GNUTLS_PRIORITY_SET_DIRECT 1
  78. # endif
  79. # if (GNUTLS_VERSION_NUMBER >= 0x020c03)
  80. # define GNUTLS_MAPS_WINSOCK_ERRORS 1
  81. # endif
  82. # ifdef USE_NGHTTP2
  83. # undef HAS_ALPN
  84. # if (GNUTLS_VERSION_NUMBER >= 0x030200)
  85. # define HAS_ALPN
  86. # endif
  87. # endif
  88. #endif
  89. /*
  90. * Custom push and pull callback functions used by GNU TLS to read and write
  91. * to the socket. These functions are simple wrappers to send() and recv()
  92. * (although here using the sread/swrite macros as defined by
  93. * curl_setup_once.h).
  94. * We use custom functions rather than the GNU TLS defaults because it allows
  95. * us to get specific about the fourth "flags" argument, and to use arbitrary
  96. * private data with gnutls_transport_set_ptr if we wish.
  97. *
  98. * When these custom push and pull callbacks fail, GNU TLS checks its own
  99. * session-specific error variable, and when not set also its own global
  100. * errno variable, in order to take appropriate action. GNU TLS does not
  101. * require that the transport is actually a socket. This implies that for
  102. * Windows builds these callbacks should ideally set the session-specific
  103. * error variable using function gnutls_transport_set_errno or as a last
  104. * resort global errno variable using gnutls_transport_set_global_errno,
  105. * with a transport agnostic error value. This implies that some winsock
  106. * error translation must take place in these callbacks.
  107. *
  108. * Paragraph above applies to GNU TLS versions older than 2.12.3, since
  109. * this version GNU TLS does its own internal winsock error translation
  110. * using system_errno() function.
  111. */
  112. #if defined(USE_WINSOCK) && !defined(GNUTLS_MAPS_WINSOCK_ERRORS)
  113. # define gtls_EINTR 4
  114. # define gtls_EIO 5
  115. # define gtls_EAGAIN 11
  116. static int gtls_mapped_sockerrno(void)
  117. {
  118. switch(SOCKERRNO) {
  119. case WSAEWOULDBLOCK:
  120. return gtls_EAGAIN;
  121. case WSAEINTR:
  122. return gtls_EINTR;
  123. default:
  124. break;
  125. }
  126. return gtls_EIO;
  127. }
  128. #endif
  129. static ssize_t Curl_gtls_push(void *s, const void *buf, size_t len)
  130. {
  131. ssize_t ret = swrite(GNUTLS_POINTER_TO_INT_CAST(s), buf, len);
  132. #if defined(USE_WINSOCK) && !defined(GNUTLS_MAPS_WINSOCK_ERRORS)
  133. if(ret < 0)
  134. gnutls_transport_set_global_errno(gtls_mapped_sockerrno());
  135. #endif
  136. return ret;
  137. }
  138. static ssize_t Curl_gtls_pull(void *s, void *buf, size_t len)
  139. {
  140. ssize_t ret = sread(GNUTLS_POINTER_TO_INT_CAST(s), buf, len);
  141. #if defined(USE_WINSOCK) && !defined(GNUTLS_MAPS_WINSOCK_ERRORS)
  142. if(ret < 0)
  143. gnutls_transport_set_global_errno(gtls_mapped_sockerrno());
  144. #endif
  145. return ret;
  146. }
  147. /* Curl_gtls_init()
  148. *
  149. * Global GnuTLS init, called from Curl_ssl_init(). This calls functions that
  150. * are not thread-safe and thus this function itself is not thread-safe and
  151. * must only be called from within curl_global_init() to keep the thread
  152. * situation under control!
  153. */
  154. int Curl_gtls_init(void)
  155. {
  156. int ret = 1;
  157. if(!gtls_inited) {
  158. ret = gnutls_global_init()?0:1;
  159. #ifdef GTLSDEBUG
  160. gnutls_global_set_log_function(tls_log_func);
  161. gnutls_global_set_log_level(2);
  162. #endif
  163. gtls_inited = TRUE;
  164. }
  165. return ret;
  166. }
  167. int Curl_gtls_cleanup(void)
  168. {
  169. if(gtls_inited) {
  170. gnutls_global_deinit();
  171. gtls_inited = FALSE;
  172. }
  173. return 1;
  174. }
  175. static void showtime(struct SessionHandle *data,
  176. const char *text,
  177. time_t stamp)
  178. {
  179. struct tm buffer;
  180. const struct tm *tm = &buffer;
  181. CURLcode result = Curl_gmtime(stamp, &buffer);
  182. if(result)
  183. return;
  184. snprintf(data->state.buffer,
  185. BUFSIZE,
  186. "\t %s: %s, %02d %s %4d %02d:%02d:%02d GMT\n",
  187. text,
  188. Curl_wkday[tm->tm_wday?tm->tm_wday-1:6],
  189. tm->tm_mday,
  190. Curl_month[tm->tm_mon],
  191. tm->tm_year + 1900,
  192. tm->tm_hour,
  193. tm->tm_min,
  194. tm->tm_sec);
  195. infof(data, "%s\n", data->state.buffer);
  196. }
  197. static gnutls_datum_t load_file (const char *file)
  198. {
  199. FILE *f;
  200. gnutls_datum_t loaded_file = { NULL, 0 };
  201. long filelen;
  202. void *ptr;
  203. if(!(f = fopen(file, "r")))
  204. return loaded_file;
  205. if(fseek(f, 0, SEEK_END) != 0
  206. || (filelen = ftell(f)) < 0
  207. || fseek(f, 0, SEEK_SET) != 0
  208. || !(ptr = malloc((size_t)filelen)))
  209. goto out;
  210. if(fread(ptr, 1, (size_t)filelen, f) < (size_t)filelen) {
  211. free(ptr);
  212. goto out;
  213. }
  214. loaded_file.data = ptr;
  215. loaded_file.size = (unsigned int)filelen;
  216. out:
  217. fclose(f);
  218. return loaded_file;
  219. }
  220. static void unload_file(gnutls_datum_t data) {
  221. free(data.data);
  222. }
  223. /* this function does a SSL/TLS (re-)handshake */
  224. static CURLcode handshake(struct connectdata *conn,
  225. int sockindex,
  226. bool duringconnect,
  227. bool nonblocking)
  228. {
  229. struct SessionHandle *data = conn->data;
  230. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  231. gnutls_session_t session = conn->ssl[sockindex].session;
  232. curl_socket_t sockfd = conn->sock[sockindex];
  233. long timeout_ms;
  234. int rc;
  235. int what;
  236. for(;;) {
  237. /* check allowed time left */
  238. timeout_ms = Curl_timeleft(data, NULL, duringconnect);
  239. if(timeout_ms < 0) {
  240. /* no need to continue if time already is up */
  241. failf(data, "SSL connection timeout");
  242. return CURLE_OPERATION_TIMEDOUT;
  243. }
  244. /* if ssl is expecting something, check if it's available. */
  245. if(connssl->connecting_state == ssl_connect_2_reading
  246. || connssl->connecting_state == ssl_connect_2_writing) {
  247. curl_socket_t writefd = ssl_connect_2_writing==
  248. connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
  249. curl_socket_t readfd = ssl_connect_2_reading==
  250. connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
  251. what = Curl_socket_ready(readfd, writefd,
  252. nonblocking?0:
  253. timeout_ms?timeout_ms:1000);
  254. if(what < 0) {
  255. /* fatal error */
  256. failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
  257. return CURLE_SSL_CONNECT_ERROR;
  258. }
  259. else if(0 == what) {
  260. if(nonblocking)
  261. return CURLE_OK;
  262. else if(timeout_ms) {
  263. /* timeout */
  264. failf(data, "SSL connection timeout at %ld", timeout_ms);
  265. return CURLE_OPERATION_TIMEDOUT;
  266. }
  267. }
  268. /* socket is readable or writable */
  269. }
  270. rc = gnutls_handshake(session);
  271. if((rc == GNUTLS_E_AGAIN) || (rc == GNUTLS_E_INTERRUPTED)) {
  272. connssl->connecting_state =
  273. gnutls_record_get_direction(session)?
  274. ssl_connect_2_writing:ssl_connect_2_reading;
  275. continue;
  276. if(nonblocking)
  277. return CURLE_OK;
  278. }
  279. else if((rc < 0) && !gnutls_error_is_fatal(rc)) {
  280. const char *strerr = NULL;
  281. if(rc == GNUTLS_E_WARNING_ALERT_RECEIVED) {
  282. int alert = gnutls_alert_get(session);
  283. strerr = gnutls_alert_get_name(alert);
  284. }
  285. if(strerr == NULL)
  286. strerr = gnutls_strerror(rc);
  287. failf(data, "gnutls_handshake() warning: %s", strerr);
  288. }
  289. else if(rc < 0) {
  290. const char *strerr = NULL;
  291. if(rc == GNUTLS_E_FATAL_ALERT_RECEIVED) {
  292. int alert = gnutls_alert_get(session);
  293. strerr = gnutls_alert_get_name(alert);
  294. }
  295. if(strerr == NULL)
  296. strerr = gnutls_strerror(rc);
  297. failf(data, "gnutls_handshake() failed: %s", strerr);
  298. return CURLE_SSL_CONNECT_ERROR;
  299. }
  300. /* Reset our connect state machine */
  301. connssl->connecting_state = ssl_connect_1;
  302. return CURLE_OK;
  303. }
  304. }
  305. static gnutls_x509_crt_fmt_t do_file_type(const char *type)
  306. {
  307. if(!type || !type[0])
  308. return GNUTLS_X509_FMT_PEM;
  309. if(Curl_raw_equal(type, "PEM"))
  310. return GNUTLS_X509_FMT_PEM;
  311. if(Curl_raw_equal(type, "DER"))
  312. return GNUTLS_X509_FMT_DER;
  313. return -1;
  314. }
  315. static CURLcode
  316. gtls_connect_step1(struct connectdata *conn,
  317. int sockindex)
  318. {
  319. struct SessionHandle *data = conn->data;
  320. gnutls_session_t session;
  321. int rc;
  322. void *ssl_sessionid;
  323. size_t ssl_idsize;
  324. bool sni = TRUE; /* default is SNI enabled */
  325. #ifdef ENABLE_IPV6
  326. struct in6_addr addr;
  327. #else
  328. struct in_addr addr;
  329. #endif
  330. #ifndef USE_GNUTLS_PRIORITY_SET_DIRECT
  331. static const int cipher_priority[] = {
  332. /* These two ciphers were added to GnuTLS as late as ver. 3.0.1,
  333. but this code path is only ever used for ver. < 2.12.0.
  334. GNUTLS_CIPHER_AES_128_GCM,
  335. GNUTLS_CIPHER_AES_256_GCM,
  336. */
  337. GNUTLS_CIPHER_AES_128_CBC,
  338. GNUTLS_CIPHER_AES_256_CBC,
  339. GNUTLS_CIPHER_CAMELLIA_128_CBC,
  340. GNUTLS_CIPHER_CAMELLIA_256_CBC,
  341. GNUTLS_CIPHER_3DES_CBC,
  342. };
  343. static const int cert_type_priority[] = { GNUTLS_CRT_X509, 0 };
  344. static int protocol_priority[] = { 0, 0, 0, 0 };
  345. #else
  346. #define GNUTLS_CIPHERS "NORMAL:-ARCFOUR-128:-CTYPE-ALL:+CTYPE-X509"
  347. /* If GnuTLS was compiled without support for SRP it will error out if SRP is
  348. requested in the priority string, so treat it specially
  349. */
  350. #define GNUTLS_SRP "+SRP"
  351. const char* prioritylist;
  352. const char *err = NULL;
  353. #endif
  354. #ifdef HAS_ALPN
  355. int protocols_size = 2;
  356. gnutls_datum_t protocols[2];
  357. #endif
  358. if(conn->ssl[sockindex].state == ssl_connection_complete)
  359. /* to make us tolerant against being called more than once for the
  360. same connection */
  361. return CURLE_OK;
  362. if(!gtls_inited)
  363. Curl_gtls_init();
  364. /* GnuTLS only supports SSLv3 and TLSv1 */
  365. if(data->set.ssl.version == CURL_SSLVERSION_SSLv2) {
  366. failf(data, "GnuTLS does not support SSLv2");
  367. return CURLE_SSL_CONNECT_ERROR;
  368. }
  369. else if(data->set.ssl.version == CURL_SSLVERSION_SSLv3)
  370. sni = FALSE; /* SSLv3 has no SNI */
  371. /* allocate a cred struct */
  372. rc = gnutls_certificate_allocate_credentials(&conn->ssl[sockindex].cred);
  373. if(rc != GNUTLS_E_SUCCESS) {
  374. failf(data, "gnutls_cert_all_cred() failed: %s", gnutls_strerror(rc));
  375. return CURLE_SSL_CONNECT_ERROR;
  376. }
  377. #ifdef USE_TLS_SRP
  378. if(data->set.ssl.authtype == CURL_TLSAUTH_SRP) {
  379. infof(data, "Using TLS-SRP username: %s\n", data->set.ssl.username);
  380. rc = gnutls_srp_allocate_client_credentials(
  381. &conn->ssl[sockindex].srp_client_cred);
  382. if(rc != GNUTLS_E_SUCCESS) {
  383. failf(data, "gnutls_srp_allocate_client_cred() failed: %s",
  384. gnutls_strerror(rc));
  385. return CURLE_OUT_OF_MEMORY;
  386. }
  387. rc = gnutls_srp_set_client_credentials(conn->ssl[sockindex].
  388. srp_client_cred,
  389. data->set.ssl.username,
  390. data->set.ssl.password);
  391. if(rc != GNUTLS_E_SUCCESS) {
  392. failf(data, "gnutls_srp_set_client_cred() failed: %s",
  393. gnutls_strerror(rc));
  394. return CURLE_BAD_FUNCTION_ARGUMENT;
  395. }
  396. }
  397. #endif
  398. if(data->set.ssl.CAfile) {
  399. /* set the trusted CA cert bundle file */
  400. gnutls_certificate_set_verify_flags(conn->ssl[sockindex].cred,
  401. GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT);
  402. rc = gnutls_certificate_set_x509_trust_file(conn->ssl[sockindex].cred,
  403. data->set.ssl.CAfile,
  404. GNUTLS_X509_FMT_PEM);
  405. if(rc < 0) {
  406. infof(data, "error reading ca cert file %s (%s)\n",
  407. data->set.ssl.CAfile, gnutls_strerror(rc));
  408. if(data->set.ssl.verifypeer)
  409. return CURLE_SSL_CACERT_BADFILE;
  410. }
  411. else
  412. infof(data, "found %d certificates in %s\n",
  413. rc, data->set.ssl.CAfile);
  414. }
  415. if(data->set.ssl.CRLfile) {
  416. /* set the CRL list file */
  417. rc = gnutls_certificate_set_x509_crl_file(conn->ssl[sockindex].cred,
  418. data->set.ssl.CRLfile,
  419. GNUTLS_X509_FMT_PEM);
  420. if(rc < 0) {
  421. failf(data, "error reading crl file %s (%s)",
  422. data->set.ssl.CRLfile, gnutls_strerror(rc));
  423. return CURLE_SSL_CRL_BADFILE;
  424. }
  425. else
  426. infof(data, "found %d CRL in %s\n",
  427. rc, data->set.ssl.CRLfile);
  428. }
  429. /* Initialize TLS session as a client */
  430. rc = gnutls_init(&conn->ssl[sockindex].session, GNUTLS_CLIENT);
  431. if(rc != GNUTLS_E_SUCCESS) {
  432. failf(data, "gnutls_init() failed: %d", rc);
  433. return CURLE_SSL_CONNECT_ERROR;
  434. }
  435. /* convenient assign */
  436. session = conn->ssl[sockindex].session;
  437. if((0 == Curl_inet_pton(AF_INET, conn->host.name, &addr)) &&
  438. #ifdef ENABLE_IPV6
  439. (0 == Curl_inet_pton(AF_INET6, conn->host.name, &addr)) &&
  440. #endif
  441. sni &&
  442. (gnutls_server_name_set(session, GNUTLS_NAME_DNS, conn->host.name,
  443. strlen(conn->host.name)) < 0))
  444. infof(data, "WARNING: failed to configure server name indication (SNI) "
  445. "TLS extension\n");
  446. /* Use default priorities */
  447. rc = gnutls_set_default_priority(session);
  448. if(rc != GNUTLS_E_SUCCESS)
  449. return CURLE_SSL_CONNECT_ERROR;
  450. #ifndef USE_GNUTLS_PRIORITY_SET_DIRECT
  451. rc = gnutls_cipher_set_priority(session, cipher_priority);
  452. if(rc != GNUTLS_E_SUCCESS)
  453. return CURLE_SSL_CONNECT_ERROR;
  454. /* Sets the priority on the certificate types supported by gnutls. Priority
  455. is higher for types specified before others. After specifying the types
  456. you want, you must append a 0. */
  457. rc = gnutls_certificate_type_set_priority(session, cert_type_priority);
  458. if(rc != GNUTLS_E_SUCCESS)
  459. return CURLE_SSL_CONNECT_ERROR;
  460. if(data->set.ssl.cipher_list != NULL) {
  461. failf(data, "can't pass a custom cipher list to older GnuTLS"
  462. " versions");
  463. return CURLE_SSL_CONNECT_ERROR;
  464. }
  465. switch (data->set.ssl.version) {
  466. case CURL_SSLVERSION_SSLv3:
  467. protocol_priority[0] = GNUTLS_SSL3;
  468. break;
  469. case CURL_SSLVERSION_DEFAULT:
  470. case CURL_SSLVERSION_TLSv1:
  471. protocol_priority[0] = GNUTLS_TLS1_0;
  472. protocol_priority[1] = GNUTLS_TLS1_1;
  473. protocol_priority[2] = GNUTLS_TLS1_2;
  474. break;
  475. case CURL_SSLVERSION_TLSv1_0:
  476. protocol_priority[0] = GNUTLS_TLS1_0;
  477. break;
  478. case CURL_SSLVERSION_TLSv1_1:
  479. protocol_priority[0] = GNUTLS_TLS1_1;
  480. break;
  481. case CURL_SSLVERSION_TLSv1_2:
  482. protocol_priority[0] = GNUTLS_TLS1_2;
  483. break;
  484. case CURL_SSLVERSION_SSLv2:
  485. default:
  486. failf(data, "GnuTLS does not support SSLv2");
  487. return CURLE_SSL_CONNECT_ERROR;
  488. break;
  489. }
  490. rc = gnutls_protocol_set_priority(session, protocol_priority);
  491. if(rc != GNUTLS_E_SUCCESS) {
  492. failf(data, "Did you pass a valid GnuTLS cipher list?");
  493. return CURLE_SSL_CONNECT_ERROR;
  494. }
  495. #else
  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. switch (data->set.ssl.version) {
  500. case CURL_SSLVERSION_SSLv3:
  501. prioritylist = GNUTLS_CIPHERS ":-VERS-TLS-ALL:+VERS-SSL3.0";
  502. sni = false;
  503. break;
  504. case CURL_SSLVERSION_DEFAULT:
  505. case CURL_SSLVERSION_TLSv1:
  506. prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:" GNUTLS_SRP;
  507. break;
  508. case CURL_SSLVERSION_TLSv1_0:
  509. prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:"
  510. "+VERS-TLS1.0:" GNUTLS_SRP;
  511. break;
  512. case CURL_SSLVERSION_TLSv1_1:
  513. prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:"
  514. "+VERS-TLS1.1:" GNUTLS_SRP;
  515. break;
  516. case CURL_SSLVERSION_TLSv1_2:
  517. prioritylist = GNUTLS_CIPHERS ":-VERS-SSL3.0:-VERS-TLS-ALL:"
  518. "+VERS-TLS1.2:" GNUTLS_SRP;
  519. break;
  520. case CURL_SSLVERSION_SSLv2:
  521. default:
  522. failf(data, "GnuTLS does not support SSLv2");
  523. return CURLE_SSL_CONNECT_ERROR;
  524. break;
  525. }
  526. rc = gnutls_priority_set_direct(session, prioritylist, &err);
  527. if((rc == GNUTLS_E_INVALID_REQUEST) && err) {
  528. if(!strcmp(err, GNUTLS_SRP)) {
  529. /* This GnuTLS was probably compiled without support for SRP.
  530. * Note that fact and try again without it. */
  531. int validprioritylen = curlx_uztosi(err - prioritylist);
  532. char *prioritycopy = strdup(prioritylist);
  533. if(!prioritycopy)
  534. return CURLE_OUT_OF_MEMORY;
  535. infof(data, "This GnuTLS does not support SRP\n");
  536. if(validprioritylen)
  537. /* Remove the :+SRP */
  538. prioritycopy[validprioritylen - 1] = 0;
  539. rc = gnutls_priority_set_direct(session, prioritycopy, &err);
  540. free(prioritycopy);
  541. }
  542. }
  543. if(rc != GNUTLS_E_SUCCESS) {
  544. failf(data, "Error %d setting GnuTLS cipher list starting with %s",
  545. rc, err);
  546. return CURLE_SSL_CONNECT_ERROR;
  547. }
  548. #endif
  549. #ifdef HAS_ALPN
  550. if(data->set.httpversion == CURL_HTTP_VERSION_2_0) {
  551. if(data->set.ssl_enable_alpn) {
  552. protocols[0].data = NGHTTP2_PROTO_VERSION_ID;
  553. protocols[0].size = NGHTTP2_PROTO_VERSION_ID_LEN;
  554. protocols[1].data = ALPN_HTTP_1_1;
  555. protocols[1].size = ALPN_HTTP_1_1_LENGTH;
  556. gnutls_alpn_set_protocols(session, protocols, protocols_size, 0);
  557. infof(data, "ALPN, offering %s, %s\n", NGHTTP2_PROTO_VERSION_ID,
  558. ALPN_HTTP_1_1);
  559. }
  560. else {
  561. infof(data, "SSL, can't negotiate HTTP/2.0 without ALPN\n");
  562. }
  563. }
  564. #endif
  565. if(data->set.str[STRING_CERT]) {
  566. if(gnutls_certificate_set_x509_key_file(
  567. conn->ssl[sockindex].cred,
  568. data->set.str[STRING_CERT],
  569. data->set.str[STRING_KEY] ?
  570. data->set.str[STRING_KEY] : data->set.str[STRING_CERT],
  571. do_file_type(data->set.str[STRING_CERT_TYPE]) ) !=
  572. GNUTLS_E_SUCCESS) {
  573. failf(data, "error reading X.509 key or certificate file");
  574. return CURLE_SSL_CONNECT_ERROR;
  575. }
  576. }
  577. #ifdef USE_TLS_SRP
  578. /* put the credentials to the current session */
  579. if(data->set.ssl.authtype == CURL_TLSAUTH_SRP) {
  580. rc = gnutls_credentials_set(session, GNUTLS_CRD_SRP,
  581. conn->ssl[sockindex].srp_client_cred);
  582. if(rc != GNUTLS_E_SUCCESS)
  583. failf(data, "gnutls_credentials_set() failed: %s", gnutls_strerror(rc));
  584. }
  585. else
  586. #endif
  587. rc = gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE,
  588. conn->ssl[sockindex].cred);
  589. /* set the connection handle (file descriptor for the socket) */
  590. gnutls_transport_set_ptr(session,
  591. GNUTLS_INT_TO_POINTER_CAST(conn->sock[sockindex]));
  592. /* register callback functions to send and receive data. */
  593. gnutls_transport_set_push_function(session, Curl_gtls_push);
  594. gnutls_transport_set_pull_function(session, Curl_gtls_pull);
  595. /* lowat must be set to zero when using custom push and pull functions. */
  596. gnutls_transport_set_lowat(session, 0);
  597. /* This might be a reconnect, so we check for a session ID in the cache
  598. to speed up things */
  599. if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, &ssl_idsize)) {
  600. /* we got a session id, use it! */
  601. gnutls_session_set_data(session, ssl_sessionid, ssl_idsize);
  602. /* Informational message */
  603. infof (data, "SSL re-using session ID\n");
  604. }
  605. return CURLE_OK;
  606. }
  607. static Curl_recv gtls_recv;
  608. static Curl_send gtls_send;
  609. static CURLcode
  610. gtls_connect_step3(struct connectdata *conn,
  611. int sockindex)
  612. {
  613. unsigned int cert_list_size;
  614. const gnutls_datum_t *chainp;
  615. unsigned int verify_status;
  616. gnutls_x509_crt_t x509_cert,x509_issuer;
  617. gnutls_datum_t issuerp;
  618. char certbuf[256] = ""; /* big enough? */
  619. size_t size;
  620. unsigned int algo;
  621. unsigned int bits;
  622. time_t certclock;
  623. const char *ptr;
  624. struct SessionHandle *data = conn->data;
  625. gnutls_session_t session = conn->ssl[sockindex].session;
  626. int rc;
  627. int incache;
  628. void *ssl_sessionid;
  629. #ifdef HAS_ALPN
  630. gnutls_datum_t proto;
  631. #endif
  632. CURLcode result = CURLE_OK;
  633. /* This function will return the peer's raw certificate (chain) as sent by
  634. the peer. These certificates are in raw format (DER encoded for
  635. X.509). In case of a X.509 then a certificate list may be present. The
  636. first certificate in the list is the peer's certificate, following the
  637. issuer's certificate, then the issuer's issuer etc. */
  638. chainp = gnutls_certificate_get_peers(session, &cert_list_size);
  639. if(!chainp) {
  640. if(data->set.ssl.verifypeer ||
  641. data->set.ssl.verifyhost ||
  642. data->set.ssl.issuercert) {
  643. #ifdef USE_TLS_SRP
  644. if(data->set.ssl.authtype == CURL_TLSAUTH_SRP
  645. && data->set.ssl.username != NULL
  646. && !data->set.ssl.verifypeer
  647. && gnutls_cipher_get(session)) {
  648. /* no peer cert, but auth is ok if we have SRP user and cipher and no
  649. peer verify */
  650. }
  651. else {
  652. #endif
  653. failf(data, "failed to get server cert");
  654. return CURLE_PEER_FAILED_VERIFICATION;
  655. #ifdef USE_TLS_SRP
  656. }
  657. #endif
  658. }
  659. infof(data, "\t common name: WARNING couldn't obtain\n");
  660. }
  661. if(data->set.ssl.verifypeer) {
  662. /* This function will try to verify the peer's certificate and return its
  663. status (trusted, invalid etc.). The value of status should be one or
  664. more of the gnutls_certificate_status_t enumerated elements bitwise
  665. or'd. To avoid denial of service attacks some default upper limits
  666. regarding the certificate key size and chain size are set. To override
  667. them use gnutls_certificate_set_verify_limits(). */
  668. rc = gnutls_certificate_verify_peers2(session, &verify_status);
  669. if(rc < 0) {
  670. failf(data, "server cert verify failed: %d", rc);
  671. return CURLE_SSL_CONNECT_ERROR;
  672. }
  673. /* verify_status is a bitmask of gnutls_certificate_status bits */
  674. if(verify_status & GNUTLS_CERT_INVALID) {
  675. if(data->set.ssl.verifypeer) {
  676. failf(data, "server certificate verification failed. CAfile: %s "
  677. "CRLfile: %s", data->set.ssl.CAfile?data->set.ssl.CAfile:"none",
  678. data->set.ssl.CRLfile?data->set.ssl.CRLfile:"none");
  679. return CURLE_SSL_CACERT;
  680. }
  681. else
  682. infof(data, "\t server certificate verification FAILED\n");
  683. }
  684. else
  685. infof(data, "\t server certificate verification OK\n");
  686. }
  687. else
  688. infof(data, "\t server certificate verification SKIPPED\n");
  689. /* initialize an X.509 certificate structure. */
  690. gnutls_x509_crt_init(&x509_cert);
  691. if(chainp)
  692. /* convert the given DER or PEM encoded Certificate to the native
  693. gnutls_x509_crt_t format */
  694. gnutls_x509_crt_import(x509_cert, chainp, GNUTLS_X509_FMT_DER);
  695. if(data->set.ssl.issuercert) {
  696. gnutls_x509_crt_init(&x509_issuer);
  697. issuerp = load_file(data->set.ssl.issuercert);
  698. gnutls_x509_crt_import(x509_issuer, &issuerp, GNUTLS_X509_FMT_PEM);
  699. rc = gnutls_x509_crt_check_issuer(x509_cert,x509_issuer);
  700. unload_file(issuerp);
  701. if(rc <= 0) {
  702. failf(data, "server certificate issuer check failed (IssuerCert: %s)",
  703. data->set.ssl.issuercert?data->set.ssl.issuercert:"none");
  704. return CURLE_SSL_ISSUER_ERROR;
  705. }
  706. infof(data,"\t server certificate issuer check OK (Issuer Cert: %s)\n",
  707. data->set.ssl.issuercert?data->set.ssl.issuercert:"none");
  708. }
  709. size=sizeof(certbuf);
  710. rc = gnutls_x509_crt_get_dn_by_oid(x509_cert, GNUTLS_OID_X520_COMMON_NAME,
  711. 0, /* the first and only one */
  712. FALSE,
  713. certbuf,
  714. &size);
  715. if(rc) {
  716. infof(data, "error fetching CN from cert:%s\n",
  717. gnutls_strerror(rc));
  718. }
  719. /* This function will check if the given certificate's subject matches the
  720. given hostname. This is a basic implementation of the matching described
  721. in RFC2818 (HTTPS), which takes into account wildcards, and the subject
  722. alternative name PKIX extension. Returns non zero on success, and zero on
  723. failure. */
  724. rc = gnutls_x509_crt_check_hostname(x509_cert, conn->host.name);
  725. #if GNUTLS_VERSION_NUMBER < 0x030306
  726. /* Before 3.3.6, gnutls_x509_crt_check_hostname() didn't check IP
  727. addresses. */
  728. if(!rc) {
  729. #ifdef ENABLE_IPV6
  730. #define use_addr in6_addr
  731. #else
  732. #define use_addr in_addr
  733. #endif
  734. unsigned char addrbuf[sizeof(struct use_addr)];
  735. unsigned char certaddr[sizeof(struct use_addr)];
  736. size_t addrlen = 0, certaddrlen;
  737. int i;
  738. int ret = 0;
  739. if(Curl_inet_pton(AF_INET, conn->host.name, addrbuf) > 0)
  740. addrlen = 4;
  741. #ifdef ENABLE_IPV6
  742. else if(Curl_inet_pton(AF_INET6, conn->host.name, addrbuf) > 0)
  743. addrlen = 16;
  744. #endif
  745. if(addrlen) {
  746. for(i=0; ; i++) {
  747. certaddrlen = sizeof(certaddr);
  748. ret = gnutls_x509_crt_get_subject_alt_name(x509_cert, i, certaddr,
  749. &certaddrlen, NULL);
  750. /* If this happens, it wasn't an IP address. */
  751. if(ret == GNUTLS_E_SHORT_MEMORY_BUFFER)
  752. continue;
  753. if(ret < 0)
  754. break;
  755. if(ret != GNUTLS_SAN_IPADDRESS)
  756. continue;
  757. if(certaddrlen == addrlen && !memcmp(addrbuf, certaddr, addrlen)) {
  758. rc = 1;
  759. break;
  760. }
  761. }
  762. }
  763. }
  764. #endif
  765. if(!rc) {
  766. if(data->set.ssl.verifyhost) {
  767. failf(data, "SSL: certificate subject name (%s) does not match "
  768. "target host name '%s'", certbuf, conn->host.dispname);
  769. gnutls_x509_crt_deinit(x509_cert);
  770. return CURLE_PEER_FAILED_VERIFICATION;
  771. }
  772. else
  773. infof(data, "\t common name: %s (does not match '%s')\n",
  774. certbuf, conn->host.dispname);
  775. }
  776. else
  777. infof(data, "\t common name: %s (matched)\n", certbuf);
  778. /* Check for time-based validity */
  779. certclock = gnutls_x509_crt_get_expiration_time(x509_cert);
  780. if(certclock == (time_t)-1) {
  781. if(data->set.ssl.verifypeer) {
  782. failf(data, "server cert expiration date verify failed");
  783. return CURLE_SSL_CONNECT_ERROR;
  784. }
  785. else
  786. infof(data, "\t server certificate expiration date verify FAILED\n");
  787. }
  788. else {
  789. if(certclock < time(NULL)) {
  790. if(data->set.ssl.verifypeer) {
  791. failf(data, "server certificate expiration date has passed.");
  792. return CURLE_PEER_FAILED_VERIFICATION;
  793. }
  794. else
  795. infof(data, "\t server certificate expiration date FAILED\n");
  796. }
  797. else
  798. infof(data, "\t server certificate expiration date OK\n");
  799. }
  800. certclock = gnutls_x509_crt_get_activation_time(x509_cert);
  801. if(certclock == (time_t)-1) {
  802. if(data->set.ssl.verifypeer) {
  803. failf(data, "server cert activation date verify failed");
  804. return CURLE_SSL_CONNECT_ERROR;
  805. }
  806. else
  807. infof(data, "\t server certificate activation date verify FAILED\n");
  808. }
  809. else {
  810. if(certclock > time(NULL)) {
  811. if(data->set.ssl.verifypeer) {
  812. failf(data, "server certificate not activated yet.");
  813. return CURLE_PEER_FAILED_VERIFICATION;
  814. }
  815. else
  816. infof(data, "\t server certificate activation date FAILED\n");
  817. }
  818. else
  819. infof(data, "\t server certificate activation date OK\n");
  820. }
  821. /* Show:
  822. - ciphers used
  823. - subject
  824. - start date
  825. - expire date
  826. - common name
  827. - issuer
  828. */
  829. /* public key algorithm's parameters */
  830. algo = gnutls_x509_crt_get_pk_algorithm(x509_cert, &bits);
  831. infof(data, "\t certificate public key: %s\n",
  832. gnutls_pk_algorithm_get_name(algo));
  833. /* version of the X.509 certificate. */
  834. infof(data, "\t certificate version: #%d\n",
  835. gnutls_x509_crt_get_version(x509_cert));
  836. size = sizeof(certbuf);
  837. gnutls_x509_crt_get_dn(x509_cert, certbuf, &size);
  838. infof(data, "\t subject: %s\n", certbuf);
  839. certclock = gnutls_x509_crt_get_activation_time(x509_cert);
  840. showtime(data, "start date", certclock);
  841. certclock = gnutls_x509_crt_get_expiration_time(x509_cert);
  842. showtime(data, "expire date", certclock);
  843. size = sizeof(certbuf);
  844. gnutls_x509_crt_get_issuer_dn(x509_cert, certbuf, &size);
  845. infof(data, "\t issuer: %s\n", certbuf);
  846. gnutls_x509_crt_deinit(x509_cert);
  847. /* compression algorithm (if any) */
  848. ptr = gnutls_compression_get_name(gnutls_compression_get(session));
  849. /* the *_get_name() says "NULL" if GNUTLS_COMP_NULL is returned */
  850. infof(data, "\t compression: %s\n", ptr);
  851. /* the name of the cipher used. ie 3DES. */
  852. ptr = gnutls_cipher_get_name(gnutls_cipher_get(session));
  853. infof(data, "\t cipher: %s\n", ptr);
  854. /* the MAC algorithms name. ie SHA1 */
  855. ptr = gnutls_mac_get_name(gnutls_mac_get(session));
  856. infof(data, "\t MAC: %s\n", ptr);
  857. #ifdef HAS_ALPN
  858. if(data->set.ssl_enable_alpn) {
  859. rc = gnutls_alpn_get_selected_protocol(session, &proto);
  860. if(rc == 0) {
  861. infof(data, "ALPN, server accepted to use %.*s\n", proto.size,
  862. proto.data);
  863. if(proto.size == NGHTTP2_PROTO_VERSION_ID_LEN &&
  864. memcmp(NGHTTP2_PROTO_VERSION_ID, proto.data,
  865. NGHTTP2_PROTO_VERSION_ID_LEN) == 0) {
  866. conn->negnpn = NPN_HTTP2;
  867. }
  868. else if(proto.size == ALPN_HTTP_1_1_LENGTH && memcmp(ALPN_HTTP_1_1,
  869. proto.data, ALPN_HTTP_1_1_LENGTH) == 0) {
  870. conn->negnpn = NPN_HTTP1_1;
  871. }
  872. }
  873. else {
  874. infof(data, "ALPN, server did not agree to a protocol\n");
  875. }
  876. }
  877. #endif
  878. conn->ssl[sockindex].state = ssl_connection_complete;
  879. conn->recv[sockindex] = gtls_recv;
  880. conn->send[sockindex] = gtls_send;
  881. {
  882. /* we always unconditionally get the session id here, as even if we
  883. already got it from the cache and asked to use it in the connection, it
  884. might've been rejected and then a new one is in use now and we need to
  885. detect that. */
  886. void *connect_sessionid;
  887. size_t connect_idsize = 0;
  888. /* get the session ID data size */
  889. gnutls_session_get_data(session, NULL, &connect_idsize);
  890. connect_sessionid = malloc(connect_idsize); /* get a buffer for it */
  891. if(connect_sessionid) {
  892. /* extract session ID to the allocated buffer */
  893. gnutls_session_get_data(session, connect_sessionid, &connect_idsize);
  894. incache = !(Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL));
  895. if(incache) {
  896. /* there was one before in the cache, so instead of risking that the
  897. previous one was rejected, we just kill that and store the new */
  898. Curl_ssl_delsessionid(conn, ssl_sessionid);
  899. }
  900. /* store this session id */
  901. result = Curl_ssl_addsessionid(conn, connect_sessionid, connect_idsize);
  902. if(result) {
  903. free(connect_sessionid);
  904. result = CURLE_OUT_OF_MEMORY;
  905. }
  906. }
  907. else
  908. result = CURLE_OUT_OF_MEMORY;
  909. }
  910. return result;
  911. }
  912. /*
  913. * This function is called after the TCP connect has completed. Setup the TLS
  914. * layer and do all necessary magic.
  915. */
  916. /* We use connssl->connecting_state to keep track of the connection status;
  917. there are three states: 'ssl_connect_1' (not started yet or complete),
  918. 'ssl_connect_2_reading' (waiting for data from server), and
  919. 'ssl_connect_2_writing' (waiting to be able to write).
  920. */
  921. static CURLcode
  922. gtls_connect_common(struct connectdata *conn,
  923. int sockindex,
  924. bool nonblocking,
  925. bool *done)
  926. {
  927. int rc;
  928. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  929. /* Initiate the connection, if not already done */
  930. if(ssl_connect_1==connssl->connecting_state) {
  931. rc = gtls_connect_step1 (conn, sockindex);
  932. if(rc)
  933. return rc;
  934. }
  935. rc = handshake(conn, sockindex, TRUE, nonblocking);
  936. if(rc)
  937. /* handshake() sets its own error message with failf() */
  938. return rc;
  939. /* Finish connecting once the handshake is done */
  940. if(ssl_connect_1==connssl->connecting_state) {
  941. rc = gtls_connect_step3(conn, sockindex);
  942. if(rc)
  943. return rc;
  944. }
  945. *done = ssl_connect_1==connssl->connecting_state;
  946. return CURLE_OK;
  947. }
  948. CURLcode
  949. Curl_gtls_connect_nonblocking(struct connectdata *conn,
  950. int sockindex,
  951. bool *done)
  952. {
  953. return gtls_connect_common(conn, sockindex, TRUE, done);
  954. }
  955. CURLcode
  956. Curl_gtls_connect(struct connectdata *conn,
  957. int sockindex)
  958. {
  959. CURLcode retcode;
  960. bool done = FALSE;
  961. retcode = gtls_connect_common(conn, sockindex, FALSE, &done);
  962. if(retcode)
  963. return retcode;
  964. DEBUGASSERT(done);
  965. return CURLE_OK;
  966. }
  967. static ssize_t gtls_send(struct connectdata *conn,
  968. int sockindex,
  969. const void *mem,
  970. size_t len,
  971. CURLcode *curlcode)
  972. {
  973. ssize_t rc = gnutls_record_send(conn->ssl[sockindex].session, mem, len);
  974. if(rc < 0 ) {
  975. *curlcode = (rc == GNUTLS_E_AGAIN)
  976. ? CURLE_AGAIN
  977. : CURLE_SEND_ERROR;
  978. rc = -1;
  979. }
  980. return rc;
  981. }
  982. void Curl_gtls_close_all(struct SessionHandle *data)
  983. {
  984. /* FIX: make the OpenSSL code more generic and use parts of it here */
  985. (void)data;
  986. }
  987. static void close_one(struct connectdata *conn,
  988. int idx)
  989. {
  990. if(conn->ssl[idx].session) {
  991. gnutls_bye(conn->ssl[idx].session, GNUTLS_SHUT_RDWR);
  992. gnutls_deinit(conn->ssl[idx].session);
  993. conn->ssl[idx].session = NULL;
  994. }
  995. if(conn->ssl[idx].cred) {
  996. gnutls_certificate_free_credentials(conn->ssl[idx].cred);
  997. conn->ssl[idx].cred = NULL;
  998. }
  999. #ifdef USE_TLS_SRP
  1000. if(conn->ssl[idx].srp_client_cred) {
  1001. gnutls_srp_free_client_credentials(conn->ssl[idx].srp_client_cred);
  1002. conn->ssl[idx].srp_client_cred = NULL;
  1003. }
  1004. #endif
  1005. }
  1006. void Curl_gtls_close(struct connectdata *conn, int sockindex)
  1007. {
  1008. close_one(conn, sockindex);
  1009. }
  1010. /*
  1011. * This function is called to shut down the SSL layer but keep the
  1012. * socket open (CCC - Clear Command Channel)
  1013. */
  1014. int Curl_gtls_shutdown(struct connectdata *conn, int sockindex)
  1015. {
  1016. ssize_t result;
  1017. int retval = 0;
  1018. struct SessionHandle *data = conn->data;
  1019. int done = 0;
  1020. char buf[120];
  1021. /* This has only been tested on the proftpd server, and the mod_tls code
  1022. sends a close notify alert without waiting for a close notify alert in
  1023. response. Thus we wait for a close notify alert from the server, but
  1024. we do not send one. Let's hope other servers do the same... */
  1025. if(data->set.ftp_ccc == CURLFTPSSL_CCC_ACTIVE)
  1026. gnutls_bye(conn->ssl[sockindex].session, GNUTLS_SHUT_WR);
  1027. if(conn->ssl[sockindex].session) {
  1028. while(!done) {
  1029. int what = Curl_socket_ready(conn->sock[sockindex],
  1030. CURL_SOCKET_BAD, SSL_SHUTDOWN_TIMEOUT);
  1031. if(what > 0) {
  1032. /* Something to read, let's do it and hope that it is the close
  1033. notify alert from the server */
  1034. result = gnutls_record_recv(conn->ssl[sockindex].session,
  1035. buf, sizeof(buf));
  1036. switch(result) {
  1037. case 0:
  1038. /* This is the expected response. There was no data but only
  1039. the close notify alert */
  1040. done = 1;
  1041. break;
  1042. case GNUTLS_E_AGAIN:
  1043. case GNUTLS_E_INTERRUPTED:
  1044. infof(data, "GNUTLS_E_AGAIN || GNUTLS_E_INTERRUPTED\n");
  1045. break;
  1046. default:
  1047. retval = -1;
  1048. done = 1;
  1049. break;
  1050. }
  1051. }
  1052. else if(0 == what) {
  1053. /* timeout */
  1054. failf(data, "SSL shutdown timeout");
  1055. done = 1;
  1056. break;
  1057. }
  1058. else {
  1059. /* anything that gets here is fatally bad */
  1060. failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
  1061. retval = -1;
  1062. done = 1;
  1063. }
  1064. }
  1065. gnutls_deinit(conn->ssl[sockindex].session);
  1066. }
  1067. gnutls_certificate_free_credentials(conn->ssl[sockindex].cred);
  1068. #ifdef USE_TLS_SRP
  1069. if(data->set.ssl.authtype == CURL_TLSAUTH_SRP
  1070. && data->set.ssl.username != NULL)
  1071. gnutls_srp_free_client_credentials(conn->ssl[sockindex].srp_client_cred);
  1072. #endif
  1073. conn->ssl[sockindex].cred = NULL;
  1074. conn->ssl[sockindex].session = NULL;
  1075. return retval;
  1076. }
  1077. static ssize_t gtls_recv(struct connectdata *conn, /* connection data */
  1078. int num, /* socketindex */
  1079. char *buf, /* store read data here */
  1080. size_t buffersize, /* max amount to read */
  1081. CURLcode *curlcode)
  1082. {
  1083. ssize_t ret;
  1084. ret = gnutls_record_recv(conn->ssl[num].session, buf, buffersize);
  1085. if((ret == GNUTLS_E_AGAIN) || (ret == GNUTLS_E_INTERRUPTED)) {
  1086. *curlcode = CURLE_AGAIN;
  1087. return -1;
  1088. }
  1089. if(ret == GNUTLS_E_REHANDSHAKE) {
  1090. /* BLOCKING call, this is bad but a work-around for now. Fixing this "the
  1091. proper way" takes a whole lot of work. */
  1092. CURLcode rc = handshake(conn, num, FALSE, FALSE);
  1093. if(rc)
  1094. /* handshake() writes error message on its own */
  1095. *curlcode = rc;
  1096. else
  1097. *curlcode = CURLE_AGAIN; /* then return as if this was a wouldblock */
  1098. return -1;
  1099. }
  1100. if(ret < 0) {
  1101. failf(conn->data, "GnuTLS recv error (%d): %s",
  1102. (int)ret, gnutls_strerror((int)ret));
  1103. *curlcode = CURLE_RECV_ERROR;
  1104. return -1;
  1105. }
  1106. return ret;
  1107. }
  1108. void Curl_gtls_session_free(void *ptr)
  1109. {
  1110. free(ptr);
  1111. }
  1112. size_t Curl_gtls_version(char *buffer, size_t size)
  1113. {
  1114. return snprintf(buffer, size, "GnuTLS/%s", gnutls_check_version(NULL));
  1115. }
  1116. int Curl_gtls_seed(struct SessionHandle *data)
  1117. {
  1118. /* we have the "SSL is seeded" boolean static to prevent multiple
  1119. time-consuming seedings in vain */
  1120. static bool ssl_seeded = FALSE;
  1121. /* Quickly add a bit of entropy */
  1122. #ifndef USE_GNUTLS_NETTLE
  1123. gcry_fast_random_poll();
  1124. #endif
  1125. if(!ssl_seeded || data->set.str[STRING_SSL_RANDOM_FILE] ||
  1126. data->set.str[STRING_SSL_EGDSOCKET]) {
  1127. /* TODO: to a good job seeding the RNG
  1128. This may involve the gcry_control function and these options:
  1129. GCRYCTL_SET_RANDOM_SEED_FILE
  1130. GCRYCTL_SET_RNDEGD_SOCKET
  1131. */
  1132. ssl_seeded = TRUE;
  1133. }
  1134. return 0;
  1135. }
  1136. void Curl_gtls_random(struct SessionHandle *data,
  1137. unsigned char *entropy,
  1138. size_t length)
  1139. {
  1140. #if defined(USE_GNUTLS_NETTLE)
  1141. (void)data;
  1142. gnutls_rnd(GNUTLS_RND_RANDOM, entropy, length);
  1143. #elif defined(USE_GNUTLS)
  1144. Curl_gtls_seed(data); /* Initiate the seed if not already done */
  1145. gcry_randomize(entropy, length, GCRY_STRONG_RANDOM);
  1146. #endif
  1147. }
  1148. void Curl_gtls_md5sum(unsigned char *tmp, /* input */
  1149. size_t tmplen,
  1150. unsigned char *md5sum, /* output */
  1151. size_t md5len)
  1152. {
  1153. #if defined(USE_GNUTLS_NETTLE)
  1154. struct md5_ctx MD5pw;
  1155. md5_init(&MD5pw);
  1156. md5_update(&MD5pw, (unsigned int)tmplen, tmp);
  1157. md5_digest(&MD5pw, (unsigned int)md5len, md5sum);
  1158. #elif defined(USE_GNUTLS)
  1159. gcry_md_hd_t MD5pw;
  1160. gcry_md_open(&MD5pw, GCRY_MD_MD5, 0);
  1161. gcry_md_write(MD5pw, tmp, tmplen);
  1162. memcpy(md5sum, gcry_md_read (MD5pw, 0), md5len);
  1163. gcry_md_close(MD5pw);
  1164. #endif
  1165. }
  1166. #endif /* USE_GNUTLS */