2
0

mbedtls.c 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
  9. * Copyright (C) Hoi-Ho Chan, <hoiho.chan@gmail.com>
  10. *
  11. * This software is licensed as described in the file COPYING, which
  12. * you should have received as part of this distribution. The terms
  13. * are also available at https://curl.se/docs/copyright.html.
  14. *
  15. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  16. * copies of the Software, and permit persons to whom the Software is
  17. * furnished to do so, under the terms of the COPYING file.
  18. *
  19. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  20. * KIND, either express or implied.
  21. *
  22. * SPDX-License-Identifier: curl
  23. *
  24. ***************************************************************************/
  25. /*
  26. * Source file for all mbedTLS-specific code for the TLS/SSL layer. No code
  27. * but vtls.c should ever call or use these functions.
  28. *
  29. */
  30. #include "curl_setup.h"
  31. #ifdef USE_MBEDTLS
  32. /* Define this to enable lots of debugging for mbedTLS */
  33. /* #define MBEDTLS_DEBUG */
  34. #include <mbedtls/version.h>
  35. #if MBEDTLS_VERSION_NUMBER >= 0x02040000
  36. #include <mbedtls/net_sockets.h>
  37. #else
  38. #include <mbedtls/net.h>
  39. #endif
  40. #include <mbedtls/ssl.h>
  41. #include <mbedtls/x509.h>
  42. #include <mbedtls/error.h>
  43. #include <mbedtls/entropy.h>
  44. #include <mbedtls/ctr_drbg.h>
  45. #include <mbedtls/sha256.h>
  46. #if MBEDTLS_VERSION_MAJOR >= 2
  47. # ifdef MBEDTLS_DEBUG
  48. # include <mbedtls/debug.h>
  49. # endif
  50. #endif
  51. #include "cipher_suite.h"
  52. #include "strcase.h"
  53. #include "urldata.h"
  54. #include "sendf.h"
  55. #include "inet_pton.h"
  56. #include "mbedtls.h"
  57. #include "vtls.h"
  58. #include "vtls_int.h"
  59. #include "x509asn1.h"
  60. #include "parsedate.h"
  61. #include "connect.h" /* for the connect timeout */
  62. #include "select.h"
  63. #include "multiif.h"
  64. #include "mbedtls_threadlock.h"
  65. #include "strdup.h"
  66. /* The last 3 #include files should be in this order */
  67. #include "curl_printf.h"
  68. #include "curl_memory.h"
  69. #include "memdebug.h"
  70. /* ALPN for http2 */
  71. #ifdef USE_HTTP2
  72. # undef HAS_ALPN
  73. # ifdef MBEDTLS_SSL_ALPN
  74. # define HAS_ALPN
  75. # endif
  76. #endif
  77. struct mbed_ssl_backend_data {
  78. mbedtls_ctr_drbg_context ctr_drbg;
  79. mbedtls_entropy_context entropy;
  80. mbedtls_ssl_context ssl;
  81. mbedtls_x509_crt cacert;
  82. mbedtls_x509_crt clicert;
  83. #ifdef MBEDTLS_X509_CRL_PARSE_C
  84. mbedtls_x509_crl crl;
  85. #endif
  86. mbedtls_pk_context pk;
  87. mbedtls_ssl_config config;
  88. #ifdef HAS_ALPN
  89. const char *protocols[3];
  90. #endif
  91. int *ciphersuites;
  92. BIT(initialized); /* mbedtls_ssl_context is initialized */
  93. BIT(sent_shutdown);
  94. };
  95. /* apply threading? */
  96. #if (defined(USE_THREADS_POSIX) && defined(HAVE_PTHREAD_H)) || \
  97. defined(_WIN32)
  98. #define THREADING_SUPPORT
  99. #endif
  100. #ifndef MBEDTLS_ERROR_C
  101. #define mbedtls_strerror(a,b,c) b[0] = 0
  102. #endif
  103. #if defined(MBEDTLS_SSL_PROTO_TLS1_3) && MBEDTLS_VERSION_NUMBER >= 0x03060000
  104. #define TLS13_SUPPORT
  105. #endif
  106. #if defined(THREADING_SUPPORT)
  107. static mbedtls_entropy_context ts_entropy;
  108. static int entropy_init_initialized = 0;
  109. static void entropy_init_mutex(mbedtls_entropy_context *ctx)
  110. {
  111. /* lock 0 = entropy_init_mutex() */
  112. Curl_mbedtlsthreadlock_lock_function(0);
  113. if(entropy_init_initialized == 0) {
  114. mbedtls_entropy_init(ctx);
  115. entropy_init_initialized = 1;
  116. }
  117. Curl_mbedtlsthreadlock_unlock_function(0);
  118. }
  119. static void entropy_cleanup_mutex(mbedtls_entropy_context *ctx)
  120. {
  121. /* lock 0 = use same lock as init */
  122. Curl_mbedtlsthreadlock_lock_function(0);
  123. if(entropy_init_initialized == 1) {
  124. mbedtls_entropy_free(ctx);
  125. entropy_init_initialized = 0;
  126. }
  127. Curl_mbedtlsthreadlock_unlock_function(0);
  128. }
  129. static int entropy_func_mutex(void *data, unsigned char *output, size_t len)
  130. {
  131. int ret;
  132. /* lock 1 = entropy_func_mutex() */
  133. Curl_mbedtlsthreadlock_lock_function(1);
  134. ret = mbedtls_entropy_func(data, output, len);
  135. Curl_mbedtlsthreadlock_unlock_function(1);
  136. return ret;
  137. }
  138. #endif /* THREADING_SUPPORT */
  139. #ifdef MBEDTLS_DEBUG
  140. static void mbed_debug(void *context, int level, const char *f_name,
  141. int line_nb, const char *line)
  142. {
  143. struct Curl_easy *data = (struct Curl_easy *)context;
  144. (void) level;
  145. (void) line_nb;
  146. (void) f_name;
  147. if(data) {
  148. size_t len = strlen(line);
  149. if(len && (line[len - 1] == '\n'))
  150. /* discount any trailing newline */
  151. len--;
  152. infof(data, "%.*s", (int)len, line);
  153. }
  154. }
  155. #endif
  156. static int mbedtls_bio_cf_write(void *bio,
  157. const unsigned char *buf, size_t blen)
  158. {
  159. struct Curl_cfilter *cf = bio;
  160. struct Curl_easy *data = CF_DATA_CURRENT(cf);
  161. ssize_t nwritten;
  162. CURLcode result;
  163. DEBUGASSERT(data);
  164. if(!data)
  165. return 0;
  166. nwritten = Curl_conn_cf_send(cf->next, data, (char *)buf, blen, FALSE,
  167. &result);
  168. CURL_TRC_CF(data, cf, "mbedtls_bio_cf_out_write(len=%zu) -> %zd, err=%d",
  169. blen, nwritten, result);
  170. if(nwritten < 0 && CURLE_AGAIN == result) {
  171. nwritten = MBEDTLS_ERR_SSL_WANT_WRITE;
  172. }
  173. return (int)nwritten;
  174. }
  175. static int mbedtls_bio_cf_read(void *bio, unsigned char *buf, size_t blen)
  176. {
  177. struct Curl_cfilter *cf = bio;
  178. struct Curl_easy *data = CF_DATA_CURRENT(cf);
  179. ssize_t nread;
  180. CURLcode result;
  181. DEBUGASSERT(data);
  182. if(!data)
  183. return 0;
  184. /* OpenSSL catches this case, so should we. */
  185. if(!buf)
  186. return 0;
  187. nread = Curl_conn_cf_recv(cf->next, data, (char *)buf, blen, &result);
  188. CURL_TRC_CF(data, cf, "mbedtls_bio_cf_in_read(len=%zu) -> %zd, err=%d",
  189. blen, nread, result);
  190. if(nread < 0 && CURLE_AGAIN == result) {
  191. nread = MBEDTLS_ERR_SSL_WANT_READ;
  192. }
  193. return (int)nread;
  194. }
  195. /*
  196. * profile
  197. */
  198. static const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_fr =
  199. {
  200. /* Hashes from SHA-1 and above */
  201. MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA1) |
  202. MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_RIPEMD160) |
  203. MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA224) |
  204. MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA256) |
  205. MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA384) |
  206. MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA512),
  207. 0xFFFFFFF, /* Any PK alg */
  208. 0xFFFFFFF, /* Any curve */
  209. 1024, /* RSA min key len */
  210. };
  211. /* See https://web.archive.org/web/20200921194007/tls.mbed.org/discussions/
  212. generic/howto-determine-exact-buffer-len-for-mbedtls_pk_write_pubkey_der
  213. */
  214. #define RSA_PUB_DER_MAX_BYTES (38 + 2 * MBEDTLS_MPI_MAX_SIZE)
  215. #define ECP_PUB_DER_MAX_BYTES (30 + 2 * MBEDTLS_ECP_MAX_BYTES)
  216. #define PUB_DER_MAX_BYTES (RSA_PUB_DER_MAX_BYTES > ECP_PUB_DER_MAX_BYTES ? \
  217. RSA_PUB_DER_MAX_BYTES : ECP_PUB_DER_MAX_BYTES)
  218. static CURLcode
  219. mbed_set_ssl_version_min_max(struct Curl_easy *data,
  220. struct mbed_ssl_backend_data *backend,
  221. struct ssl_primary_config *conn_config)
  222. {
  223. /* TLS 1.0 and TLS 1.1 were dropped with mbedTLS 3.0.0 (2021). So, since
  224. * then, and before the introduction of TLS 1.3 in 3.6.0 (2024), this
  225. * function basically always sets TLS 1.2 as min/max, unless given
  226. * unsupported option values. */
  227. #if MBEDTLS_VERSION_NUMBER < 0x03020000
  228. int ver_min = MBEDTLS_SSL_MINOR_VERSION_3; /* TLS 1.2 */
  229. int ver_max = MBEDTLS_SSL_MINOR_VERSION_3; /* TLS 1.2 */
  230. #else
  231. /* mbedTLS 3.2.0 (2022) introduced new methods for setting TLS version */
  232. mbedtls_ssl_protocol_version ver_min = MBEDTLS_SSL_VERSION_TLS1_2;
  233. mbedtls_ssl_protocol_version ver_max = MBEDTLS_SSL_VERSION_TLS1_2;
  234. #endif
  235. switch(conn_config->version) {
  236. case CURL_SSLVERSION_DEFAULT:
  237. #if MBEDTLS_VERSION_NUMBER < 0x03000000
  238. case CURL_SSLVERSION_TLSv1:
  239. case CURL_SSLVERSION_TLSv1_0:
  240. ver_min = MBEDTLS_SSL_MINOR_VERSION_1;
  241. break;
  242. case CURL_SSLVERSION_TLSv1_1:
  243. ver_min = MBEDTLS_SSL_MINOR_VERSION_2;
  244. break;
  245. #else
  246. case CURL_SSLVERSION_TLSv1:
  247. case CURL_SSLVERSION_TLSv1_0:
  248. case CURL_SSLVERSION_TLSv1_1:
  249. #endif
  250. case CURL_SSLVERSION_TLSv1_2:
  251. /* ver_min = MBEDTLS_SSL_VERSION_TLS1_2; */
  252. break;
  253. case CURL_SSLVERSION_TLSv1_3:
  254. #ifdef TLS13_SUPPORT
  255. ver_min = MBEDTLS_SSL_VERSION_TLS1_3;
  256. break;
  257. #endif
  258. default:
  259. failf(data, "mbedTLS: unsupported minimum TLS version value");
  260. return CURLE_SSL_CONNECT_ERROR;
  261. }
  262. switch(conn_config->version_max) {
  263. case CURL_SSLVERSION_MAX_DEFAULT:
  264. case CURL_SSLVERSION_MAX_NONE:
  265. case CURL_SSLVERSION_MAX_TLSv1_3:
  266. #ifdef TLS13_SUPPORT
  267. ver_max = MBEDTLS_SSL_VERSION_TLS1_3;
  268. break;
  269. #endif
  270. case CURL_SSLVERSION_MAX_TLSv1_2:
  271. /* ver_max = MBEDTLS_SSL_VERSION_TLS1_2; */
  272. break;
  273. #if MBEDTLS_VERSION_NUMBER < 0x03000000
  274. case CURL_SSLVERSION_MAX_TLSv1_1:
  275. ver_max = MBEDTLS_SSL_MINOR_VERSION_2;
  276. break;
  277. case CURL_SSLVERSION_MAX_TLSv1_0:
  278. ver_max = MBEDTLS_SSL_MINOR_VERSION_1;
  279. break;
  280. #else
  281. case CURL_SSLVERSION_MAX_TLSv1_1:
  282. case CURL_SSLVERSION_MAX_TLSv1_0:
  283. #endif
  284. default:
  285. failf(data, "mbedTLS: unsupported maximum TLS version value");
  286. return CURLE_SSL_CONNECT_ERROR;
  287. }
  288. #if MBEDTLS_VERSION_NUMBER < 0x03020000
  289. mbedtls_ssl_conf_min_version(&backend->config, MBEDTLS_SSL_MAJOR_VERSION_3,
  290. ver_min);
  291. mbedtls_ssl_conf_max_version(&backend->config, MBEDTLS_SSL_MAJOR_VERSION_3,
  292. ver_max);
  293. #else
  294. mbedtls_ssl_conf_min_tls_version(&backend->config, ver_min);
  295. mbedtls_ssl_conf_max_tls_version(&backend->config, ver_max);
  296. #endif
  297. return CURLE_OK;
  298. }
  299. /* TLS_ECJPAKE_WITH_AES_128_CCM_8 (0xC0FF) is marked experimental
  300. in mbedTLS. The number is not reserved by IANA nor is the
  301. cipher suite present in other SSL implementations. Provide
  302. provisional support for specifying the cipher suite here. */
  303. #ifdef MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8
  304. static int
  305. mbed_cipher_suite_get_str(uint16_t id, char *buf, size_t buf_size,
  306. bool prefer_rfc)
  307. {
  308. if(id == MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8)
  309. msnprintf(buf, buf_size, "%s", "TLS_ECJPAKE_WITH_AES_128_CCM_8");
  310. else
  311. return Curl_cipher_suite_get_str(id, buf, buf_size, prefer_rfc);
  312. return 0;
  313. }
  314. static uint16_t
  315. mbed_cipher_suite_walk_str(const char **str, const char **end)
  316. {
  317. uint16_t id = Curl_cipher_suite_walk_str(str, end);
  318. size_t len = *end - *str;
  319. if(!id) {
  320. if(strncasecompare("TLS_ECJPAKE_WITH_AES_128_CCM_8", *str, len))
  321. id = MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8;
  322. }
  323. return id;
  324. }
  325. #else
  326. #define mbed_cipher_suite_get_str Curl_cipher_suite_get_str
  327. #define mbed_cipher_suite_walk_str Curl_cipher_suite_walk_str
  328. #endif
  329. static CURLcode
  330. mbed_set_selected_ciphers(struct Curl_easy *data,
  331. struct mbed_ssl_backend_data *backend,
  332. const char *ciphers12,
  333. const char *ciphers13)
  334. {
  335. const char *ciphers = ciphers12;
  336. const int *supported;
  337. int *selected;
  338. size_t supported_len, count = 0, default13_count = 0, i, j;
  339. const char *ptr, *end;
  340. supported = mbedtls_ssl_list_ciphersuites();
  341. for(i = 0; supported[i] != 0; i++);
  342. supported_len = i;
  343. selected = malloc(sizeof(int) * (supported_len + 1));
  344. if(!selected)
  345. return CURLE_OUT_OF_MEMORY;
  346. #ifndef TLS13_SUPPORT
  347. (void) ciphers13, (void) j;
  348. #else
  349. if(!ciphers13) {
  350. /* Add default TLSv1.3 ciphers to selection */
  351. for(j = 0; j < supported_len; j++) {
  352. uint16_t id = (uint16_t) supported[j];
  353. if(strncmp(mbedtls_ssl_get_ciphersuite_name(id), "TLS1-3", 6) != 0)
  354. continue;
  355. selected[count++] = id;
  356. }
  357. default13_count = count;
  358. }
  359. else
  360. ciphers = ciphers13;
  361. add_ciphers:
  362. #endif
  363. for(ptr = ciphers; ptr[0] != '\0' && count < supported_len; ptr = end) {
  364. uint16_t id = mbed_cipher_suite_walk_str(&ptr, &end);
  365. /* Check if cipher is supported */
  366. if(id) {
  367. for(i = 0; i < supported_len && supported[i] != id; i++);
  368. if(i == supported_len)
  369. id = 0;
  370. }
  371. if(!id) {
  372. if(ptr[0] != '\0')
  373. infof(data, "mbedTLS: unknown cipher in list: \"%.*s\"",
  374. (int) (end - ptr), ptr);
  375. continue;
  376. }
  377. /* No duplicates allowed (so selected cannot overflow) */
  378. for(i = 0; i < count && selected[i] != id; i++);
  379. if(i < count) {
  380. if(i >= default13_count)
  381. infof(data, "mbedTLS: duplicate cipher in list: \"%.*s\"",
  382. (int) (end - ptr), ptr);
  383. continue;
  384. }
  385. selected[count++] = id;
  386. }
  387. #ifdef TLS13_SUPPORT
  388. if(ciphers == ciphers13 && ciphers12) {
  389. ciphers = ciphers12;
  390. goto add_ciphers;
  391. }
  392. if(!ciphers12) {
  393. /* Add default TLSv1.2 ciphers to selection */
  394. for(j = 0; j < supported_len; j++) {
  395. uint16_t id = (uint16_t) supported[j];
  396. if(strncmp(mbedtls_ssl_get_ciphersuite_name(id), "TLS1-3", 6) == 0)
  397. continue;
  398. /* No duplicates allowed (so selected cannot overflow) */
  399. for(i = 0; i < count && selected[i] != id; i++);
  400. if(i < count)
  401. continue;
  402. selected[count++] = id;
  403. }
  404. }
  405. #endif
  406. selected[count] = 0;
  407. if(count == 0) {
  408. free(selected);
  409. failf(data, "mbedTLS: no supported cipher in list");
  410. return CURLE_SSL_CIPHER;
  411. }
  412. /* mbedtls_ssl_conf_ciphersuites(): The ciphersuites array is not copied.
  413. It must remain valid for the lifetime of the SSL configuration */
  414. backend->ciphersuites = selected;
  415. mbedtls_ssl_conf_ciphersuites(&backend->config, backend->ciphersuites);
  416. return CURLE_OK;
  417. }
  418. static void
  419. mbed_dump_cert_info(struct Curl_easy *data, const mbedtls_x509_crt *crt)
  420. {
  421. #if defined(CURL_DISABLE_VERBOSE_STRINGS) || \
  422. (MBEDTLS_VERSION_NUMBER >= 0x03000000 && defined(MBEDTLS_X509_REMOVE_INFO))
  423. (void) data, (void) crt;
  424. #else
  425. const size_t bufsize = 16384;
  426. char *p, *buffer = malloc(bufsize);
  427. if(buffer && mbedtls_x509_crt_info(buffer, bufsize, " ", crt) > 0) {
  428. infof(data, "Server certificate:");
  429. for(p = buffer; *p; p += *p != '\0') {
  430. size_t s = strcspn(p, "\n");
  431. infof(data, "%.*s", (int) s, p);
  432. p += s;
  433. }
  434. }
  435. else
  436. infof(data, "Unable to dump certificate information");
  437. free(buffer);
  438. #endif
  439. }
  440. static void
  441. mbed_extract_certinfo(struct Curl_easy *data, const mbedtls_x509_crt *crt)
  442. {
  443. CURLcode result;
  444. const mbedtls_x509_crt *cur;
  445. int i;
  446. for(i = 0, cur = crt; cur; ++i, cur = cur->next);
  447. result = Curl_ssl_init_certinfo(data, i);
  448. for(i = 0, cur = crt; result == CURLE_OK && cur; ++i, cur = cur->next) {
  449. const char *beg = (const char *) cur->raw.p;
  450. const char *end = beg + cur->raw.len;
  451. result = Curl_extract_certinfo(data, i, beg, end);
  452. }
  453. }
  454. static int mbed_verify_cb(void *ptr, mbedtls_x509_crt *crt,
  455. int depth, uint32_t *flags)
  456. {
  457. struct Curl_cfilter *cf = (struct Curl_cfilter *) ptr;
  458. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  459. struct Curl_easy *data = CF_DATA_CURRENT(cf);
  460. if(depth == 0) {
  461. if(data->set.verbose)
  462. mbed_dump_cert_info(data, crt);
  463. if(data->set.ssl.certinfo)
  464. mbed_extract_certinfo(data, crt);
  465. }
  466. if(!conn_config->verifypeer)
  467. *flags = 0;
  468. else if(!conn_config->verifyhost)
  469. *flags &= ~MBEDTLS_X509_BADCERT_CN_MISMATCH;
  470. if(*flags) {
  471. #if MBEDTLS_VERSION_NUMBER < 0x03000000 || !defined(MBEDTLS_X509_REMOVE_INFO)
  472. char buf[128];
  473. mbedtls_x509_crt_verify_info(buf, sizeof(buf), "", *flags);
  474. failf(data, "mbedTLS: %s", buf);
  475. #else
  476. failf(data, "mbedTLS: certificate verification error 0x%08x", *flags);
  477. #endif
  478. }
  479. return 0;
  480. }
  481. static CURLcode
  482. mbed_connect_step1(struct Curl_cfilter *cf, struct Curl_easy *data)
  483. {
  484. struct ssl_connect_data *connssl = cf->ctx;
  485. struct mbed_ssl_backend_data *backend =
  486. (struct mbed_ssl_backend_data *)connssl->backend;
  487. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  488. const struct curl_blob *ca_info_blob = conn_config->ca_info_blob;
  489. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  490. const char * const ssl_cafile =
  491. /* CURLOPT_CAINFO_BLOB overrides CURLOPT_CAINFO */
  492. (ca_info_blob ? NULL : conn_config->CAfile);
  493. const bool verifypeer = conn_config->verifypeer;
  494. const char * const ssl_capath = conn_config->CApath;
  495. char * const ssl_cert = ssl_config->primary.clientcert;
  496. const struct curl_blob *ssl_cert_blob = ssl_config->primary.cert_blob;
  497. const char * const ssl_crlfile = ssl_config->primary.CRLfile;
  498. const char *hostname = connssl->peer.hostname;
  499. int ret = -1;
  500. char errorbuf[128];
  501. DEBUGASSERT(backend);
  502. DEBUGASSERT(!backend->initialized);
  503. if((conn_config->version == CURL_SSLVERSION_SSLv2) ||
  504. (conn_config->version == CURL_SSLVERSION_SSLv3)) {
  505. failf(data, "Not supported SSL version");
  506. return CURLE_NOT_BUILT_IN;
  507. }
  508. #ifdef TLS13_SUPPORT
  509. ret = psa_crypto_init();
  510. if(ret != PSA_SUCCESS) {
  511. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  512. failf(data, "mbedTLS psa_crypto_init returned (-0x%04X) %s",
  513. -ret, errorbuf);
  514. return CURLE_SSL_CONNECT_ERROR;
  515. }
  516. #endif /* TLS13_SUPPORT */
  517. #ifdef THREADING_SUPPORT
  518. mbedtls_ctr_drbg_init(&backend->ctr_drbg);
  519. ret = mbedtls_ctr_drbg_seed(&backend->ctr_drbg, entropy_func_mutex,
  520. &ts_entropy, NULL, 0);
  521. if(ret) {
  522. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  523. failf(data, "mbedtls_ctr_drbg_seed returned (-0x%04X) %s",
  524. -ret, errorbuf);
  525. return CURLE_FAILED_INIT;
  526. }
  527. #else
  528. mbedtls_entropy_init(&backend->entropy);
  529. mbedtls_ctr_drbg_init(&backend->ctr_drbg);
  530. ret = mbedtls_ctr_drbg_seed(&backend->ctr_drbg, mbedtls_entropy_func,
  531. &backend->entropy, NULL, 0);
  532. if(ret) {
  533. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  534. failf(data, "mbedtls_ctr_drbg_seed returned (-0x%04X) %s",
  535. -ret, errorbuf);
  536. return CURLE_FAILED_INIT;
  537. }
  538. #endif /* THREADING_SUPPORT */
  539. /* Load the trusted CA */
  540. mbedtls_x509_crt_init(&backend->cacert);
  541. if(ca_info_blob && verifypeer) {
  542. /* Unfortunately, mbedtls_x509_crt_parse() requires the data to be null
  543. terminated even when provided the exact length, forcing us to waste
  544. extra memory here. */
  545. unsigned char *newblob = Curl_memdup0(ca_info_blob->data,
  546. ca_info_blob->len);
  547. if(!newblob)
  548. return CURLE_OUT_OF_MEMORY;
  549. ret = mbedtls_x509_crt_parse(&backend->cacert, newblob,
  550. ca_info_blob->len + 1);
  551. free(newblob);
  552. if(ret < 0) {
  553. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  554. failf(data, "Error importing ca cert blob - mbedTLS: (-0x%04X) %s",
  555. -ret, errorbuf);
  556. return CURLE_SSL_CERTPROBLEM;
  557. }
  558. }
  559. if(ssl_cafile && verifypeer) {
  560. #ifdef MBEDTLS_FS_IO
  561. ret = mbedtls_x509_crt_parse_file(&backend->cacert, ssl_cafile);
  562. if(ret < 0) {
  563. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  564. failf(data, "Error reading ca cert file %s - mbedTLS: (-0x%04X) %s",
  565. ssl_cafile, -ret, errorbuf);
  566. return CURLE_SSL_CACERT_BADFILE;
  567. }
  568. #else
  569. failf(data, "mbedtls: functions that use the filesystem not built in");
  570. return CURLE_NOT_BUILT_IN;
  571. #endif
  572. }
  573. if(ssl_capath) {
  574. #ifdef MBEDTLS_FS_IO
  575. ret = mbedtls_x509_crt_parse_path(&backend->cacert, ssl_capath);
  576. if(ret < 0) {
  577. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  578. failf(data, "Error reading ca cert path %s - mbedTLS: (-0x%04X) %s",
  579. ssl_capath, -ret, errorbuf);
  580. if(verifypeer)
  581. return CURLE_SSL_CACERT_BADFILE;
  582. }
  583. #else
  584. failf(data, "mbedtls: functions that use the filesystem not built in");
  585. return CURLE_NOT_BUILT_IN;
  586. #endif
  587. }
  588. /* Load the client certificate */
  589. mbedtls_x509_crt_init(&backend->clicert);
  590. if(ssl_cert) {
  591. #ifdef MBEDTLS_FS_IO
  592. ret = mbedtls_x509_crt_parse_file(&backend->clicert, ssl_cert);
  593. if(ret) {
  594. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  595. failf(data, "Error reading client cert file %s - mbedTLS: (-0x%04X) %s",
  596. ssl_cert, -ret, errorbuf);
  597. return CURLE_SSL_CERTPROBLEM;
  598. }
  599. #else
  600. failf(data, "mbedtls: functions that use the filesystem not built in");
  601. return CURLE_NOT_BUILT_IN;
  602. #endif
  603. }
  604. if(ssl_cert_blob) {
  605. /* Unfortunately, mbedtls_x509_crt_parse() requires the data to be null
  606. terminated even when provided the exact length, forcing us to waste
  607. extra memory here. */
  608. unsigned char *newblob = Curl_memdup0(ssl_cert_blob->data,
  609. ssl_cert_blob->len);
  610. if(!newblob)
  611. return CURLE_OUT_OF_MEMORY;
  612. ret = mbedtls_x509_crt_parse(&backend->clicert, newblob,
  613. ssl_cert_blob->len + 1);
  614. free(newblob);
  615. if(ret) {
  616. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  617. failf(data, "Error reading client cert data %s - mbedTLS: (-0x%04X) %s",
  618. ssl_config->key, -ret, errorbuf);
  619. return CURLE_SSL_CERTPROBLEM;
  620. }
  621. }
  622. /* Load the client private key */
  623. mbedtls_pk_init(&backend->pk);
  624. if(ssl_config->key || ssl_config->key_blob) {
  625. if(ssl_config->key) {
  626. #ifdef MBEDTLS_FS_IO
  627. #if MBEDTLS_VERSION_NUMBER >= 0x03000000
  628. ret = mbedtls_pk_parse_keyfile(&backend->pk, ssl_config->key,
  629. ssl_config->key_passwd,
  630. mbedtls_ctr_drbg_random,
  631. &backend->ctr_drbg);
  632. #else
  633. ret = mbedtls_pk_parse_keyfile(&backend->pk, ssl_config->key,
  634. ssl_config->key_passwd);
  635. #endif
  636. if(ret) {
  637. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  638. failf(data, "Error reading private key %s - mbedTLS: (-0x%04X) %s",
  639. ssl_config->key, -ret, errorbuf);
  640. return CURLE_SSL_CERTPROBLEM;
  641. }
  642. #else
  643. failf(data, "mbedtls: functions that use the filesystem not built in");
  644. return CURLE_NOT_BUILT_IN;
  645. #endif
  646. }
  647. else {
  648. const struct curl_blob *ssl_key_blob = ssl_config->key_blob;
  649. const unsigned char *key_data =
  650. (const unsigned char *)ssl_key_blob->data;
  651. const char *passwd = ssl_config->key_passwd;
  652. #if MBEDTLS_VERSION_NUMBER >= 0x03000000
  653. ret = mbedtls_pk_parse_key(&backend->pk, key_data, ssl_key_blob->len,
  654. (const unsigned char *)passwd,
  655. passwd ? strlen(passwd) : 0,
  656. mbedtls_ctr_drbg_random,
  657. &backend->ctr_drbg);
  658. #else
  659. ret = mbedtls_pk_parse_key(&backend->pk, key_data, ssl_key_blob->len,
  660. (const unsigned char *)passwd,
  661. passwd ? strlen(passwd) : 0);
  662. #endif
  663. if(ret) {
  664. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  665. failf(data, "Error parsing private key - mbedTLS: (-0x%04X) %s",
  666. -ret, errorbuf);
  667. return CURLE_SSL_CERTPROBLEM;
  668. }
  669. }
  670. if(ret == 0 && !(mbedtls_pk_can_do(&backend->pk, MBEDTLS_PK_RSA) ||
  671. mbedtls_pk_can_do(&backend->pk, MBEDTLS_PK_ECKEY)))
  672. ret = MBEDTLS_ERR_PK_TYPE_MISMATCH;
  673. }
  674. /* Load the CRL */
  675. #ifdef MBEDTLS_X509_CRL_PARSE_C
  676. mbedtls_x509_crl_init(&backend->crl);
  677. if(ssl_crlfile) {
  678. #ifdef MBEDTLS_FS_IO
  679. ret = mbedtls_x509_crl_parse_file(&backend->crl, ssl_crlfile);
  680. if(ret) {
  681. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  682. failf(data, "Error reading CRL file %s - mbedTLS: (-0x%04X) %s",
  683. ssl_crlfile, -ret, errorbuf);
  684. return CURLE_SSL_CRL_BADFILE;
  685. }
  686. #else
  687. failf(data, "mbedtls: functions that use the filesystem not built in");
  688. return CURLE_NOT_BUILT_IN;
  689. #endif
  690. }
  691. #else
  692. if(ssl_crlfile) {
  693. failf(data, "mbedtls: crl support not built in");
  694. return CURLE_NOT_BUILT_IN;
  695. }
  696. #endif
  697. infof(data, "mbedTLS: Connecting to %s:%d", hostname, connssl->peer.port);
  698. mbedtls_ssl_config_init(&backend->config);
  699. ret = mbedtls_ssl_config_defaults(&backend->config,
  700. MBEDTLS_SSL_IS_CLIENT,
  701. MBEDTLS_SSL_TRANSPORT_STREAM,
  702. MBEDTLS_SSL_PRESET_DEFAULT);
  703. if(ret) {
  704. failf(data, "mbedTLS: ssl_config failed");
  705. return CURLE_SSL_CONNECT_ERROR;
  706. }
  707. /* Always let mbedTLS verify certificates, if verifypeer or verifyhost are
  708. * disabled we clear the corresponding error flags in the verify callback
  709. * function. That is also where we log verification errors. */
  710. mbedtls_ssl_conf_verify(&backend->config, mbed_verify_cb, cf);
  711. mbedtls_ssl_conf_authmode(&backend->config, MBEDTLS_SSL_VERIFY_REQUIRED);
  712. mbedtls_ssl_init(&backend->ssl);
  713. backend->initialized = TRUE;
  714. /* new profile with RSA min key len = 1024 ... */
  715. mbedtls_ssl_conf_cert_profile(&backend->config,
  716. &mbedtls_x509_crt_profile_fr);
  717. ret = mbed_set_ssl_version_min_max(data, backend, conn_config);
  718. if(ret != CURLE_OK)
  719. return ret;
  720. mbedtls_ssl_conf_rng(&backend->config, mbedtls_ctr_drbg_random,
  721. &backend->ctr_drbg);
  722. ret = mbedtls_ssl_setup(&backend->ssl, &backend->config);
  723. if(ret) {
  724. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  725. failf(data, "ssl_setup failed - mbedTLS: (-0x%04X) %s",
  726. -ret, errorbuf);
  727. return CURLE_SSL_CONNECT_ERROR;
  728. }
  729. mbedtls_ssl_set_bio(&backend->ssl, cf,
  730. mbedtls_bio_cf_write,
  731. mbedtls_bio_cf_read,
  732. NULL /* rev_timeout() */);
  733. #ifndef TLS13_SUPPORT
  734. if(conn_config->cipher_list) {
  735. CURLcode result = mbed_set_selected_ciphers(data, backend,
  736. conn_config->cipher_list,
  737. NULL);
  738. #else
  739. if(conn_config->cipher_list || conn_config->cipher_list13) {
  740. CURLcode result = mbed_set_selected_ciphers(data, backend,
  741. conn_config->cipher_list,
  742. conn_config->cipher_list13);
  743. #endif
  744. if(result != CURLE_OK) {
  745. failf(data, "mbedTLS: failed to set cipher suites");
  746. return result;
  747. }
  748. }
  749. else {
  750. mbedtls_ssl_conf_ciphersuites(&backend->config,
  751. mbedtls_ssl_list_ciphersuites());
  752. }
  753. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  754. mbedtls_ssl_conf_renegotiation(&backend->config,
  755. MBEDTLS_SSL_RENEGOTIATION_ENABLED);
  756. #endif
  757. #if defined(MBEDTLS_SSL_SESSION_TICKETS)
  758. mbedtls_ssl_conf_session_tickets(&backend->config,
  759. MBEDTLS_SSL_SESSION_TICKETS_DISABLED);
  760. #endif
  761. /* Check if there is a cached ID we can/should use here! */
  762. if(ssl_config->primary.cache_session) {
  763. void *old_session = NULL;
  764. Curl_ssl_sessionid_lock(data);
  765. if(!Curl_ssl_getsessionid(cf, data, &connssl->peer, &old_session, NULL)) {
  766. ret = mbedtls_ssl_set_session(&backend->ssl, old_session);
  767. if(ret) {
  768. Curl_ssl_sessionid_unlock(data);
  769. failf(data, "mbedtls_ssl_set_session returned -0x%x", -ret);
  770. return CURLE_SSL_CONNECT_ERROR;
  771. }
  772. infof(data, "mbedTLS reusing session");
  773. }
  774. Curl_ssl_sessionid_unlock(data);
  775. }
  776. mbedtls_ssl_conf_ca_chain(&backend->config,
  777. &backend->cacert,
  778. #ifdef MBEDTLS_X509_CRL_PARSE_C
  779. &backend->crl);
  780. #else
  781. NULL);
  782. #endif
  783. if(ssl_config->key || ssl_config->key_blob) {
  784. mbedtls_ssl_conf_own_cert(&backend->config,
  785. &backend->clicert, &backend->pk);
  786. }
  787. if(mbedtls_ssl_set_hostname(&backend->ssl, connssl->peer.sni ?
  788. connssl->peer.sni : connssl->peer.hostname)) {
  789. /* mbedtls_ssl_set_hostname() sets the name to use in CN/SAN checks and
  790. the name to set in the SNI extension. So even if curl connects to a
  791. host specified as an IP address, this function must be used. */
  792. failf(data, "Failed to set SNI");
  793. return CURLE_SSL_CONNECT_ERROR;
  794. }
  795. #ifdef HAS_ALPN
  796. if(connssl->alpn) {
  797. struct alpn_proto_buf proto;
  798. size_t i;
  799. for(i = 0; i < connssl->alpn->count; ++i) {
  800. backend->protocols[i] = connssl->alpn->entries[i];
  801. }
  802. /* this function does not clone the protocols array, which is why we need
  803. to keep it around */
  804. if(mbedtls_ssl_conf_alpn_protocols(&backend->config,
  805. &backend->protocols[0])) {
  806. failf(data, "Failed setting ALPN protocols");
  807. return CURLE_SSL_CONNECT_ERROR;
  808. }
  809. Curl_alpn_to_proto_str(&proto, connssl->alpn);
  810. infof(data, VTLS_INFOF_ALPN_OFFER_1STR, proto.data);
  811. }
  812. #endif
  813. #ifdef MBEDTLS_DEBUG
  814. /* In order to make that work in mbedtls MBEDTLS_DEBUG_C must be defined. */
  815. mbedtls_ssl_conf_dbg(&backend->config, mbed_debug, data);
  816. /* - 0 No debug
  817. * - 1 Error
  818. * - 2 State change
  819. * - 3 Informational
  820. * - 4 Verbose
  821. */
  822. mbedtls_debug_set_threshold(4);
  823. #endif
  824. /* give application a chance to interfere with mbedTLS set up. */
  825. if(data->set.ssl.fsslctx) {
  826. CURLcode result = (*data->set.ssl.fsslctx)(data, &backend->config,
  827. data->set.ssl.fsslctxp);
  828. if(result != CURLE_OK) {
  829. failf(data, "error signaled by ssl ctx callback");
  830. return result;
  831. }
  832. }
  833. connssl->connecting_state = ssl_connect_2;
  834. return CURLE_OK;
  835. }
  836. static CURLcode
  837. mbed_connect_step2(struct Curl_cfilter *cf, struct Curl_easy *data)
  838. {
  839. int ret;
  840. struct ssl_connect_data *connssl = cf->ctx;
  841. struct mbed_ssl_backend_data *backend =
  842. (struct mbed_ssl_backend_data *)connssl->backend;
  843. #ifndef CURL_DISABLE_PROXY
  844. const char * const pinnedpubkey = Curl_ssl_cf_is_proxy(cf) ?
  845. data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY] :
  846. data->set.str[STRING_SSL_PINNEDPUBLICKEY];
  847. #else
  848. const char * const pinnedpubkey = data->set.str[STRING_SSL_PINNEDPUBLICKEY];
  849. #endif
  850. DEBUGASSERT(backend);
  851. ret = mbedtls_ssl_handshake(&backend->ssl);
  852. if(ret == MBEDTLS_ERR_SSL_WANT_READ) {
  853. connssl->io_need = CURL_SSL_IO_NEED_RECV;
  854. return CURLE_OK;
  855. }
  856. else if(ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  857. connssl->io_need = CURL_SSL_IO_NEED_SEND;
  858. return CURLE_OK;
  859. }
  860. else if(ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) {
  861. failf(data, "peer certificate could not be verified");
  862. return CURLE_PEER_FAILED_VERIFICATION;
  863. }
  864. else if(ret) {
  865. char errorbuf[128];
  866. #if MBEDTLS_VERSION_NUMBER >= 0x03020000
  867. CURL_TRC_CF(data, cf, "TLS version %04X",
  868. mbedtls_ssl_get_version_number(&backend->ssl));
  869. #endif
  870. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  871. failf(data, "ssl_handshake returned: (-0x%04X) %s",
  872. -ret, errorbuf);
  873. return CURLE_SSL_CONNECT_ERROR;
  874. }
  875. #if MBEDTLS_VERSION_NUMBER >= 0x03020000
  876. {
  877. char cipher_str[64];
  878. uint16_t cipher_id;
  879. cipher_id = (uint16_t)
  880. mbedtls_ssl_get_ciphersuite_id_from_ssl(&backend->ssl);
  881. mbed_cipher_suite_get_str(cipher_id, cipher_str, sizeof(cipher_str), TRUE);
  882. infof(data, "mbedTLS: %s Handshake complete, cipher is %s",
  883. mbedtls_ssl_get_version(&backend->ssl), cipher_str);
  884. }
  885. #else
  886. infof(data, "mbedTLS: %s Handshake complete",
  887. mbedtls_ssl_get_version(&backend->ssl));
  888. #endif
  889. if(pinnedpubkey) {
  890. int size;
  891. CURLcode result;
  892. const mbedtls_x509_crt *peercert;
  893. mbedtls_x509_crt *p = NULL;
  894. unsigned char *pubkey = NULL;
  895. peercert = mbedtls_ssl_get_peer_cert(&backend->ssl);
  896. #if MBEDTLS_VERSION_NUMBER == 0x03000000
  897. if(!peercert || !peercert->MBEDTLS_PRIVATE(raw).MBEDTLS_PRIVATE(p) ||
  898. !peercert->MBEDTLS_PRIVATE(raw).MBEDTLS_PRIVATE(len)) {
  899. #else
  900. if(!peercert || !peercert->raw.p || !peercert->raw.len) {
  901. #endif
  902. failf(data, "Failed due to missing peer certificate");
  903. return CURLE_SSL_PINNEDPUBKEYNOTMATCH;
  904. }
  905. p = calloc(1, sizeof(*p));
  906. if(!p)
  907. return CURLE_OUT_OF_MEMORY;
  908. pubkey = malloc(PUB_DER_MAX_BYTES);
  909. if(!pubkey) {
  910. result = CURLE_OUT_OF_MEMORY;
  911. goto pinnedpubkey_error;
  912. }
  913. mbedtls_x509_crt_init(p);
  914. /* Make a copy of our const peercert because mbedtls_pk_write_pubkey_der
  915. needs a non-const key, for now.
  916. https://github.com/ARMmbed/mbedtls/issues/396 */
  917. #if MBEDTLS_VERSION_NUMBER == 0x03000000
  918. if(mbedtls_x509_crt_parse_der(p,
  919. peercert->MBEDTLS_PRIVATE(raw).MBEDTLS_PRIVATE(p),
  920. peercert->MBEDTLS_PRIVATE(raw).MBEDTLS_PRIVATE(len))) {
  921. #else
  922. if(mbedtls_x509_crt_parse_der(p, peercert->raw.p, peercert->raw.len)) {
  923. #endif
  924. failf(data, "Failed copying peer certificate");
  925. result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
  926. goto pinnedpubkey_error;
  927. }
  928. #if MBEDTLS_VERSION_NUMBER == 0x03000000
  929. size = mbedtls_pk_write_pubkey_der(&p->MBEDTLS_PRIVATE(pk), pubkey,
  930. PUB_DER_MAX_BYTES);
  931. #else
  932. size = mbedtls_pk_write_pubkey_der(&p->pk, pubkey, PUB_DER_MAX_BYTES);
  933. #endif
  934. if(size <= 0) {
  935. failf(data, "Failed copying public key from peer certificate");
  936. result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
  937. goto pinnedpubkey_error;
  938. }
  939. /* mbedtls_pk_write_pubkey_der writes data at the end of the buffer. */
  940. result = Curl_pin_peer_pubkey(data,
  941. pinnedpubkey,
  942. &pubkey[PUB_DER_MAX_BYTES - size], size);
  943. pinnedpubkey_error:
  944. mbedtls_x509_crt_free(p);
  945. free(p);
  946. free(pubkey);
  947. if(result) {
  948. return result;
  949. }
  950. }
  951. #ifdef HAS_ALPN
  952. if(connssl->alpn) {
  953. const char *proto = mbedtls_ssl_get_alpn_protocol(&backend->ssl);
  954. Curl_alpn_set_negotiated(cf, data, (const unsigned char *)proto,
  955. proto ? strlen(proto) : 0);
  956. }
  957. #endif
  958. connssl->connecting_state = ssl_connect_3;
  959. infof(data, "SSL connected");
  960. return CURLE_OK;
  961. }
  962. static void mbedtls_session_free(void *sessionid, size_t idsize)
  963. {
  964. (void)idsize;
  965. mbedtls_ssl_session_free(sessionid);
  966. free(sessionid);
  967. }
  968. static CURLcode
  969. mbed_connect_step3(struct Curl_cfilter *cf, struct Curl_easy *data)
  970. {
  971. CURLcode retcode = CURLE_OK;
  972. struct ssl_connect_data *connssl = cf->ctx;
  973. struct mbed_ssl_backend_data *backend =
  974. (struct mbed_ssl_backend_data *)connssl->backend;
  975. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  976. DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);
  977. DEBUGASSERT(backend);
  978. if(ssl_config->primary.cache_session) {
  979. int ret;
  980. mbedtls_ssl_session *our_ssl_sessionid;
  981. our_ssl_sessionid = malloc(sizeof(mbedtls_ssl_session));
  982. if(!our_ssl_sessionid)
  983. return CURLE_OUT_OF_MEMORY;
  984. mbedtls_ssl_session_init(our_ssl_sessionid);
  985. ret = mbedtls_ssl_get_session(&backend->ssl, our_ssl_sessionid);
  986. if(ret) {
  987. if(ret != MBEDTLS_ERR_SSL_ALLOC_FAILED)
  988. mbedtls_ssl_session_free(our_ssl_sessionid);
  989. free(our_ssl_sessionid);
  990. failf(data, "mbedtls_ssl_get_session returned -0x%x", -ret);
  991. return CURLE_SSL_CONNECT_ERROR;
  992. }
  993. /* If there is already a matching session in the cache, delete it */
  994. Curl_ssl_sessionid_lock(data);
  995. retcode = Curl_ssl_set_sessionid(cf, data, &connssl->peer,
  996. our_ssl_sessionid, 0,
  997. mbedtls_session_free);
  998. Curl_ssl_sessionid_unlock(data);
  999. if(retcode)
  1000. return retcode;
  1001. }
  1002. connssl->connecting_state = ssl_connect_done;
  1003. return CURLE_OK;
  1004. }
  1005. static ssize_t mbed_send(struct Curl_cfilter *cf, struct Curl_easy *data,
  1006. const void *mem, size_t len,
  1007. CURLcode *curlcode)
  1008. {
  1009. struct ssl_connect_data *connssl = cf->ctx;
  1010. struct mbed_ssl_backend_data *backend =
  1011. (struct mbed_ssl_backend_data *)connssl->backend;
  1012. int ret = -1;
  1013. (void)data;
  1014. DEBUGASSERT(backend);
  1015. ret = mbedtls_ssl_write(&backend->ssl, (unsigned char *)mem, len);
  1016. if(ret < 0) {
  1017. CURL_TRC_CF(data, cf, "mbedtls_ssl_write(len=%zu) -> -0x%04X",
  1018. len, -ret);
  1019. *curlcode = ((ret == MBEDTLS_ERR_SSL_WANT_WRITE)
  1020. #ifdef TLS13_SUPPORT
  1021. || (ret == MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET)
  1022. #endif
  1023. ) ? CURLE_AGAIN : CURLE_SEND_ERROR;
  1024. ret = -1;
  1025. }
  1026. return ret;
  1027. }
  1028. static void mbedtls_close_all(struct Curl_easy *data)
  1029. {
  1030. (void)data;
  1031. }
  1032. static CURLcode mbedtls_shutdown(struct Curl_cfilter *cf,
  1033. struct Curl_easy *data,
  1034. bool send_shutdown, bool *done)
  1035. {
  1036. struct ssl_connect_data *connssl = cf->ctx;
  1037. struct mbed_ssl_backend_data *backend =
  1038. (struct mbed_ssl_backend_data *)connssl->backend;
  1039. unsigned char buf[1024];
  1040. CURLcode result = CURLE_OK;
  1041. int ret;
  1042. size_t i;
  1043. DEBUGASSERT(backend);
  1044. if(!backend->initialized || cf->shutdown) {
  1045. *done = TRUE;
  1046. return CURLE_OK;
  1047. }
  1048. connssl->io_need = CURL_SSL_IO_NEED_NONE;
  1049. *done = FALSE;
  1050. if(!backend->sent_shutdown) {
  1051. /* do this only once */
  1052. backend->sent_shutdown = TRUE;
  1053. if(send_shutdown) {
  1054. ret = mbedtls_ssl_close_notify(&backend->ssl);
  1055. switch(ret) {
  1056. case 0: /* we sent it, receive from the server */
  1057. break;
  1058. case MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY: /* server also closed */
  1059. *done = TRUE;
  1060. goto out;
  1061. case MBEDTLS_ERR_SSL_WANT_READ:
  1062. connssl->io_need = CURL_SSL_IO_NEED_RECV;
  1063. goto out;
  1064. case MBEDTLS_ERR_SSL_WANT_WRITE:
  1065. connssl->io_need = CURL_SSL_IO_NEED_SEND;
  1066. goto out;
  1067. default:
  1068. CURL_TRC_CF(data, cf, "mbedtls_shutdown error -0x%04X", -ret);
  1069. result = CURLE_RECV_ERROR;
  1070. goto out;
  1071. }
  1072. }
  1073. }
  1074. /* SSL should now have started the shutdown from our side. Since it
  1075. * was not complete, we are lacking the close notify from the server. */
  1076. for(i = 0; i < 10; ++i) {
  1077. ret = mbedtls_ssl_read(&backend->ssl, buf, sizeof(buf));
  1078. /* This seems to be a bug in mbedTLS TLSv1.3 where it reports
  1079. * WANT_READ, but has not encountered an EAGAIN. */
  1080. if(ret == MBEDTLS_ERR_SSL_WANT_READ)
  1081. ret = mbedtls_ssl_read(&backend->ssl, buf, sizeof(buf));
  1082. #ifdef TLS13_SUPPORT
  1083. if(ret == MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET)
  1084. continue;
  1085. #endif
  1086. if(ret <= 0)
  1087. break;
  1088. }
  1089. if(ret > 0) {
  1090. /* still data coming in? */
  1091. CURL_TRC_CF(data, cf, "mbedtls_shutdown, still getting data");
  1092. }
  1093. else if(ret == 0 || (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY)) {
  1094. /* We got the close notify alert and are done. */
  1095. CURL_TRC_CF(data, cf, "mbedtls_shutdown done");
  1096. *done = TRUE;
  1097. }
  1098. else if(ret == MBEDTLS_ERR_SSL_WANT_READ) {
  1099. CURL_TRC_CF(data, cf, "mbedtls_shutdown, need RECV");
  1100. connssl->io_need = CURL_SSL_IO_NEED_RECV;
  1101. }
  1102. else if(ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  1103. CURL_TRC_CF(data, cf, "mbedtls_shutdown, need SEND");
  1104. connssl->io_need = CURL_SSL_IO_NEED_SEND;
  1105. }
  1106. else {
  1107. CURL_TRC_CF(data, cf, "mbedtls_shutdown error -0x%04X", -ret);
  1108. result = CURLE_RECV_ERROR;
  1109. }
  1110. out:
  1111. cf->shutdown = (result || *done);
  1112. return result;
  1113. }
  1114. static void mbedtls_close(struct Curl_cfilter *cf, struct Curl_easy *data)
  1115. {
  1116. struct ssl_connect_data *connssl = cf->ctx;
  1117. struct mbed_ssl_backend_data *backend =
  1118. (struct mbed_ssl_backend_data *)connssl->backend;
  1119. (void)data;
  1120. DEBUGASSERT(backend);
  1121. if(backend->initialized) {
  1122. mbedtls_pk_free(&backend->pk);
  1123. mbedtls_x509_crt_free(&backend->clicert);
  1124. mbedtls_x509_crt_free(&backend->cacert);
  1125. #ifdef MBEDTLS_X509_CRL_PARSE_C
  1126. mbedtls_x509_crl_free(&backend->crl);
  1127. #endif
  1128. Curl_safefree(backend->ciphersuites);
  1129. mbedtls_ssl_config_free(&backend->config);
  1130. mbedtls_ssl_free(&backend->ssl);
  1131. mbedtls_ctr_drbg_free(&backend->ctr_drbg);
  1132. #ifndef THREADING_SUPPORT
  1133. mbedtls_entropy_free(&backend->entropy);
  1134. #endif /* THREADING_SUPPORT */
  1135. backend->initialized = FALSE;
  1136. }
  1137. }
  1138. static ssize_t mbed_recv(struct Curl_cfilter *cf, struct Curl_easy *data,
  1139. char *buf, size_t buffersize,
  1140. CURLcode *curlcode)
  1141. {
  1142. struct ssl_connect_data *connssl = cf->ctx;
  1143. struct mbed_ssl_backend_data *backend =
  1144. (struct mbed_ssl_backend_data *)connssl->backend;
  1145. int ret = -1;
  1146. ssize_t len = -1;
  1147. (void)data;
  1148. DEBUGASSERT(backend);
  1149. ret = mbedtls_ssl_read(&backend->ssl, (unsigned char *)buf,
  1150. buffersize);
  1151. if(ret <= 0) {
  1152. CURL_TRC_CF(data, cf, "mbedtls_ssl_read(len=%zu) -> -0x%04X",
  1153. buffersize, -ret);
  1154. if(ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY)
  1155. return 0;
  1156. *curlcode = ((ret == MBEDTLS_ERR_SSL_WANT_READ)
  1157. #ifdef TLS13_SUPPORT
  1158. || (ret == MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET)
  1159. #endif
  1160. ) ? CURLE_AGAIN : CURLE_RECV_ERROR;
  1161. if(*curlcode != CURLE_AGAIN) {
  1162. char errorbuf[128];
  1163. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  1164. failf(data, "ssl_read returned: (-0x%04X) %s", -ret, errorbuf);
  1165. }
  1166. return -1;
  1167. }
  1168. len = ret;
  1169. return len;
  1170. }
  1171. static size_t mbedtls_version(char *buffer, size_t size)
  1172. {
  1173. #ifdef MBEDTLS_VERSION_C
  1174. /* if mbedtls_version_get_number() is available it is better */
  1175. unsigned int version = mbedtls_version_get_number();
  1176. return msnprintf(buffer, size, "mbedTLS/%u.%u.%u", version >> 24,
  1177. (version >> 16) & 0xff, (version >> 8) & 0xff);
  1178. #else
  1179. return msnprintf(buffer, size, "mbedTLS/%s", MBEDTLS_VERSION_STRING);
  1180. #endif
  1181. }
  1182. static CURLcode mbedtls_random(struct Curl_easy *data,
  1183. unsigned char *entropy, size_t length)
  1184. {
  1185. #if defined(MBEDTLS_CTR_DRBG_C)
  1186. int ret = -1;
  1187. char errorbuf[128];
  1188. mbedtls_entropy_context ctr_entropy;
  1189. mbedtls_ctr_drbg_context ctr_drbg;
  1190. mbedtls_entropy_init(&ctr_entropy);
  1191. mbedtls_ctr_drbg_init(&ctr_drbg);
  1192. ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func,
  1193. &ctr_entropy, NULL, 0);
  1194. if(ret) {
  1195. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  1196. failf(data, "mbedtls_ctr_drbg_seed returned (-0x%04X) %s",
  1197. -ret, errorbuf);
  1198. }
  1199. else {
  1200. ret = mbedtls_ctr_drbg_random(&ctr_drbg, entropy, length);
  1201. if(ret) {
  1202. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  1203. failf(data, "mbedtls_ctr_drbg_random returned (-0x%04X) %s",
  1204. -ret, errorbuf);
  1205. }
  1206. }
  1207. mbedtls_ctr_drbg_free(&ctr_drbg);
  1208. mbedtls_entropy_free(&ctr_entropy);
  1209. return ret == 0 ? CURLE_OK : CURLE_FAILED_INIT;
  1210. #elif defined(MBEDTLS_HAVEGE_C)
  1211. mbedtls_havege_state hs;
  1212. mbedtls_havege_init(&hs);
  1213. mbedtls_havege_random(&hs, entropy, length);
  1214. mbedtls_havege_free(&hs);
  1215. return CURLE_OK;
  1216. #else
  1217. return CURLE_NOT_BUILT_IN;
  1218. #endif
  1219. }
  1220. static CURLcode
  1221. mbed_connect_common(struct Curl_cfilter *cf, struct Curl_easy *data,
  1222. bool nonblocking,
  1223. bool *done)
  1224. {
  1225. CURLcode retcode;
  1226. struct ssl_connect_data *connssl = cf->ctx;
  1227. curl_socket_t sockfd = Curl_conn_cf_get_socket(cf, data);
  1228. timediff_t timeout_ms;
  1229. int what;
  1230. /* check if the connection has already been established */
  1231. if(ssl_connection_complete == connssl->state) {
  1232. *done = TRUE;
  1233. return CURLE_OK;
  1234. }
  1235. if(ssl_connect_1 == connssl->connecting_state) {
  1236. /* Find out how much more time we are allowed */
  1237. timeout_ms = Curl_timeleft(data, NULL, TRUE);
  1238. if(timeout_ms < 0) {
  1239. /* no need to continue if time already is up */
  1240. failf(data, "SSL connection timeout");
  1241. return CURLE_OPERATION_TIMEDOUT;
  1242. }
  1243. retcode = mbed_connect_step1(cf, data);
  1244. if(retcode)
  1245. return retcode;
  1246. }
  1247. while(ssl_connect_2 == connssl->connecting_state) {
  1248. /* check allowed time left */
  1249. timeout_ms = Curl_timeleft(data, NULL, TRUE);
  1250. if(timeout_ms < 0) {
  1251. /* no need to continue if time already is up */
  1252. failf(data, "SSL connection timeout");
  1253. return CURLE_OPERATION_TIMEDOUT;
  1254. }
  1255. /* if ssl is expecting something, check if it is available. */
  1256. if(connssl->io_need) {
  1257. curl_socket_t writefd = (connssl->io_need & CURL_SSL_IO_NEED_SEND) ?
  1258. sockfd : CURL_SOCKET_BAD;
  1259. curl_socket_t readfd = (connssl->io_need & CURL_SSL_IO_NEED_RECV) ?
  1260. sockfd : CURL_SOCKET_BAD;
  1261. what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
  1262. nonblocking ? 0 : timeout_ms);
  1263. if(what < 0) {
  1264. /* fatal error */
  1265. failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
  1266. return CURLE_SSL_CONNECT_ERROR;
  1267. }
  1268. else if(0 == what) {
  1269. if(nonblocking) {
  1270. *done = FALSE;
  1271. return CURLE_OK;
  1272. }
  1273. else {
  1274. /* timeout */
  1275. failf(data, "SSL connection timeout");
  1276. return CURLE_OPERATION_TIMEDOUT;
  1277. }
  1278. }
  1279. /* socket is readable or writable */
  1280. }
  1281. /* Run transaction, and return to the caller if it failed or if
  1282. * this connection is part of a multi handle and this loop would
  1283. * execute again. This permits the owner of a multi handle to
  1284. * abort a connection attempt before step2 has completed while
  1285. * ensuring that a client using select() or epoll() will always
  1286. * have a valid fdset to wait on.
  1287. */
  1288. connssl->io_need = CURL_SSL_IO_NEED_NONE;
  1289. retcode = mbed_connect_step2(cf, data);
  1290. if(retcode ||
  1291. (nonblocking && (ssl_connect_2 == connssl->connecting_state)))
  1292. return retcode;
  1293. } /* repeat step2 until all transactions are done. */
  1294. if(ssl_connect_3 == connssl->connecting_state) {
  1295. retcode = mbed_connect_step3(cf, data);
  1296. if(retcode)
  1297. return retcode;
  1298. }
  1299. if(ssl_connect_done == connssl->connecting_state) {
  1300. connssl->state = ssl_connection_complete;
  1301. *done = TRUE;
  1302. }
  1303. else
  1304. *done = FALSE;
  1305. /* Reset our connect state machine */
  1306. connssl->connecting_state = ssl_connect_1;
  1307. return CURLE_OK;
  1308. }
  1309. static CURLcode mbedtls_connect_nonblocking(struct Curl_cfilter *cf,
  1310. struct Curl_easy *data,
  1311. bool *done)
  1312. {
  1313. return mbed_connect_common(cf, data, TRUE, done);
  1314. }
  1315. static CURLcode mbedtls_connect(struct Curl_cfilter *cf,
  1316. struct Curl_easy *data)
  1317. {
  1318. CURLcode retcode;
  1319. bool done = FALSE;
  1320. retcode = mbed_connect_common(cf, data, FALSE, &done);
  1321. if(retcode)
  1322. return retcode;
  1323. DEBUGASSERT(done);
  1324. return CURLE_OK;
  1325. }
  1326. /*
  1327. * return 0 error initializing SSL
  1328. * return 1 SSL initialized successfully
  1329. */
  1330. static int mbedtls_init(void)
  1331. {
  1332. if(!Curl_mbedtlsthreadlock_thread_setup())
  1333. return 0;
  1334. #ifdef THREADING_SUPPORT
  1335. entropy_init_mutex(&ts_entropy);
  1336. #endif
  1337. return 1;
  1338. }
  1339. static void mbedtls_cleanup(void)
  1340. {
  1341. #ifdef THREADING_SUPPORT
  1342. entropy_cleanup_mutex(&ts_entropy);
  1343. #endif
  1344. (void)Curl_mbedtlsthreadlock_thread_cleanup();
  1345. }
  1346. static bool mbedtls_data_pending(struct Curl_cfilter *cf,
  1347. const struct Curl_easy *data)
  1348. {
  1349. struct ssl_connect_data *ctx = cf->ctx;
  1350. struct mbed_ssl_backend_data *backend;
  1351. (void)data;
  1352. DEBUGASSERT(ctx && ctx->backend);
  1353. backend = (struct mbed_ssl_backend_data *)ctx->backend;
  1354. return mbedtls_ssl_get_bytes_avail(&backend->ssl) != 0;
  1355. }
  1356. static CURLcode mbedtls_sha256sum(const unsigned char *input,
  1357. size_t inputlen,
  1358. unsigned char *sha256sum,
  1359. size_t sha256len UNUSED_PARAM)
  1360. {
  1361. /* TODO: explain this for different mbedtls 2.x vs 3 version */
  1362. (void)sha256len;
  1363. #if MBEDTLS_VERSION_NUMBER < 0x02070000
  1364. mbedtls_sha256(input, inputlen, sha256sum, 0);
  1365. #else
  1366. /* returns 0 on success, otherwise failure */
  1367. #if MBEDTLS_VERSION_NUMBER >= 0x03000000
  1368. if(mbedtls_sha256(input, inputlen, sha256sum, 0) != 0)
  1369. #else
  1370. if(mbedtls_sha256_ret(input, inputlen, sha256sum, 0) != 0)
  1371. #endif
  1372. return CURLE_BAD_FUNCTION_ARGUMENT;
  1373. #endif
  1374. return CURLE_OK;
  1375. }
  1376. static void *mbedtls_get_internals(struct ssl_connect_data *connssl,
  1377. CURLINFO info UNUSED_PARAM)
  1378. {
  1379. struct mbed_ssl_backend_data *backend =
  1380. (struct mbed_ssl_backend_data *)connssl->backend;
  1381. (void)info;
  1382. DEBUGASSERT(backend);
  1383. return &backend->ssl;
  1384. }
  1385. const struct Curl_ssl Curl_ssl_mbedtls = {
  1386. { CURLSSLBACKEND_MBEDTLS, "mbedtls" }, /* info */
  1387. SSLSUPP_CA_PATH |
  1388. SSLSUPP_CAINFO_BLOB |
  1389. SSLSUPP_CERTINFO |
  1390. SSLSUPP_PINNEDPUBKEY |
  1391. SSLSUPP_SSL_CTX |
  1392. #ifdef TLS13_SUPPORT
  1393. SSLSUPP_TLS13_CIPHERSUITES |
  1394. #endif
  1395. SSLSUPP_HTTPS_PROXY |
  1396. SSLSUPP_CIPHER_LIST,
  1397. sizeof(struct mbed_ssl_backend_data),
  1398. mbedtls_init, /* init */
  1399. mbedtls_cleanup, /* cleanup */
  1400. mbedtls_version, /* version */
  1401. Curl_none_check_cxn, /* check_cxn */
  1402. mbedtls_shutdown, /* shutdown */
  1403. mbedtls_data_pending, /* data_pending */
  1404. mbedtls_random, /* random */
  1405. Curl_none_cert_status_request, /* cert_status_request */
  1406. mbedtls_connect, /* connect */
  1407. mbedtls_connect_nonblocking, /* connect_nonblocking */
  1408. Curl_ssl_adjust_pollset, /* adjust_pollset */
  1409. mbedtls_get_internals, /* get_internals */
  1410. mbedtls_close, /* close_one */
  1411. mbedtls_close_all, /* close_all */
  1412. Curl_none_set_engine, /* set_engine */
  1413. Curl_none_set_engine_default, /* set_engine_default */
  1414. Curl_none_engines_list, /* engines_list */
  1415. Curl_none_false_start, /* false_start */
  1416. mbedtls_sha256sum, /* sha256sum */
  1417. NULL, /* associate_connection */
  1418. NULL, /* disassociate_connection */
  1419. mbed_recv, /* recv decrypted data */
  1420. mbed_send, /* send data to encrypt */
  1421. NULL, /* get_channel_binding */
  1422. };
  1423. #endif /* USE_MBEDTLS */