诸暨麻将添加redis
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1120 lines
34 KiB

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