gtls.c 51 KB

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