gtls.c 56 KB

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