gtls.c 42 KB

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