mbedtls.c 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 2010 - 2011, Hoi-Ho Chan, <hoiho.chan@gmail.com>
  9. * Copyright (C) 2012 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
  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.haxx.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. ***************************************************************************/
  23. /*
  24. * Source file for all mbedTLS-specific code for the TLS/SSL layer. No code
  25. * but vtls.c should ever call or use these functions.
  26. *
  27. */
  28. #include "curl_setup.h"
  29. #ifdef USE_MBEDTLS
  30. #include <mbedtls/version.h>
  31. #if MBEDTLS_VERSION_NUMBER >= 0x02040000
  32. #include <mbedtls/net_sockets.h>
  33. #else
  34. #include <mbedtls/net.h>
  35. #endif
  36. #include <mbedtls/ssl.h>
  37. #include <mbedtls/certs.h>
  38. #include <mbedtls/x509.h>
  39. #include <mbedtls/error.h>
  40. #include <mbedtls/entropy.h>
  41. #include <mbedtls/ctr_drbg.h>
  42. #include <mbedtls/sha256.h>
  43. #include "urldata.h"
  44. #include "sendf.h"
  45. #include "inet_pton.h"
  46. #include "mbedtls.h"
  47. #include "vtls.h"
  48. #include "parsedate.h"
  49. #include "connect.h" /* for the connect timeout */
  50. #include "select.h"
  51. #include "multiif.h"
  52. #include "mbedtls_threadlock.h"
  53. /* The last 3 #include files should be in this order */
  54. #include "curl_printf.h"
  55. #include "curl_memory.h"
  56. #include "memdebug.h"
  57. struct ssl_backend_data {
  58. mbedtls_ctr_drbg_context ctr_drbg;
  59. mbedtls_entropy_context entropy;
  60. mbedtls_ssl_context ssl;
  61. int server_fd;
  62. mbedtls_x509_crt cacert;
  63. mbedtls_x509_crt clicert;
  64. mbedtls_x509_crl crl;
  65. mbedtls_pk_context pk;
  66. mbedtls_ssl_config config;
  67. const char *protocols[3];
  68. };
  69. /* apply threading? */
  70. #if defined(USE_THREADS_POSIX) || defined(USE_THREADS_WIN32)
  71. #define THREADING_SUPPORT
  72. #endif
  73. #if defined(THREADING_SUPPORT)
  74. static mbedtls_entropy_context ts_entropy;
  75. static int entropy_init_initialized = 0;
  76. /* start of entropy_init_mutex() */
  77. static void entropy_init_mutex(mbedtls_entropy_context *ctx)
  78. {
  79. /* lock 0 = entropy_init_mutex() */
  80. Curl_mbedtlsthreadlock_lock_function(0);
  81. if(entropy_init_initialized == 0) {
  82. mbedtls_entropy_init(ctx);
  83. entropy_init_initialized = 1;
  84. }
  85. Curl_mbedtlsthreadlock_unlock_function(0);
  86. }
  87. /* end of entropy_init_mutex() */
  88. /* start of entropy_func_mutex() */
  89. static int entropy_func_mutex(void *data, unsigned char *output, size_t len)
  90. {
  91. int ret;
  92. /* lock 1 = entropy_func_mutex() */
  93. Curl_mbedtlsthreadlock_lock_function(1);
  94. ret = mbedtls_entropy_func(data, output, len);
  95. Curl_mbedtlsthreadlock_unlock_function(1);
  96. return ret;
  97. }
  98. /* end of entropy_func_mutex() */
  99. #endif /* THREADING_SUPPORT */
  100. /* Define this to enable lots of debugging for mbedTLS */
  101. #undef MBEDTLS_DEBUG
  102. #ifdef MBEDTLS_DEBUG
  103. static void mbed_debug(void *context, int level, const char *f_name,
  104. int line_nb, const char *line)
  105. {
  106. struct Curl_easy *data = NULL;
  107. if(!context)
  108. return;
  109. data = (struct Curl_easy *)context;
  110. infof(data, "%s", line);
  111. (void) level;
  112. }
  113. #else
  114. #endif
  115. /* ALPN for http2? */
  116. #ifdef USE_NGHTTP2
  117. # undef HAS_ALPN
  118. # ifdef MBEDTLS_SSL_ALPN
  119. # define HAS_ALPN
  120. # endif
  121. #endif
  122. /*
  123. * profile
  124. */
  125. static const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_fr =
  126. {
  127. /* Hashes from SHA-1 and above */
  128. MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA1) |
  129. MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_RIPEMD160) |
  130. MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA224) |
  131. MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA256) |
  132. MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA384) |
  133. MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_SHA512),
  134. 0xFFFFFFF, /* Any PK alg */
  135. 0xFFFFFFF, /* Any curve */
  136. 1024, /* RSA min key len */
  137. };
  138. /* See https://tls.mbed.org/discussions/generic/
  139. howto-determine-exact-buffer-len-for-mbedtls_pk_write_pubkey_der
  140. */
  141. #define RSA_PUB_DER_MAX_BYTES (38 + 2 * MBEDTLS_MPI_MAX_SIZE)
  142. #define ECP_PUB_DER_MAX_BYTES (30 + 2 * MBEDTLS_ECP_MAX_BYTES)
  143. #define PUB_DER_MAX_BYTES (RSA_PUB_DER_MAX_BYTES > ECP_PUB_DER_MAX_BYTES ? \
  144. RSA_PUB_DER_MAX_BYTES : ECP_PUB_DER_MAX_BYTES)
  145. static Curl_recv mbed_recv;
  146. static Curl_send mbed_send;
  147. static CURLcode mbedtls_version_from_curl(int *mbedver, long version)
  148. {
  149. switch(version) {
  150. case CURL_SSLVERSION_TLSv1_0:
  151. *mbedver = MBEDTLS_SSL_MINOR_VERSION_1;
  152. return CURLE_OK;
  153. case CURL_SSLVERSION_TLSv1_1:
  154. *mbedver = MBEDTLS_SSL_MINOR_VERSION_2;
  155. return CURLE_OK;
  156. case CURL_SSLVERSION_TLSv1_2:
  157. *mbedver = MBEDTLS_SSL_MINOR_VERSION_3;
  158. return CURLE_OK;
  159. case CURL_SSLVERSION_TLSv1_3:
  160. break;
  161. }
  162. return CURLE_SSL_CONNECT_ERROR;
  163. }
  164. static CURLcode
  165. set_ssl_version_min_max(struct connectdata *conn, int sockindex)
  166. {
  167. struct Curl_easy *data = conn->data;
  168. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  169. struct ssl_backend_data *backend = connssl->backend;
  170. int mbedtls_ver_min = MBEDTLS_SSL_MINOR_VERSION_1;
  171. int mbedtls_ver_max = MBEDTLS_SSL_MINOR_VERSION_1;
  172. long ssl_version = SSL_CONN_CONFIG(version);
  173. long ssl_version_max = SSL_CONN_CONFIG(version_max);
  174. CURLcode result = CURLE_OK;
  175. switch(ssl_version) {
  176. case CURL_SSLVERSION_DEFAULT:
  177. case CURL_SSLVERSION_TLSv1:
  178. ssl_version = CURL_SSLVERSION_TLSv1_0;
  179. break;
  180. }
  181. switch(ssl_version_max) {
  182. case CURL_SSLVERSION_MAX_NONE:
  183. case CURL_SSLVERSION_MAX_DEFAULT:
  184. ssl_version_max = CURL_SSLVERSION_MAX_TLSv1_2;
  185. break;
  186. }
  187. result = mbedtls_version_from_curl(&mbedtls_ver_min, ssl_version);
  188. if(result) {
  189. failf(data, "unsupported min version passed via CURLOPT_SSLVERSION");
  190. return result;
  191. }
  192. result = mbedtls_version_from_curl(&mbedtls_ver_max, ssl_version_max >> 16);
  193. if(result) {
  194. failf(data, "unsupported max version passed via CURLOPT_SSLVERSION");
  195. return result;
  196. }
  197. mbedtls_ssl_conf_min_version(&backend->config, MBEDTLS_SSL_MAJOR_VERSION_3,
  198. mbedtls_ver_min);
  199. mbedtls_ssl_conf_max_version(&backend->config, MBEDTLS_SSL_MAJOR_VERSION_3,
  200. mbedtls_ver_max);
  201. return result;
  202. }
  203. static CURLcode
  204. mbed_connect_step1(struct connectdata *conn,
  205. int sockindex)
  206. {
  207. struct Curl_easy *data = conn->data;
  208. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  209. struct ssl_backend_data *backend = connssl->backend;
  210. const char * const ssl_cafile = SSL_CONN_CONFIG(CAfile);
  211. const bool verifypeer = SSL_CONN_CONFIG(verifypeer);
  212. const char * const ssl_capath = SSL_CONN_CONFIG(CApath);
  213. char * const ssl_cert = SSL_SET_OPTION(cert);
  214. const char * const ssl_crlfile = SSL_SET_OPTION(CRLfile);
  215. #ifndef CURL_DISABLE_PROXY
  216. const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name :
  217. conn->host.name;
  218. const long int port = SSL_IS_PROXY() ? conn->port : conn->remote_port;
  219. #else
  220. const char * const hostname = conn->host.name;
  221. const long int port = conn->remote_port;
  222. #endif
  223. int ret = -1;
  224. char errorbuf[128];
  225. errorbuf[0] = 0;
  226. /* mbedTLS only supports SSLv3 and TLSv1 */
  227. if(SSL_CONN_CONFIG(version) == CURL_SSLVERSION_SSLv2) {
  228. failf(data, "mbedTLS does not support SSLv2");
  229. return CURLE_SSL_CONNECT_ERROR;
  230. }
  231. #ifdef THREADING_SUPPORT
  232. entropy_init_mutex(&ts_entropy);
  233. mbedtls_ctr_drbg_init(&backend->ctr_drbg);
  234. ret = mbedtls_ctr_drbg_seed(&backend->ctr_drbg, entropy_func_mutex,
  235. &ts_entropy, NULL, 0);
  236. if(ret) {
  237. #ifdef MBEDTLS_ERROR_C
  238. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  239. #endif /* MBEDTLS_ERROR_C */
  240. failf(data, "Failed - mbedTLS: ctr_drbg_init returned (-0x%04X) %s\n",
  241. -ret, errorbuf);
  242. }
  243. #else
  244. mbedtls_entropy_init(&backend->entropy);
  245. mbedtls_ctr_drbg_init(&backend->ctr_drbg);
  246. ret = mbedtls_ctr_drbg_seed(&backend->ctr_drbg, mbedtls_entropy_func,
  247. &backend->entropy, NULL, 0);
  248. if(ret) {
  249. #ifdef MBEDTLS_ERROR_C
  250. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  251. #endif /* MBEDTLS_ERROR_C */
  252. failf(data, "Failed - mbedTLS: ctr_drbg_init returned (-0x%04X) %s\n",
  253. -ret, errorbuf);
  254. }
  255. #endif /* THREADING_SUPPORT */
  256. /* Load the trusted CA */
  257. mbedtls_x509_crt_init(&backend->cacert);
  258. if(ssl_cafile) {
  259. ret = mbedtls_x509_crt_parse_file(&backend->cacert, ssl_cafile);
  260. if(ret<0) {
  261. #ifdef MBEDTLS_ERROR_C
  262. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  263. #endif /* MBEDTLS_ERROR_C */
  264. failf(data, "Error reading ca cert file %s - mbedTLS: (-0x%04X) %s",
  265. ssl_cafile, -ret, errorbuf);
  266. if(verifypeer)
  267. return CURLE_SSL_CACERT_BADFILE;
  268. }
  269. }
  270. if(ssl_capath) {
  271. ret = mbedtls_x509_crt_parse_path(&backend->cacert, ssl_capath);
  272. if(ret<0) {
  273. #ifdef MBEDTLS_ERROR_C
  274. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  275. #endif /* MBEDTLS_ERROR_C */
  276. failf(data, "Error reading ca cert path %s - mbedTLS: (-0x%04X) %s",
  277. ssl_capath, -ret, errorbuf);
  278. if(verifypeer)
  279. return CURLE_SSL_CACERT_BADFILE;
  280. }
  281. }
  282. /* Load the client certificate */
  283. mbedtls_x509_crt_init(&backend->clicert);
  284. if(ssl_cert) {
  285. ret = mbedtls_x509_crt_parse_file(&backend->clicert, ssl_cert);
  286. if(ret) {
  287. #ifdef MBEDTLS_ERROR_C
  288. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  289. #endif /* MBEDTLS_ERROR_C */
  290. failf(data, "Error reading client cert file %s - mbedTLS: (-0x%04X) %s",
  291. ssl_cert, -ret, errorbuf);
  292. return CURLE_SSL_CERTPROBLEM;
  293. }
  294. }
  295. /* Load the client private key */
  296. mbedtls_pk_init(&backend->pk);
  297. if(SSL_SET_OPTION(key)) {
  298. ret = mbedtls_pk_parse_keyfile(&backend->pk, SSL_SET_OPTION(key),
  299. SSL_SET_OPTION(key_passwd));
  300. if(ret == 0 && !(mbedtls_pk_can_do(&backend->pk, MBEDTLS_PK_RSA) ||
  301. mbedtls_pk_can_do(&backend->pk, MBEDTLS_PK_ECKEY)))
  302. ret = MBEDTLS_ERR_PK_TYPE_MISMATCH;
  303. if(ret) {
  304. #ifdef MBEDTLS_ERROR_C
  305. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  306. #endif /* MBEDTLS_ERROR_C */
  307. failf(data, "Error reading private key %s - mbedTLS: (-0x%04X) %s",
  308. SSL_SET_OPTION(key), -ret, errorbuf);
  309. return CURLE_SSL_CERTPROBLEM;
  310. }
  311. }
  312. /* Load the CRL */
  313. mbedtls_x509_crl_init(&backend->crl);
  314. if(ssl_crlfile) {
  315. ret = mbedtls_x509_crl_parse_file(&backend->crl, ssl_crlfile);
  316. if(ret) {
  317. #ifdef MBEDTLS_ERROR_C
  318. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  319. #endif /* MBEDTLS_ERROR_C */
  320. failf(data, "Error reading CRL file %s - mbedTLS: (-0x%04X) %s",
  321. ssl_crlfile, -ret, errorbuf);
  322. return CURLE_SSL_CRL_BADFILE;
  323. }
  324. }
  325. infof(data, "mbedTLS: Connecting to %s:%ld\n", hostname, port);
  326. mbedtls_ssl_config_init(&backend->config);
  327. mbedtls_ssl_init(&backend->ssl);
  328. if(mbedtls_ssl_setup(&backend->ssl, &backend->config)) {
  329. failf(data, "mbedTLS: ssl_init failed");
  330. return CURLE_SSL_CONNECT_ERROR;
  331. }
  332. ret = mbedtls_ssl_config_defaults(&backend->config,
  333. MBEDTLS_SSL_IS_CLIENT,
  334. MBEDTLS_SSL_TRANSPORT_STREAM,
  335. MBEDTLS_SSL_PRESET_DEFAULT);
  336. if(ret) {
  337. failf(data, "mbedTLS: ssl_config failed");
  338. return CURLE_SSL_CONNECT_ERROR;
  339. }
  340. /* new profile with RSA min key len = 1024 ... */
  341. mbedtls_ssl_conf_cert_profile(&backend->config,
  342. &mbedtls_x509_crt_profile_fr);
  343. switch(SSL_CONN_CONFIG(version)) {
  344. case CURL_SSLVERSION_DEFAULT:
  345. case CURL_SSLVERSION_TLSv1:
  346. mbedtls_ssl_conf_min_version(&backend->config, MBEDTLS_SSL_MAJOR_VERSION_3,
  347. MBEDTLS_SSL_MINOR_VERSION_1);
  348. infof(data, "mbedTLS: Set min SSL version to TLS 1.0\n");
  349. break;
  350. case CURL_SSLVERSION_SSLv3:
  351. mbedtls_ssl_conf_min_version(&backend->config, MBEDTLS_SSL_MAJOR_VERSION_3,
  352. MBEDTLS_SSL_MINOR_VERSION_0);
  353. mbedtls_ssl_conf_max_version(&backend->config, MBEDTLS_SSL_MAJOR_VERSION_3,
  354. MBEDTLS_SSL_MINOR_VERSION_0);
  355. infof(data, "mbedTLS: Set SSL version to SSLv3\n");
  356. break;
  357. case CURL_SSLVERSION_TLSv1_0:
  358. case CURL_SSLVERSION_TLSv1_1:
  359. case CURL_SSLVERSION_TLSv1_2:
  360. case CURL_SSLVERSION_TLSv1_3:
  361. {
  362. CURLcode result = set_ssl_version_min_max(conn, sockindex);
  363. if(result != CURLE_OK)
  364. return result;
  365. break;
  366. }
  367. default:
  368. failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
  369. return CURLE_SSL_CONNECT_ERROR;
  370. }
  371. mbedtls_ssl_conf_authmode(&backend->config, MBEDTLS_SSL_VERIFY_OPTIONAL);
  372. mbedtls_ssl_conf_rng(&backend->config, mbedtls_ctr_drbg_random,
  373. &backend->ctr_drbg);
  374. mbedtls_ssl_set_bio(&backend->ssl, &conn->sock[sockindex],
  375. mbedtls_net_send,
  376. mbedtls_net_recv,
  377. NULL /* rev_timeout() */);
  378. mbedtls_ssl_conf_ciphersuites(&backend->config,
  379. mbedtls_ssl_list_ciphersuites());
  380. #if defined(MBEDTLS_SSL_RENEGOTIATION)
  381. mbedtls_ssl_conf_renegotiation(&backend->config,
  382. MBEDTLS_SSL_RENEGOTIATION_ENABLED);
  383. #endif
  384. #if defined(MBEDTLS_SSL_SESSION_TICKETS)
  385. mbedtls_ssl_conf_session_tickets(&backend->config,
  386. MBEDTLS_SSL_SESSION_TICKETS_DISABLED);
  387. #endif
  388. /* Check if there's a cached ID we can/should use here! */
  389. if(SSL_SET_OPTION(primary.sessionid)) {
  390. void *old_session = NULL;
  391. Curl_ssl_sessionid_lock(conn);
  392. if(!Curl_ssl_getsessionid(conn, &old_session, NULL, sockindex)) {
  393. ret = mbedtls_ssl_set_session(&backend->ssl, old_session);
  394. if(ret) {
  395. Curl_ssl_sessionid_unlock(conn);
  396. failf(data, "mbedtls_ssl_set_session returned -0x%x", -ret);
  397. return CURLE_SSL_CONNECT_ERROR;
  398. }
  399. infof(data, "mbedTLS re-using session\n");
  400. }
  401. Curl_ssl_sessionid_unlock(conn);
  402. }
  403. mbedtls_ssl_conf_ca_chain(&backend->config,
  404. &backend->cacert,
  405. &backend->crl);
  406. if(SSL_SET_OPTION(key)) {
  407. mbedtls_ssl_conf_own_cert(&backend->config,
  408. &backend->clicert, &backend->pk);
  409. }
  410. if(mbedtls_ssl_set_hostname(&backend->ssl, hostname)) {
  411. /* mbedtls_ssl_set_hostname() sets the name to use in CN/SAN checks *and*
  412. the name to set in the SNI extension. So even if curl connects to a
  413. host specified as an IP address, this function must be used. */
  414. failf(data, "couldn't set hostname in mbedTLS");
  415. return CURLE_SSL_CONNECT_ERROR;
  416. }
  417. #ifdef HAS_ALPN
  418. if(conn->bits.tls_enable_alpn) {
  419. const char **p = &backend->protocols[0];
  420. #ifdef USE_NGHTTP2
  421. if(data->set.httpversion >= CURL_HTTP_VERSION_2)
  422. *p++ = NGHTTP2_PROTO_VERSION_ID;
  423. #endif
  424. *p++ = ALPN_HTTP_1_1;
  425. *p = NULL;
  426. /* this function doesn't clone the protocols array, which is why we need
  427. to keep it around */
  428. if(mbedtls_ssl_conf_alpn_protocols(&backend->config,
  429. &backend->protocols[0])) {
  430. failf(data, "Failed setting ALPN protocols");
  431. return CURLE_SSL_CONNECT_ERROR;
  432. }
  433. for(p = &backend->protocols[0]; *p; ++p)
  434. infof(data, "ALPN, offering %s\n", *p);
  435. }
  436. #endif
  437. #ifdef MBEDTLS_DEBUG
  438. /* In order to make that work in mbedtls MBEDTLS_DEBUG_C must be defined. */
  439. mbedtls_ssl_conf_dbg(&backend->config, mbed_debug, data);
  440. /* - 0 No debug
  441. * - 1 Error
  442. * - 2 State change
  443. * - 3 Informational
  444. * - 4 Verbose
  445. */
  446. mbedtls_debug_set_threshold(4);
  447. #endif
  448. /* give application a chance to interfere with mbedTLS set up. */
  449. if(data->set.ssl.fsslctx) {
  450. ret = (*data->set.ssl.fsslctx)(data, &backend->config,
  451. data->set.ssl.fsslctxp);
  452. if(ret) {
  453. failf(data, "error signaled by ssl ctx callback");
  454. return ret;
  455. }
  456. }
  457. connssl->connecting_state = ssl_connect_2;
  458. return CURLE_OK;
  459. }
  460. static CURLcode
  461. mbed_connect_step2(struct connectdata *conn,
  462. int sockindex)
  463. {
  464. int ret;
  465. struct Curl_easy *data = conn->data;
  466. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  467. struct ssl_backend_data *backend = connssl->backend;
  468. const mbedtls_x509_crt *peercert;
  469. #ifndef CURL_DISABLE_PROXY
  470. const char * const pinnedpubkey = SSL_IS_PROXY() ?
  471. data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY] :
  472. data->set.str[STRING_SSL_PINNEDPUBLICKEY_ORIG];
  473. #else
  474. const char * const pinnedpubkey =
  475. data->set.str[STRING_SSL_PINNEDPUBLICKEY_ORIG];
  476. #endif
  477. conn->recv[sockindex] = mbed_recv;
  478. conn->send[sockindex] = mbed_send;
  479. ret = mbedtls_ssl_handshake(&backend->ssl);
  480. if(ret == MBEDTLS_ERR_SSL_WANT_READ) {
  481. connssl->connecting_state = ssl_connect_2_reading;
  482. return CURLE_OK;
  483. }
  484. else if(ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  485. connssl->connecting_state = ssl_connect_2_writing;
  486. return CURLE_OK;
  487. }
  488. else if(ret) {
  489. char errorbuf[128];
  490. errorbuf[0] = 0;
  491. #ifdef MBEDTLS_ERROR_C
  492. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  493. #endif /* MBEDTLS_ERROR_C */
  494. failf(data, "ssl_handshake returned - mbedTLS: (-0x%04X) %s",
  495. -ret, errorbuf);
  496. return CURLE_SSL_CONNECT_ERROR;
  497. }
  498. infof(data, "mbedTLS: Handshake complete, cipher is %s\n",
  499. mbedtls_ssl_get_ciphersuite(&backend->ssl)
  500. );
  501. ret = mbedtls_ssl_get_verify_result(&backend->ssl);
  502. if(!SSL_CONN_CONFIG(verifyhost))
  503. /* Ignore hostname errors if verifyhost is disabled */
  504. ret &= ~MBEDTLS_X509_BADCERT_CN_MISMATCH;
  505. if(ret && SSL_CONN_CONFIG(verifypeer)) {
  506. if(ret & MBEDTLS_X509_BADCERT_EXPIRED)
  507. failf(data, "Cert verify failed: BADCERT_EXPIRED");
  508. else if(ret & MBEDTLS_X509_BADCERT_REVOKED)
  509. failf(data, "Cert verify failed: BADCERT_REVOKED");
  510. else if(ret & MBEDTLS_X509_BADCERT_CN_MISMATCH)
  511. failf(data, "Cert verify failed: BADCERT_CN_MISMATCH");
  512. else if(ret & MBEDTLS_X509_BADCERT_NOT_TRUSTED)
  513. failf(data, "Cert verify failed: BADCERT_NOT_TRUSTED");
  514. else if(ret & MBEDTLS_X509_BADCERT_FUTURE)
  515. failf(data, "Cert verify failed: BADCERT_FUTURE");
  516. return CURLE_PEER_FAILED_VERIFICATION;
  517. }
  518. peercert = mbedtls_ssl_get_peer_cert(&backend->ssl);
  519. if(peercert && data->set.verbose) {
  520. const size_t bufsize = 16384;
  521. char *buffer = malloc(bufsize);
  522. if(!buffer)
  523. return CURLE_OUT_OF_MEMORY;
  524. if(mbedtls_x509_crt_info(buffer, bufsize, "* ", peercert) > 0)
  525. infof(data, "Dumping cert info:\n%s\n", buffer);
  526. else
  527. infof(data, "Unable to dump certificate information.\n");
  528. free(buffer);
  529. }
  530. if(pinnedpubkey) {
  531. int size;
  532. CURLcode result;
  533. mbedtls_x509_crt *p;
  534. unsigned char pubkey[PUB_DER_MAX_BYTES];
  535. if(!peercert || !peercert->raw.p || !peercert->raw.len) {
  536. failf(data, "Failed due to missing peer certificate");
  537. return CURLE_SSL_PINNEDPUBKEYNOTMATCH;
  538. }
  539. p = calloc(1, sizeof(*p));
  540. if(!p)
  541. return CURLE_OUT_OF_MEMORY;
  542. mbedtls_x509_crt_init(p);
  543. /* Make a copy of our const peercert because mbedtls_pk_write_pubkey_der
  544. needs a non-const key, for now.
  545. https://github.com/ARMmbed/mbedtls/issues/396 */
  546. if(mbedtls_x509_crt_parse_der(p, peercert->raw.p, peercert->raw.len)) {
  547. failf(data, "Failed copying peer certificate");
  548. mbedtls_x509_crt_free(p);
  549. free(p);
  550. return CURLE_SSL_PINNEDPUBKEYNOTMATCH;
  551. }
  552. size = mbedtls_pk_write_pubkey_der(&p->pk, pubkey, PUB_DER_MAX_BYTES);
  553. if(size <= 0) {
  554. failf(data, "Failed copying public key from peer certificate");
  555. mbedtls_x509_crt_free(p);
  556. free(p);
  557. return CURLE_SSL_PINNEDPUBKEYNOTMATCH;
  558. }
  559. /* mbedtls_pk_write_pubkey_der writes data at the end of the buffer. */
  560. result = Curl_pin_peer_pubkey(data,
  561. pinnedpubkey,
  562. &pubkey[PUB_DER_MAX_BYTES - size], size);
  563. if(result) {
  564. mbedtls_x509_crt_free(p);
  565. free(p);
  566. return result;
  567. }
  568. mbedtls_x509_crt_free(p);
  569. free(p);
  570. }
  571. #ifdef HAS_ALPN
  572. if(conn->bits.tls_enable_alpn) {
  573. const char *next_protocol = mbedtls_ssl_get_alpn_protocol(&backend->ssl);
  574. if(next_protocol) {
  575. infof(data, "ALPN, server accepted to use %s\n", next_protocol);
  576. #ifdef USE_NGHTTP2
  577. if(!strncmp(next_protocol, NGHTTP2_PROTO_VERSION_ID,
  578. NGHTTP2_PROTO_VERSION_ID_LEN) &&
  579. !next_protocol[NGHTTP2_PROTO_VERSION_ID_LEN]) {
  580. conn->negnpn = CURL_HTTP_VERSION_2;
  581. }
  582. else
  583. #endif
  584. if(!strncmp(next_protocol, ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH) &&
  585. !next_protocol[ALPN_HTTP_1_1_LENGTH]) {
  586. conn->negnpn = CURL_HTTP_VERSION_1_1;
  587. }
  588. }
  589. else {
  590. infof(data, "ALPN, server did not agree to a protocol\n");
  591. }
  592. Curl_multiuse_state(conn, conn->negnpn == CURL_HTTP_VERSION_2 ?
  593. BUNDLE_MULTIPLEX : BUNDLE_NO_MULTIUSE);
  594. }
  595. #endif
  596. connssl->connecting_state = ssl_connect_3;
  597. infof(data, "SSL connected\n");
  598. return CURLE_OK;
  599. }
  600. static CURLcode
  601. mbed_connect_step3(struct connectdata *conn,
  602. int sockindex)
  603. {
  604. CURLcode retcode = CURLE_OK;
  605. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  606. struct ssl_backend_data *backend = connssl->backend;
  607. struct Curl_easy *data = conn->data;
  608. DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);
  609. if(SSL_SET_OPTION(primary.sessionid)) {
  610. int ret;
  611. mbedtls_ssl_session *our_ssl_sessionid;
  612. void *old_ssl_sessionid = NULL;
  613. our_ssl_sessionid = malloc(sizeof(mbedtls_ssl_session));
  614. if(!our_ssl_sessionid)
  615. return CURLE_OUT_OF_MEMORY;
  616. mbedtls_ssl_session_init(our_ssl_sessionid);
  617. ret = mbedtls_ssl_get_session(&backend->ssl, our_ssl_sessionid);
  618. if(ret) {
  619. if(ret != MBEDTLS_ERR_SSL_ALLOC_FAILED)
  620. mbedtls_ssl_session_free(our_ssl_sessionid);
  621. free(our_ssl_sessionid);
  622. failf(data, "mbedtls_ssl_get_session returned -0x%x", -ret);
  623. return CURLE_SSL_CONNECT_ERROR;
  624. }
  625. /* If there's already a matching session in the cache, delete it */
  626. Curl_ssl_sessionid_lock(conn);
  627. if(!Curl_ssl_getsessionid(conn, &old_ssl_sessionid, NULL, sockindex))
  628. Curl_ssl_delsessionid(conn, old_ssl_sessionid);
  629. retcode = Curl_ssl_addsessionid(conn, our_ssl_sessionid, 0, sockindex);
  630. Curl_ssl_sessionid_unlock(conn);
  631. if(retcode) {
  632. mbedtls_ssl_session_free(our_ssl_sessionid);
  633. free(our_ssl_sessionid);
  634. failf(data, "failed to store ssl session");
  635. return retcode;
  636. }
  637. }
  638. connssl->connecting_state = ssl_connect_done;
  639. return CURLE_OK;
  640. }
  641. static ssize_t mbed_send(struct connectdata *conn, int sockindex,
  642. const void *mem, size_t len,
  643. CURLcode *curlcode)
  644. {
  645. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  646. struct ssl_backend_data *backend = connssl->backend;
  647. int ret = -1;
  648. ret = mbedtls_ssl_write(&backend->ssl,
  649. (unsigned char *)mem, len);
  650. if(ret < 0) {
  651. *curlcode = (ret == MBEDTLS_ERR_SSL_WANT_WRITE) ?
  652. CURLE_AGAIN : CURLE_SEND_ERROR;
  653. ret = -1;
  654. }
  655. return ret;
  656. }
  657. static void Curl_mbedtls_close_all(struct Curl_easy *data)
  658. {
  659. (void)data;
  660. }
  661. static void Curl_mbedtls_close(struct connectdata *conn, int sockindex)
  662. {
  663. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  664. struct ssl_backend_data *backend = connssl->backend;
  665. mbedtls_pk_free(&backend->pk);
  666. mbedtls_x509_crt_free(&backend->clicert);
  667. mbedtls_x509_crt_free(&backend->cacert);
  668. mbedtls_x509_crl_free(&backend->crl);
  669. mbedtls_ssl_config_free(&backend->config);
  670. mbedtls_ssl_free(&backend->ssl);
  671. mbedtls_ctr_drbg_free(&backend->ctr_drbg);
  672. #ifndef THREADING_SUPPORT
  673. mbedtls_entropy_free(&backend->entropy);
  674. #endif /* THREADING_SUPPORT */
  675. }
  676. static ssize_t mbed_recv(struct connectdata *conn, int num,
  677. char *buf, size_t buffersize,
  678. CURLcode *curlcode)
  679. {
  680. struct ssl_connect_data *connssl = &conn->ssl[num];
  681. struct ssl_backend_data *backend = connssl->backend;
  682. int ret = -1;
  683. ssize_t len = -1;
  684. memset(buf, 0, buffersize);
  685. ret = mbedtls_ssl_read(&backend->ssl, (unsigned char *)buf,
  686. buffersize);
  687. if(ret <= 0) {
  688. if(ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY)
  689. return 0;
  690. *curlcode = (ret == MBEDTLS_ERR_SSL_WANT_READ) ?
  691. CURLE_AGAIN : CURLE_RECV_ERROR;
  692. return -1;
  693. }
  694. len = ret;
  695. return len;
  696. }
  697. static void Curl_mbedtls_session_free(void *ptr)
  698. {
  699. mbedtls_ssl_session_free(ptr);
  700. free(ptr);
  701. }
  702. static size_t Curl_mbedtls_version(char *buffer, size_t size)
  703. {
  704. #ifdef MBEDTLS_VERSION_C
  705. /* if mbedtls_version_get_number() is available it is better */
  706. unsigned int version = mbedtls_version_get_number();
  707. return msnprintf(buffer, size, "mbedTLS/%u.%u.%u", version>>24,
  708. (version>>16)&0xff, (version>>8)&0xff);
  709. #else
  710. return msnprintf(buffer, size, "mbedTLS/%s", MBEDTLS_VERSION_STRING);
  711. #endif
  712. }
  713. static CURLcode Curl_mbedtls_random(struct Curl_easy *data,
  714. unsigned char *entropy, size_t length)
  715. {
  716. #if defined(MBEDTLS_CTR_DRBG_C)
  717. int ret = -1;
  718. char errorbuf[128];
  719. mbedtls_entropy_context ctr_entropy;
  720. mbedtls_ctr_drbg_context ctr_drbg;
  721. mbedtls_entropy_init(&ctr_entropy);
  722. mbedtls_ctr_drbg_init(&ctr_drbg);
  723. errorbuf[0] = 0;
  724. ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func,
  725. &ctr_entropy, NULL, 0);
  726. if(ret) {
  727. #ifdef MBEDTLS_ERROR_C
  728. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  729. #endif /* MBEDTLS_ERROR_C */
  730. failf(data, "Failed - mbedTLS: ctr_drbg_seed returned (-0x%04X) %s\n",
  731. -ret, errorbuf);
  732. }
  733. else {
  734. ret = mbedtls_ctr_drbg_random(&ctr_drbg, entropy, length);
  735. if(ret) {
  736. #ifdef MBEDTLS_ERROR_C
  737. mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
  738. #endif /* MBEDTLS_ERROR_C */
  739. failf(data, "mbedTLS: ctr_drbg_init returned (-0x%04X) %s\n",
  740. -ret, errorbuf);
  741. }
  742. }
  743. mbedtls_ctr_drbg_free(&ctr_drbg);
  744. mbedtls_entropy_free(&ctr_entropy);
  745. return ret == 0 ? CURLE_OK : CURLE_FAILED_INIT;
  746. #elif defined(MBEDTLS_HAVEGE_C)
  747. mbedtls_havege_state hs;
  748. mbedtls_havege_init(&hs);
  749. mbedtls_havege_random(&hs, entropy, length);
  750. mbedtls_havege_free(&hs);
  751. return CURLE_OK;
  752. #else
  753. return CURLE_NOT_BUILT_IN;
  754. #endif
  755. }
  756. static CURLcode
  757. mbed_connect_common(struct connectdata *conn,
  758. int sockindex,
  759. bool nonblocking,
  760. bool *done)
  761. {
  762. CURLcode retcode;
  763. struct Curl_easy *data = conn->data;
  764. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  765. curl_socket_t sockfd = conn->sock[sockindex];
  766. timediff_t timeout_ms;
  767. int what;
  768. /* check if the connection has already been established */
  769. if(ssl_connection_complete == connssl->state) {
  770. *done = TRUE;
  771. return CURLE_OK;
  772. }
  773. if(ssl_connect_1 == connssl->connecting_state) {
  774. /* Find out how much more time we're allowed */
  775. timeout_ms = Curl_timeleft(data, NULL, TRUE);
  776. if(timeout_ms < 0) {
  777. /* no need to continue if time already is up */
  778. failf(data, "SSL connection timeout");
  779. return CURLE_OPERATION_TIMEDOUT;
  780. }
  781. retcode = mbed_connect_step1(conn, sockindex);
  782. if(retcode)
  783. return retcode;
  784. }
  785. while(ssl_connect_2 == connssl->connecting_state ||
  786. ssl_connect_2_reading == connssl->connecting_state ||
  787. ssl_connect_2_writing == connssl->connecting_state) {
  788. /* check allowed time left */
  789. timeout_ms = Curl_timeleft(data, NULL, TRUE);
  790. if(timeout_ms < 0) {
  791. /* no need to continue if time already is up */
  792. failf(data, "SSL connection timeout");
  793. return CURLE_OPERATION_TIMEDOUT;
  794. }
  795. /* if ssl is expecting something, check if it's available. */
  796. if(connssl->connecting_state == ssl_connect_2_reading
  797. || connssl->connecting_state == ssl_connect_2_writing) {
  798. curl_socket_t writefd = ssl_connect_2_writing ==
  799. connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
  800. curl_socket_t readfd = ssl_connect_2_reading ==
  801. connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
  802. what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
  803. nonblocking ? 0 : timeout_ms);
  804. if(what < 0) {
  805. /* fatal error */
  806. failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
  807. return CURLE_SSL_CONNECT_ERROR;
  808. }
  809. else if(0 == what) {
  810. if(nonblocking) {
  811. *done = FALSE;
  812. return CURLE_OK;
  813. }
  814. else {
  815. /* timeout */
  816. failf(data, "SSL connection timeout");
  817. return CURLE_OPERATION_TIMEDOUT;
  818. }
  819. }
  820. /* socket is readable or writable */
  821. }
  822. /* Run transaction, and return to the caller if it failed or if
  823. * this connection is part of a multi handle and this loop would
  824. * execute again. This permits the owner of a multi handle to
  825. * abort a connection attempt before step2 has completed while
  826. * ensuring that a client using select() or epoll() will always
  827. * have a valid fdset to wait on.
  828. */
  829. retcode = mbed_connect_step2(conn, sockindex);
  830. if(retcode || (nonblocking &&
  831. (ssl_connect_2 == connssl->connecting_state ||
  832. ssl_connect_2_reading == connssl->connecting_state ||
  833. ssl_connect_2_writing == connssl->connecting_state)))
  834. return retcode;
  835. } /* repeat step2 until all transactions are done. */
  836. if(ssl_connect_3 == connssl->connecting_state) {
  837. retcode = mbed_connect_step3(conn, sockindex);
  838. if(retcode)
  839. return retcode;
  840. }
  841. if(ssl_connect_done == connssl->connecting_state) {
  842. connssl->state = ssl_connection_complete;
  843. conn->recv[sockindex] = mbed_recv;
  844. conn->send[sockindex] = mbed_send;
  845. *done = TRUE;
  846. }
  847. else
  848. *done = FALSE;
  849. /* Reset our connect state machine */
  850. connssl->connecting_state = ssl_connect_1;
  851. return CURLE_OK;
  852. }
  853. static CURLcode Curl_mbedtls_connect_nonblocking(struct connectdata *conn,
  854. int sockindex, bool *done)
  855. {
  856. return mbed_connect_common(conn, sockindex, TRUE, done);
  857. }
  858. static CURLcode Curl_mbedtls_connect(struct connectdata *conn, int sockindex)
  859. {
  860. CURLcode retcode;
  861. bool done = FALSE;
  862. retcode = mbed_connect_common(conn, sockindex, FALSE, &done);
  863. if(retcode)
  864. return retcode;
  865. DEBUGASSERT(done);
  866. return CURLE_OK;
  867. }
  868. /*
  869. * return 0 error initializing SSL
  870. * return 1 SSL initialized successfully
  871. */
  872. static int Curl_mbedtls_init(void)
  873. {
  874. return Curl_mbedtlsthreadlock_thread_setup();
  875. }
  876. static void Curl_mbedtls_cleanup(void)
  877. {
  878. (void)Curl_mbedtlsthreadlock_thread_cleanup();
  879. }
  880. static bool Curl_mbedtls_data_pending(const struct connectdata *conn,
  881. int sockindex)
  882. {
  883. const struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  884. struct ssl_backend_data *backend = connssl->backend;
  885. return mbedtls_ssl_get_bytes_avail(&backend->ssl) != 0;
  886. }
  887. static CURLcode Curl_mbedtls_sha256sum(const unsigned char *input,
  888. size_t inputlen,
  889. unsigned char *sha256sum,
  890. size_t sha256len UNUSED_PARAM)
  891. {
  892. (void)sha256len;
  893. #if MBEDTLS_VERSION_NUMBER < 0x02070000
  894. mbedtls_sha256(input, inputlen, sha256sum, 0);
  895. #else
  896. /* returns 0 on success, otherwise failure */
  897. if(mbedtls_sha256_ret(input, inputlen, sha256sum, 0) != 0)
  898. return CURLE_BAD_FUNCTION_ARGUMENT;
  899. #endif
  900. return CURLE_OK;
  901. }
  902. static void *Curl_mbedtls_get_internals(struct ssl_connect_data *connssl,
  903. CURLINFO info UNUSED_PARAM)
  904. {
  905. struct ssl_backend_data *backend = connssl->backend;
  906. (void)info;
  907. return &backend->ssl;
  908. }
  909. const struct Curl_ssl Curl_ssl_mbedtls = {
  910. { CURLSSLBACKEND_MBEDTLS, "mbedtls" }, /* info */
  911. SSLSUPP_CA_PATH |
  912. SSLSUPP_PINNEDPUBKEY |
  913. SSLSUPP_SSL_CTX,
  914. sizeof(struct ssl_backend_data),
  915. Curl_mbedtls_init, /* init */
  916. Curl_mbedtls_cleanup, /* cleanup */
  917. Curl_mbedtls_version, /* version */
  918. Curl_none_check_cxn, /* check_cxn */
  919. Curl_none_shutdown, /* shutdown */
  920. Curl_mbedtls_data_pending, /* data_pending */
  921. Curl_mbedtls_random, /* random */
  922. Curl_none_cert_status_request, /* cert_status_request */
  923. Curl_mbedtls_connect, /* connect */
  924. Curl_mbedtls_connect_nonblocking, /* connect_nonblocking */
  925. Curl_mbedtls_get_internals, /* get_internals */
  926. Curl_mbedtls_close, /* close_one */
  927. Curl_mbedtls_close_all, /* close_all */
  928. Curl_mbedtls_session_free, /* session_free */
  929. Curl_none_set_engine, /* set_engine */
  930. Curl_none_set_engine_default, /* set_engine_default */
  931. Curl_none_engines_list, /* engines_list */
  932. Curl_none_false_start, /* false_start */
  933. Curl_none_md5sum, /* md5sum */
  934. Curl_mbedtls_sha256sum /* sha256sum */
  935. };
  936. #endif /* USE_MBEDTLS */