gtls.c 51 KB

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