mbedtls.c 33 KB

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