gtls.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2005, 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. * $Id$
  22. ***************************************************************************/
  23. /*
  24. * Source file for all GnuTLS-specific code for the TLS/SSL layer. No code
  25. * but sslgen.c should ever call or use these functions.
  26. *
  27. * Note: don't use the GnuTLS' *_t variable type names in this source code,
  28. * since they were not present in 1.0.X.
  29. */
  30. #include "setup.h"
  31. #ifdef USE_GNUTLS
  32. #include <gnutls/gnutls.h>
  33. #include <gnutls/x509.h>
  34. #include <string.h>
  35. #include <stdlib.h>
  36. #include <ctype.h>
  37. #ifdef HAVE_SYS_TYPES_H
  38. #include <sys/types.h>
  39. #endif
  40. #ifdef HAVE_SYS_SOCKET_H
  41. #include <sys/socket.h>
  42. #endif
  43. #include "urldata.h"
  44. #include "sendf.h"
  45. #include "gtls.h"
  46. #include "sslgen.h"
  47. #include "parsedate.h"
  48. #include "connect.h" /* for the connect timeout */
  49. #include "select.h"
  50. #define _MPRINTF_REPLACE /* use our functions only */
  51. #include <curl/mprintf.h>
  52. #include "memory.h"
  53. /* The last #include file should be: */
  54. #include "memdebug.h"
  55. /* Enable GnuTLS debugging by defining GTLSDEBUG */
  56. /*#define GTLSDEBUG */
  57. #ifdef GTLSDEBUG
  58. static void tls_log_func(int level, const char *str)
  59. {
  60. fprintf(stderr, "|<%d>| %s", level, str);
  61. }
  62. #endif
  63. /* Global GnuTLS init, called from Curl_ssl_init() */
  64. int Curl_gtls_init(void)
  65. {
  66. gnutls_global_init();
  67. #ifdef GTLSDEBUG
  68. gnutls_global_set_log_function(tls_log_func);
  69. gnutls_global_set_log_level(2);
  70. #endif
  71. return 1;
  72. }
  73. int Curl_gtls_cleanup(void)
  74. {
  75. gnutls_global_deinit();
  76. return 1;
  77. }
  78. static void showtime(struct SessionHandle *data,
  79. const char *text,
  80. time_t stamp)
  81. {
  82. struct tm *tm;
  83. #ifdef HAVE_GMTIME_R
  84. struct tm buffer;
  85. tm = (struct tm *)gmtime_r(&stamp, &buffer);
  86. #else
  87. tm = gmtime(&stamp);
  88. #endif
  89. snprintf(data->state.buffer,
  90. BUFSIZE,
  91. "\t %s: %s, %02d %s %4d %02d:%02d:%02d GMT\n",
  92. text,
  93. Curl_wkday[tm->tm_wday?tm->tm_wday-1:6],
  94. tm->tm_mday,
  95. Curl_month[tm->tm_mon],
  96. tm->tm_year + 1900,
  97. tm->tm_hour,
  98. tm->tm_min,
  99. tm->tm_sec);
  100. infof(data, "%s", data->state.buffer);
  101. }
  102. /*
  103. * This function is called after the TCP connect has completed. Setup the TLS
  104. * layer and do all necessary magic.
  105. */
  106. CURLcode
  107. Curl_gtls_connect(struct connectdata *conn,
  108. int sockindex)
  109. {
  110. const int cert_type_priority[] = { GNUTLS_CRT_X509, 0 };
  111. struct SessionHandle *data = conn->data;
  112. gnutls_session session;
  113. int rc;
  114. unsigned int cert_list_size;
  115. const gnutls_datum *chainp;
  116. unsigned int verify_status;
  117. gnutls_x509_crt x509_cert;
  118. char certbuf[256]; /* big enough? */
  119. size_t size;
  120. unsigned int algo;
  121. unsigned int bits;
  122. time_t clock;
  123. const char *ptr;
  124. void *ssl_sessionid;
  125. size_t ssl_idsize;
  126. /* GnuTLS only supports TLSv1 (and SSLv3?) */
  127. if(data->set.ssl.version == CURL_SSLVERSION_SSLv2) {
  128. failf(data, "GnuTLS does not support SSLv2");
  129. return CURLE_SSL_CONNECT_ERROR;
  130. }
  131. /* allocate a cred struct */
  132. rc = gnutls_certificate_allocate_credentials(&conn->ssl[sockindex].cred);
  133. if(rc < 0) {
  134. failf(data, "gnutls_cert_all_cred() failed: %s", gnutls_strerror(rc));
  135. return CURLE_SSL_CONNECT_ERROR;
  136. }
  137. if(data->set.ssl.CAfile) {
  138. /* set the trusted CA cert bundle file */
  139. gnutls_certificate_set_verify_flags(conn->ssl[sockindex].cred,
  140. GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT);
  141. rc = gnutls_certificate_set_x509_trust_file(conn->ssl[sockindex].cred,
  142. data->set.ssl.CAfile,
  143. GNUTLS_X509_FMT_PEM);
  144. if(rc < 0)
  145. infof(data, "error reading ca cert file %s (%s)\n",
  146. data->set.ssl.CAfile, gnutls_strerror(rc));
  147. else
  148. infof(data, "found %d certificates in %s\n",
  149. rc, data->set.ssl.CAfile);
  150. }
  151. /* Initialize TLS session as a client */
  152. rc = gnutls_init(&conn->ssl[sockindex].session, GNUTLS_CLIENT);
  153. if(rc) {
  154. failf(data, "gnutls_init() failed: %d", rc);
  155. return CURLE_SSL_CONNECT_ERROR;
  156. }
  157. /* convenient assign */
  158. session = conn->ssl[sockindex].session;
  159. /* Use default priorities */
  160. rc = gnutls_set_default_priority(session);
  161. if(rc < 0)
  162. return CURLE_SSL_CONNECT_ERROR;
  163. /* Sets the priority on the certificate types supported by gnutls. Priority
  164. is higher for types specified before others. After specifying the types
  165. you want, you must append a 0. */
  166. rc = gnutls_certificate_type_set_priority(session, cert_type_priority);
  167. if(rc < 0)
  168. return CURLE_SSL_CONNECT_ERROR;
  169. /* put the anonymous credentials to the current session */
  170. rc = gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE,
  171. conn->ssl[sockindex].cred);
  172. /* set the connection handle (file descriptor for the socket) */
  173. gnutls_transport_set_ptr(session,
  174. (gnutls_transport_ptr)conn->sock[sockindex]);
  175. /* This might be a reconnect, so we check for a session ID in the cache
  176. to speed up things */
  177. if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, &ssl_idsize)) {
  178. /* we got a session id, use it! */
  179. gnutls_session_set_data(session, ssl_sessionid, ssl_idsize);
  180. /* Informational message */
  181. infof (data, "SSL re-using session ID\n");
  182. }
  183. do {
  184. rc = gnutls_handshake(session);
  185. if((rc == GNUTLS_E_AGAIN) || (rc == GNUTLS_E_INTERRUPTED)) {
  186. long timeout_ms;
  187. long has_passed;
  188. if(data->set.timeout || data->set.connecttimeout) {
  189. /* get the most strict timeout of the ones converted to milliseconds */
  190. if(data->set.timeout &&
  191. (data->set.timeout>data->set.connecttimeout))
  192. timeout_ms = data->set.timeout*1000;
  193. else
  194. timeout_ms = data->set.connecttimeout*1000;
  195. }
  196. else
  197. timeout_ms = DEFAULT_CONNECT_TIMEOUT;
  198. /* Evaluate in milliseconds how much time that has passed */
  199. has_passed = Curl_tvdiff(Curl_tvnow(), data->progress.t_startsingle);
  200. /* subtract the passed time */
  201. timeout_ms -= has_passed;
  202. if(timeout_ms < 0) {
  203. /* a precaution, no need to continue if time already is up */
  204. failf(data, "SSL connection timeout");
  205. return CURLE_OPERATION_TIMEOUTED;
  206. }
  207. rc = Curl_select(conn->sock[sockindex],
  208. conn->sock[sockindex], (int)timeout_ms);
  209. if(rc > 0)
  210. /* reabable or writable, go loop*/
  211. continue;
  212. else if(0 == rc) {
  213. /* timeout */
  214. failf(data, "SSL connection timeout");
  215. return CURLE_OPERATION_TIMEDOUT;
  216. }
  217. else {
  218. /* anything that gets here is fatally bad */
  219. failf(data, "select on SSL socket, errno: %d", Curl_ourerrno());
  220. return CURLE_SSL_CONNECT_ERROR;
  221. }
  222. }
  223. else
  224. break;
  225. } while(1);
  226. if (rc < 0) {
  227. failf(data, "gnutls_handshake() failed: %d", rc);
  228. /* gnutls_perror(ret); */
  229. return CURLE_SSL_CONNECT_ERROR;
  230. }
  231. /* This function will return the peer's raw certificate (chain) as sent by
  232. the peer. These certificates are in raw format (DER encoded for
  233. X.509). In case of a X.509 then a certificate list may be present. The
  234. first certificate in the list is the peer's certificate, following the
  235. issuer's certificate, then the issuer's issuer etc. */
  236. chainp = gnutls_certificate_get_peers(session, &cert_list_size);
  237. if(!chainp) {
  238. if(data->set.ssl.verifyhost) {
  239. failf(data, "failed to get server cert");
  240. return CURLE_SSL_PEER_CERTIFICATE;
  241. }
  242. infof(data, "\t common name: WARNING couldn't obtain\n");
  243. }
  244. /* This function will try to verify the peer's certificate and return its
  245. status (trusted, invalid etc.). The value of status should be one or more
  246. of the gnutls_certificate_status_t enumerated elements bitwise or'd. To
  247. avoid denial of service attacks some default upper limits regarding the
  248. certificate key size and chain size are set. To override them use
  249. gnutls_certificate_set_verify_limits(). */
  250. rc = gnutls_certificate_verify_peers2(session, &verify_status);
  251. if (rc < 0) {
  252. failf(data, "server cert verify failed: %d", rc);
  253. return CURLE_SSL_CONNECT_ERROR;
  254. }
  255. /* verify_status is a bitmask of gnutls_certificate_status bits */
  256. if(verify_status & GNUTLS_CERT_INVALID) {
  257. if (data->set.ssl.verifypeer) {
  258. failf(data, "server certificate verification failed. CAfile: %s",
  259. data->set.ssl.CAfile?data->set.ssl.CAfile:"none");
  260. return CURLE_SSL_CACERT;
  261. }
  262. else
  263. infof(data, "\t server certificate verification FAILED\n");
  264. }
  265. else
  266. infof(data, "\t server certificate verification OK\n");
  267. /* initialize an X.509 certificate structure. */
  268. gnutls_x509_crt_init(&x509_cert);
  269. /* convert the given DER or PEM encoded Certificate to the native
  270. gnutls_x509_crt_t format */
  271. gnutls_x509_crt_import(x509_cert, chainp, GNUTLS_X509_FMT_DER);
  272. size=sizeof(certbuf);
  273. rc = gnutls_x509_crt_get_dn_by_oid(x509_cert, GNUTLS_OID_X520_COMMON_NAME,
  274. 0, /* the first and only one */
  275. FALSE,
  276. certbuf,
  277. &size);
  278. if(rc) {
  279. infof(data, "error fetching CN from cert:%s\n",
  280. gnutls_strerror(rc));
  281. }
  282. /* This function will check if the given certificate's subject matches the
  283. given hostname. This is a basic implementation of the matching described
  284. in RFC2818 (HTTPS), which takes into account wildcards, and the subject
  285. alternative name PKIX extension. Returns non zero on success, and zero on
  286. failure. */
  287. rc = gnutls_x509_crt_check_hostname(x509_cert, conn->host.name);
  288. if(!rc) {
  289. if (data->set.ssl.verifyhost > 1) {
  290. failf(data, "SSL: certificate subject name (%s) does not match "
  291. "target host name '%s'", certbuf, conn->host.dispname);
  292. gnutls_x509_crt_deinit(x509_cert);
  293. return CURLE_SSL_PEER_CERTIFICATE;
  294. }
  295. else
  296. infof(data, "\t common name: %s (does not match '%s')\n",
  297. certbuf, conn->host.dispname);
  298. }
  299. else
  300. infof(data, "\t common name: %s (matched)\n", certbuf);
  301. /* Show:
  302. - ciphers used
  303. - subject
  304. - start date
  305. - expire date
  306. - common name
  307. - issuer
  308. */
  309. /* public key algorithm's parameters */
  310. algo = gnutls_x509_crt_get_pk_algorithm(x509_cert, &bits);
  311. infof(data, "\t certificate public key: %s\n",
  312. gnutls_pk_algorithm_get_name(algo));
  313. /* version of the X.509 certificate. */
  314. infof(data, "\t certificate version: #%d\n",
  315. gnutls_x509_crt_get_version(x509_cert));
  316. size = sizeof(certbuf);
  317. gnutls_x509_crt_get_dn(x509_cert, certbuf, &size);
  318. infof(data, "\t subject: %s\n", certbuf);
  319. clock = gnutls_x509_crt_get_activation_time(x509_cert);
  320. showtime(data, "start date", clock);
  321. clock = gnutls_x509_crt_get_expiration_time(x509_cert);
  322. showtime(data, "expire date", clock);
  323. size = sizeof(certbuf);
  324. gnutls_x509_crt_get_issuer_dn(x509_cert, certbuf, &size);
  325. infof(data, "\t issuer: %s\n", certbuf);
  326. gnutls_x509_crt_deinit(x509_cert);
  327. /* compression algorithm (if any) */
  328. ptr = gnutls_compression_get_name(gnutls_compression_get(session));
  329. /* the *_get_name() says "NULL" if GNUTLS_COMP_NULL is returned */
  330. infof(data, "\t compression: %s\n", ptr);
  331. /* the name of the cipher used. ie 3DES. */
  332. ptr = gnutls_cipher_get_name(gnutls_cipher_get(session));
  333. infof(data, "\t cipher: %s\n", ptr);
  334. /* the MAC algorithms name. ie SHA1 */
  335. ptr = gnutls_mac_get_name(gnutls_mac_get(session));
  336. infof(data, "\t MAC: %s\n", ptr);
  337. if(!ssl_sessionid) {
  338. /* this session was not previously in the cache, add it now */
  339. /* get the session ID data size */
  340. gnutls_session_get_data(session, NULL, &ssl_idsize);
  341. ssl_sessionid = malloc(ssl_idsize); /* get a buffer for it */
  342. if(ssl_sessionid) {
  343. /* extract session ID to the allocated buffer */
  344. gnutls_session_get_data(session, ssl_sessionid, &ssl_idsize);
  345. /* store this session id */
  346. return Curl_ssl_addsessionid(conn, ssl_sessionid, ssl_idsize);
  347. }
  348. }
  349. return CURLE_OK;
  350. }
  351. /* return number of sent (non-SSL) bytes */
  352. int Curl_gtls_send(struct connectdata *conn,
  353. int sockindex,
  354. void *mem,
  355. size_t len)
  356. {
  357. int rc;
  358. rc = gnutls_record_send(conn->ssl[sockindex].session, mem, len);
  359. return rc;
  360. }
  361. void Curl_gtls_close_all(struct SessionHandle *data)
  362. {
  363. /* FIX: make the OpenSSL code more generic and use parts of it here */
  364. (void)data;
  365. }
  366. static void close_one(struct connectdata *conn,
  367. int index)
  368. {
  369. if(conn->ssl[index].session) {
  370. gnutls_bye(conn->ssl[index].session, GNUTLS_SHUT_RDWR);
  371. gnutls_deinit(conn->ssl[index].session);
  372. }
  373. gnutls_certificate_free_credentials(conn->ssl[index].cred);
  374. }
  375. void Curl_gtls_close(struct connectdata *conn)
  376. {
  377. if(conn->ssl[0].use)
  378. close_one(conn, 0);
  379. if(conn->ssl[1].use)
  380. close_one(conn, 1);
  381. }
  382. /*
  383. * If the read would block we return -1 and set 'wouldblock' to TRUE.
  384. * Otherwise we return the amount of data read. Other errors should return -1
  385. * and set 'wouldblock' to FALSE.
  386. */
  387. ssize_t Curl_gtls_recv(struct connectdata *conn, /* connection data */
  388. int num, /* socketindex */
  389. char *buf, /* store read data here */
  390. size_t buffersize, /* max amount to read */
  391. bool *wouldblock)
  392. {
  393. ssize_t ret;
  394. ret = gnutls_record_recv(conn->ssl[num].session, buf, buffersize);
  395. if((ret == GNUTLS_E_AGAIN) || (ret == GNUTLS_E_INTERRUPTED)) {
  396. *wouldblock = TRUE;
  397. return -1;
  398. }
  399. *wouldblock = FALSE;
  400. if (!ret) {
  401. failf(conn->data, "Peer closed the TLS connection");
  402. return -1;
  403. }
  404. if (ret < 0) {
  405. failf(conn->data, "GnuTLS recv error (%d): %s",
  406. (int)ret, gnutls_strerror(ret));
  407. return -1;
  408. }
  409. return ret;
  410. }
  411. void Curl_gtls_session_free(void *ptr)
  412. {
  413. free(ptr);
  414. }
  415. size_t Curl_gtls_version(char *buffer, size_t size)
  416. {
  417. return snprintf(buffer, size, " GnuTLS/%s", gnutls_check_version(NULL));
  418. }
  419. #endif /* USE_GNUTLS */