gtls.c 56 KB

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