gtls.c 49 KB

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