ssl_session.cc 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273
  1. /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  2. * All rights reserved.
  3. *
  4. * This package is an SSL implementation written
  5. * by Eric Young (eay@cryptsoft.com).
  6. * The implementation was written so as to conform with Netscapes SSL.
  7. *
  8. * This library is free for commercial and non-commercial use as long as
  9. * the following conditions are aheared to. The following conditions
  10. * apply to all code found in this distribution, be it the RC4, RSA,
  11. * lhash, DES, etc., code; not just the SSL code. The SSL documentation
  12. * included with this distribution is covered by the same copyright terms
  13. * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  14. *
  15. * Copyright remains Eric Young's, and as such any Copyright notices in
  16. * the code are not to be removed.
  17. * If this package is used in a product, Eric Young should be given attribution
  18. * as the author of the parts of the library used.
  19. * This can be in the form of a textual message at program startup or
  20. * in documentation (online or textual) provided with the package.
  21. *
  22. * Redistribution and use in source and binary forms, with or without
  23. * modification, are permitted provided that the following conditions
  24. * are met:
  25. * 1. Redistributions of source code must retain the copyright
  26. * notice, this list of conditions and the following disclaimer.
  27. * 2. Redistributions in binary form must reproduce the above copyright
  28. * notice, this list of conditions and the following disclaimer in the
  29. * documentation and/or other materials provided with the distribution.
  30. * 3. All advertising materials mentioning features or use of this software
  31. * must display the following acknowledgement:
  32. * "This product includes cryptographic software written by
  33. * Eric Young (eay@cryptsoft.com)"
  34. * The word 'cryptographic' can be left out if the rouines from the library
  35. * being used are not cryptographic related :-).
  36. * 4. If you include any Windows specific code (or a derivative thereof) from
  37. * the apps directory (application code) you must include an acknowledgement:
  38. * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  39. *
  40. * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  41. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  42. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  43. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  44. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  45. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  46. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  47. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  48. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  49. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  50. * SUCH DAMAGE.
  51. *
  52. * The licence and distribution terms for any publically available version or
  53. * derivative of this code cannot be changed. i.e. this code cannot simply be
  54. * copied and put under another distribution licence
  55. * [including the GNU Public Licence.]
  56. */
  57. /* ====================================================================
  58. * Copyright (c) 1998-2006 The OpenSSL Project. All rights reserved.
  59. *
  60. * Redistribution and use in source and binary forms, with or without
  61. * modification, are permitted provided that the following conditions
  62. * are met:
  63. *
  64. * 1. Redistributions of source code must retain the above copyright
  65. * notice, this list of conditions and the following disclaimer.
  66. *
  67. * 2. Redistributions in binary form must reproduce the above copyright
  68. * notice, this list of conditions and the following disclaimer in
  69. * the documentation and/or other materials provided with the
  70. * distribution.
  71. *
  72. * 3. All advertising materials mentioning features or use of this
  73. * software must display the following acknowledgment:
  74. * "This product includes software developed by the OpenSSL Project
  75. * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
  76. *
  77. * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  78. * endorse or promote products derived from this software without
  79. * prior written permission. For written permission, please contact
  80. * openssl-core@openssl.org.
  81. *
  82. * 5. Products derived from this software may not be called "OpenSSL"
  83. * nor may "OpenSSL" appear in their names without prior written
  84. * permission of the OpenSSL Project.
  85. *
  86. * 6. Redistributions of any form whatsoever must retain the following
  87. * acknowledgment:
  88. * "This product includes software developed by the OpenSSL Project
  89. * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
  90. *
  91. * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  92. * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  93. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  94. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
  95. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  96. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  97. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  98. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  99. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  100. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  101. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  102. * OF THE POSSIBILITY OF SUCH DAMAGE.
  103. * ====================================================================
  104. *
  105. * This product includes cryptographic software written by Eric Young
  106. * (eay@cryptsoft.com). This product includes software written by Tim
  107. * Hudson (tjh@cryptsoft.com).
  108. *
  109. */
  110. /* ====================================================================
  111. * Copyright 2005 Nokia. All rights reserved.
  112. *
  113. * The portions of the attached software ("Contribution") is developed by
  114. * Nokia Corporation and is licensed pursuant to the OpenSSL open source
  115. * license.
  116. *
  117. * The Contribution, originally written by Mika Kousa and Pasi Eronen of
  118. * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
  119. * support (see RFC 4279) to OpenSSL.
  120. *
  121. * No patent licenses or other rights except those expressly stated in
  122. * the OpenSSL open source license shall be deemed granted or received
  123. * expressly, by implication, estoppel, or otherwise.
  124. *
  125. * No assurances are provided by Nokia that the Contribution does not
  126. * infringe the patent or other intellectual property rights of any third
  127. * party or that the license provides you with all the necessary rights
  128. * to make use of the Contribution.
  129. *
  130. * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
  131. * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
  132. * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
  133. * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
  134. * OTHERWISE. */
  135. #include <openssl/ssl.h>
  136. #include <assert.h>
  137. #include <stdlib.h>
  138. #include <string.h>
  139. #include <utility>
  140. #include <openssl/err.h>
  141. #include <openssl/hmac.h>
  142. #include <openssl/lhash.h>
  143. #include <openssl/mem.h>
  144. #include <openssl/rand.h>
  145. #include "internal.h"
  146. #include "../crypto/internal.h"
  147. BSSL_NAMESPACE_BEGIN
  148. // The address of this is a magic value, a pointer to which is returned by
  149. // SSL_magic_pending_session_ptr(). It allows a session callback to indicate
  150. // that it needs to asynchronously fetch session information.
  151. static const char g_pending_session_magic = 0;
  152. static CRYPTO_EX_DATA_CLASS g_ex_data_class =
  153. CRYPTO_EX_DATA_CLASS_INIT_WITH_APP_DATA;
  154. static void SSL_SESSION_list_remove(SSL_CTX *ctx, SSL_SESSION *session);
  155. static void SSL_SESSION_list_add(SSL_CTX *ctx, SSL_SESSION *session);
  156. static int remove_session_lock(SSL_CTX *ctx, SSL_SESSION *session, int lock);
  157. UniquePtr<SSL_SESSION> ssl_session_new(const SSL_X509_METHOD *x509_method) {
  158. return MakeUnique<SSL_SESSION>(x509_method);
  159. }
  160. uint32_t ssl_hash_session_id(Span<const uint8_t> session_id) {
  161. // Take the first four bytes of |session_id|. Session IDs are generated by the
  162. // server randomly, so we can assume even using the first four bytes results
  163. // in a good distribution.
  164. uint8_t tmp_storage[sizeof(uint32_t)];
  165. if (session_id.size() < sizeof(tmp_storage)) {
  166. OPENSSL_memset(tmp_storage, 0, sizeof(tmp_storage));
  167. OPENSSL_memcpy(tmp_storage, session_id.data(), session_id.size());
  168. session_id = tmp_storage;
  169. }
  170. uint32_t hash =
  171. ((uint32_t)session_id[0]) |
  172. ((uint32_t)session_id[1] << 8) |
  173. ((uint32_t)session_id[2] << 16) |
  174. ((uint32_t)session_id[3] << 24);
  175. return hash;
  176. }
  177. UniquePtr<SSL_SESSION> SSL_SESSION_dup(SSL_SESSION *session, int dup_flags) {
  178. UniquePtr<SSL_SESSION> new_session = ssl_session_new(session->x509_method);
  179. if (!new_session) {
  180. return nullptr;
  181. }
  182. new_session->is_server = session->is_server;
  183. new_session->ssl_version = session->ssl_version;
  184. new_session->sid_ctx_length = session->sid_ctx_length;
  185. OPENSSL_memcpy(new_session->sid_ctx, session->sid_ctx, session->sid_ctx_length);
  186. // Copy the key material.
  187. new_session->master_key_length = session->master_key_length;
  188. OPENSSL_memcpy(new_session->master_key, session->master_key,
  189. session->master_key_length);
  190. new_session->cipher = session->cipher;
  191. // Copy authentication state.
  192. if (session->psk_identity != nullptr) {
  193. new_session->psk_identity.reset(BUF_strdup(session->psk_identity.get()));
  194. if (new_session->psk_identity == nullptr) {
  195. return nullptr;
  196. }
  197. }
  198. if (session->certs != nullptr) {
  199. auto buf_up_ref = [](CRYPTO_BUFFER *buf) {
  200. CRYPTO_BUFFER_up_ref(buf);
  201. return buf;
  202. };
  203. new_session->certs.reset(sk_CRYPTO_BUFFER_deep_copy(
  204. session->certs.get(), buf_up_ref, CRYPTO_BUFFER_free));
  205. if (new_session->certs == nullptr) {
  206. return nullptr;
  207. }
  208. }
  209. if (!session->x509_method->session_dup(new_session.get(), session)) {
  210. return nullptr;
  211. }
  212. new_session->verify_result = session->verify_result;
  213. new_session->ocsp_response = UpRef(session->ocsp_response);
  214. new_session->signed_cert_timestamp_list =
  215. UpRef(session->signed_cert_timestamp_list);
  216. OPENSSL_memcpy(new_session->peer_sha256, session->peer_sha256,
  217. SHA256_DIGEST_LENGTH);
  218. new_session->peer_sha256_valid = session->peer_sha256_valid;
  219. new_session->peer_signature_algorithm = session->peer_signature_algorithm;
  220. new_session->timeout = session->timeout;
  221. new_session->auth_timeout = session->auth_timeout;
  222. new_session->time = session->time;
  223. // Copy non-authentication connection properties.
  224. if (dup_flags & SSL_SESSION_INCLUDE_NONAUTH) {
  225. new_session->session_id_length = session->session_id_length;
  226. OPENSSL_memcpy(new_session->session_id, session->session_id,
  227. session->session_id_length);
  228. new_session->group_id = session->group_id;
  229. OPENSSL_memcpy(new_session->original_handshake_hash,
  230. session->original_handshake_hash,
  231. session->original_handshake_hash_len);
  232. new_session->original_handshake_hash_len =
  233. session->original_handshake_hash_len;
  234. new_session->ticket_lifetime_hint = session->ticket_lifetime_hint;
  235. new_session->ticket_age_add = session->ticket_age_add;
  236. new_session->ticket_max_early_data = session->ticket_max_early_data;
  237. new_session->extended_master_secret = session->extended_master_secret;
  238. if (!new_session->early_alpn.CopyFrom(session->early_alpn)) {
  239. return nullptr;
  240. }
  241. }
  242. // Copy the ticket.
  243. if (dup_flags & SSL_SESSION_INCLUDE_TICKET &&
  244. !new_session->ticket.CopyFrom(session->ticket)) {
  245. return nullptr;
  246. }
  247. // The new_session does not get a copy of the ex_data.
  248. new_session->not_resumable = true;
  249. return new_session;
  250. }
  251. void ssl_session_rebase_time(SSL *ssl, SSL_SESSION *session) {
  252. struct OPENSSL_timeval now;
  253. ssl_get_current_time(ssl, &now);
  254. // To avoid overflows and underflows, if we've gone back in time, update the
  255. // time, but mark the session expired.
  256. if (session->time > now.tv_sec) {
  257. session->time = now.tv_sec;
  258. session->timeout = 0;
  259. session->auth_timeout = 0;
  260. return;
  261. }
  262. // Adjust the session time and timeouts. If the session has already expired,
  263. // clamp the timeouts at zero.
  264. uint64_t delta = now.tv_sec - session->time;
  265. session->time = now.tv_sec;
  266. if (session->timeout < delta) {
  267. session->timeout = 0;
  268. } else {
  269. session->timeout -= delta;
  270. }
  271. if (session->auth_timeout < delta) {
  272. session->auth_timeout = 0;
  273. } else {
  274. session->auth_timeout -= delta;
  275. }
  276. }
  277. void ssl_session_renew_timeout(SSL *ssl, SSL_SESSION *session,
  278. uint32_t timeout) {
  279. // Rebase the timestamp relative to the current time so |timeout| is measured
  280. // correctly.
  281. ssl_session_rebase_time(ssl, session);
  282. if (session->timeout > timeout) {
  283. return;
  284. }
  285. session->timeout = timeout;
  286. if (session->timeout > session->auth_timeout) {
  287. session->timeout = session->auth_timeout;
  288. }
  289. }
  290. uint16_t ssl_session_protocol_version(const SSL_SESSION *session) {
  291. uint16_t ret;
  292. if (!ssl_protocol_version_from_wire(&ret, session->ssl_version)) {
  293. // An |SSL_SESSION| will never have an invalid version. This is enforced by
  294. // the parser.
  295. assert(0);
  296. return 0;
  297. }
  298. return ret;
  299. }
  300. const EVP_MD *ssl_session_get_digest(const SSL_SESSION *session) {
  301. return ssl_get_handshake_digest(ssl_session_protocol_version(session),
  302. session->cipher);
  303. }
  304. int ssl_get_new_session(SSL_HANDSHAKE *hs, int is_server) {
  305. SSL *const ssl = hs->ssl;
  306. if (ssl->mode & SSL_MODE_NO_SESSION_CREATION) {
  307. OPENSSL_PUT_ERROR(SSL, SSL_R_SESSION_MAY_NOT_BE_CREATED);
  308. return 0;
  309. }
  310. UniquePtr<SSL_SESSION> session = ssl_session_new(ssl->ctx->x509_method);
  311. if (session == NULL) {
  312. return 0;
  313. }
  314. session->is_server = is_server;
  315. session->ssl_version = ssl->version;
  316. // Fill in the time from the |SSL_CTX|'s clock.
  317. struct OPENSSL_timeval now;
  318. ssl_get_current_time(ssl, &now);
  319. session->time = now.tv_sec;
  320. uint16_t version = ssl_protocol_version(ssl);
  321. if (version >= TLS1_3_VERSION) {
  322. // TLS 1.3 uses tickets as authenticators, so we are willing to use them for
  323. // longer.
  324. session->timeout = ssl->session_ctx->session_psk_dhe_timeout;
  325. session->auth_timeout = SSL_DEFAULT_SESSION_AUTH_TIMEOUT;
  326. } else {
  327. // TLS 1.2 resumption does not incorporate new key material, so we use a
  328. // much shorter timeout.
  329. session->timeout = ssl->session_ctx->session_timeout;
  330. session->auth_timeout = ssl->session_ctx->session_timeout;
  331. }
  332. if (is_server) {
  333. if (hs->ticket_expected || version >= TLS1_3_VERSION) {
  334. // Don't set session IDs for sessions resumed with tickets. This will keep
  335. // them out of the session cache.
  336. session->session_id_length = 0;
  337. } else {
  338. session->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
  339. if (!RAND_bytes(session->session_id, session->session_id_length)) {
  340. return 0;
  341. }
  342. }
  343. } else {
  344. session->session_id_length = 0;
  345. }
  346. if (hs->config->cert->sid_ctx_length > sizeof(session->sid_ctx)) {
  347. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  348. return 0;
  349. }
  350. OPENSSL_memcpy(session->sid_ctx, hs->config->cert->sid_ctx,
  351. hs->config->cert->sid_ctx_length);
  352. session->sid_ctx_length = hs->config->cert->sid_ctx_length;
  353. // The session is marked not resumable until it is completely filled in.
  354. session->not_resumable = true;
  355. session->verify_result = X509_V_ERR_INVALID_CALL;
  356. hs->new_session = std::move(session);
  357. ssl_set_session(ssl, NULL);
  358. return 1;
  359. }
  360. int ssl_ctx_rotate_ticket_encryption_key(SSL_CTX *ctx) {
  361. OPENSSL_timeval now;
  362. ssl_ctx_get_current_time(ctx, &now);
  363. {
  364. // Avoid acquiring a write lock in the common case (i.e. a non-default key
  365. // is used or the default keys have not expired yet).
  366. MutexReadLock lock(&ctx->lock);
  367. if (ctx->ticket_key_current &&
  368. (ctx->ticket_key_current->next_rotation_tv_sec == 0 ||
  369. ctx->ticket_key_current->next_rotation_tv_sec > now.tv_sec) &&
  370. (!ctx->ticket_key_prev ||
  371. ctx->ticket_key_prev->next_rotation_tv_sec > now.tv_sec)) {
  372. return 1;
  373. }
  374. }
  375. MutexWriteLock lock(&ctx->lock);
  376. if (!ctx->ticket_key_current ||
  377. (ctx->ticket_key_current->next_rotation_tv_sec != 0 &&
  378. ctx->ticket_key_current->next_rotation_tv_sec <= now.tv_sec)) {
  379. // The current key has not been initialized or it is expired.
  380. auto new_key = bssl::MakeUnique<TicketKey>();
  381. if (!new_key) {
  382. return 0;
  383. }
  384. RAND_bytes(new_key->name, 16);
  385. RAND_bytes(new_key->hmac_key, 16);
  386. RAND_bytes(new_key->aes_key, 16);
  387. new_key->next_rotation_tv_sec =
  388. now.tv_sec + SSL_DEFAULT_TICKET_KEY_ROTATION_INTERVAL;
  389. if (ctx->ticket_key_current) {
  390. // The current key expired. Rotate it to prev and bump up its rotation
  391. // timestamp. Note that even with the new rotation time it may still be
  392. // expired and get dropped below.
  393. ctx->ticket_key_current->next_rotation_tv_sec +=
  394. SSL_DEFAULT_TICKET_KEY_ROTATION_INTERVAL;
  395. ctx->ticket_key_prev = std::move(ctx->ticket_key_current);
  396. }
  397. ctx->ticket_key_current = std::move(new_key);
  398. }
  399. // Drop an expired prev key.
  400. if (ctx->ticket_key_prev &&
  401. ctx->ticket_key_prev->next_rotation_tv_sec <= now.tv_sec) {
  402. ctx->ticket_key_prev.reset();
  403. }
  404. return 1;
  405. }
  406. static int ssl_encrypt_ticket_with_cipher_ctx(SSL_HANDSHAKE *hs, CBB *out,
  407. const uint8_t *session_buf,
  408. size_t session_len) {
  409. ScopedEVP_CIPHER_CTX ctx;
  410. ScopedHMAC_CTX hctx;
  411. // If the session is too long, emit a dummy value rather than abort the
  412. // connection.
  413. static const size_t kMaxTicketOverhead =
  414. 16 + EVP_MAX_IV_LENGTH + EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE;
  415. if (session_len > 0xffff - kMaxTicketOverhead) {
  416. static const char kTicketPlaceholder[] = "TICKET TOO LARGE";
  417. return CBB_add_bytes(out, (const uint8_t *)kTicketPlaceholder,
  418. strlen(kTicketPlaceholder));
  419. }
  420. // Initialize HMAC and cipher contexts. If callback present it does all the
  421. // work otherwise use generated values from parent ctx.
  422. SSL_CTX *tctx = hs->ssl->session_ctx.get();
  423. uint8_t iv[EVP_MAX_IV_LENGTH];
  424. uint8_t key_name[16];
  425. if (tctx->ticket_key_cb != NULL) {
  426. if (tctx->ticket_key_cb(hs->ssl, key_name, iv, ctx.get(), hctx.get(),
  427. 1 /* encrypt */) < 0) {
  428. return 0;
  429. }
  430. } else {
  431. // Rotate ticket key if necessary.
  432. if (!ssl_ctx_rotate_ticket_encryption_key(tctx)) {
  433. return 0;
  434. }
  435. MutexReadLock lock(&tctx->lock);
  436. if (!RAND_bytes(iv, 16) ||
  437. !EVP_EncryptInit_ex(ctx.get(), EVP_aes_128_cbc(), NULL,
  438. tctx->ticket_key_current->aes_key, iv) ||
  439. !HMAC_Init_ex(hctx.get(), tctx->ticket_key_current->hmac_key, 16,
  440. tlsext_tick_md(), NULL)) {
  441. return 0;
  442. }
  443. OPENSSL_memcpy(key_name, tctx->ticket_key_current->name, 16);
  444. }
  445. uint8_t *ptr;
  446. if (!CBB_add_bytes(out, key_name, 16) ||
  447. !CBB_add_bytes(out, iv, EVP_CIPHER_CTX_iv_length(ctx.get())) ||
  448. !CBB_reserve(out, &ptr, session_len + EVP_MAX_BLOCK_LENGTH)) {
  449. return 0;
  450. }
  451. size_t total = 0;
  452. #if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
  453. OPENSSL_memcpy(ptr, session_buf, session_len);
  454. total = session_len;
  455. #else
  456. int len;
  457. if (!EVP_EncryptUpdate(ctx.get(), ptr + total, &len, session_buf, session_len)) {
  458. return 0;
  459. }
  460. total += len;
  461. if (!EVP_EncryptFinal_ex(ctx.get(), ptr + total, &len)) {
  462. return 0;
  463. }
  464. total += len;
  465. #endif
  466. if (!CBB_did_write(out, total)) {
  467. return 0;
  468. }
  469. unsigned hlen;
  470. if (!HMAC_Update(hctx.get(), CBB_data(out), CBB_len(out)) ||
  471. !CBB_reserve(out, &ptr, EVP_MAX_MD_SIZE) ||
  472. !HMAC_Final(hctx.get(), ptr, &hlen) ||
  473. !CBB_did_write(out, hlen)) {
  474. return 0;
  475. }
  476. return 1;
  477. }
  478. static int ssl_encrypt_ticket_with_method(SSL_HANDSHAKE *hs, CBB *out,
  479. const uint8_t *session_buf,
  480. size_t session_len) {
  481. SSL *const ssl = hs->ssl;
  482. const SSL_TICKET_AEAD_METHOD *method = ssl->session_ctx->ticket_aead_method;
  483. const size_t max_overhead = method->max_overhead(ssl);
  484. const size_t max_out = session_len + max_overhead;
  485. if (max_out < max_overhead) {
  486. OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
  487. return 0;
  488. }
  489. uint8_t *ptr;
  490. if (!CBB_reserve(out, &ptr, max_out)) {
  491. return 0;
  492. }
  493. size_t out_len;
  494. if (!method->seal(ssl, ptr, &out_len, max_out, session_buf,
  495. session_len)) {
  496. OPENSSL_PUT_ERROR(SSL, SSL_R_TICKET_ENCRYPTION_FAILED);
  497. return 0;
  498. }
  499. if (!CBB_did_write(out, out_len)) {
  500. return 0;
  501. }
  502. return 1;
  503. }
  504. int ssl_encrypt_ticket(SSL_HANDSHAKE *hs, CBB *out,
  505. const SSL_SESSION *session) {
  506. // Serialize the SSL_SESSION to be encoded into the ticket.
  507. uint8_t *session_buf = NULL;
  508. size_t session_len;
  509. if (!SSL_SESSION_to_bytes_for_ticket(session, &session_buf, &session_len)) {
  510. return -1;
  511. }
  512. int ret = 0;
  513. if (hs->ssl->session_ctx->ticket_aead_method) {
  514. ret = ssl_encrypt_ticket_with_method(hs, out, session_buf, session_len);
  515. } else {
  516. ret = ssl_encrypt_ticket_with_cipher_ctx(hs, out, session_buf, session_len);
  517. }
  518. OPENSSL_free(session_buf);
  519. return ret;
  520. }
  521. int ssl_session_is_context_valid(const SSL_HANDSHAKE *hs,
  522. const SSL_SESSION *session) {
  523. if (session == NULL) {
  524. return 0;
  525. }
  526. return session->sid_ctx_length == hs->config->cert->sid_ctx_length &&
  527. OPENSSL_memcmp(session->sid_ctx, hs->config->cert->sid_ctx,
  528. hs->config->cert->sid_ctx_length) == 0;
  529. }
  530. int ssl_session_is_time_valid(const SSL *ssl, const SSL_SESSION *session) {
  531. if (session == NULL) {
  532. return 0;
  533. }
  534. struct OPENSSL_timeval now;
  535. ssl_get_current_time(ssl, &now);
  536. // Reject tickets from the future to avoid underflow.
  537. if (now.tv_sec < session->time) {
  538. return 0;
  539. }
  540. return session->timeout > now.tv_sec - session->time;
  541. }
  542. int ssl_session_is_resumable(const SSL_HANDSHAKE *hs,
  543. const SSL_SESSION *session) {
  544. const SSL *const ssl = hs->ssl;
  545. return ssl_session_is_context_valid(hs, session) &&
  546. // The session must have been created by the same type of end point as
  547. // we're now using it with.
  548. ssl->server == session->is_server &&
  549. // The session must not be expired.
  550. ssl_session_is_time_valid(ssl, session) &&
  551. /* Only resume if the session's version matches the negotiated
  552. * version. */
  553. ssl->version == session->ssl_version &&
  554. // Only resume if the session's cipher matches the negotiated one.
  555. hs->new_cipher == session->cipher &&
  556. // If the session contains a client certificate (either the full
  557. // certificate or just the hash) then require that the form of the
  558. // certificate matches the current configuration.
  559. ((sk_CRYPTO_BUFFER_num(session->certs.get()) == 0 &&
  560. !session->peer_sha256_valid) ||
  561. session->peer_sha256_valid ==
  562. hs->config->retain_only_sha256_of_client_certs);
  563. }
  564. // ssl_lookup_session looks up |session_id| in the session cache and sets
  565. // |*out_session| to an |SSL_SESSION| object if found.
  566. static enum ssl_hs_wait_t ssl_lookup_session(
  567. SSL_HANDSHAKE *hs, UniquePtr<SSL_SESSION> *out_session,
  568. Span<const uint8_t> session_id) {
  569. SSL *const ssl = hs->ssl;
  570. out_session->reset();
  571. if (session_id.empty() || session_id.size() > SSL_MAX_SSL_SESSION_ID_LENGTH) {
  572. return ssl_hs_ok;
  573. }
  574. UniquePtr<SSL_SESSION> session;
  575. // Try the internal cache, if it exists.
  576. if (!(ssl->session_ctx->session_cache_mode &
  577. SSL_SESS_CACHE_NO_INTERNAL_LOOKUP)) {
  578. uint32_t hash = ssl_hash_session_id(session_id);
  579. auto cmp = [](const void *key, const SSL_SESSION *sess) -> int {
  580. Span<const uint8_t> key_id =
  581. *reinterpret_cast<const Span<const uint8_t> *>(key);
  582. Span<const uint8_t> sess_id =
  583. MakeConstSpan(sess->session_id, sess->session_id_length);
  584. return key_id == sess_id ? 0 : 1;
  585. };
  586. MutexReadLock lock(&ssl->session_ctx->lock);
  587. // |lh_SSL_SESSION_retrieve_key| returns a non-owning pointer.
  588. session = UpRef(lh_SSL_SESSION_retrieve_key(ssl->session_ctx->sessions,
  589. &session_id, hash, cmp));
  590. // TODO(davidben): This should probably move it to the front of the list.
  591. }
  592. // Fall back to the external cache, if it exists.
  593. if (!session && ssl->session_ctx->get_session_cb != nullptr) {
  594. int copy = 1;
  595. session.reset(ssl->session_ctx->get_session_cb(ssl, session_id.data(),
  596. session_id.size(), &copy));
  597. if (!session) {
  598. return ssl_hs_ok;
  599. }
  600. if (session.get() == SSL_magic_pending_session_ptr()) {
  601. session.release(); // This pointer is not actually owned.
  602. return ssl_hs_pending_session;
  603. }
  604. // Increment reference count now if the session callback asks us to do so
  605. // (note that if the session structures returned by the callback are shared
  606. // between threads, it must handle the reference count itself [i.e. copy ==
  607. // 0], or things won't be thread-safe).
  608. if (copy) {
  609. SSL_SESSION_up_ref(session.get());
  610. }
  611. // Add the externally cached session to the internal cache if necessary.
  612. if (!(ssl->session_ctx->session_cache_mode &
  613. SSL_SESS_CACHE_NO_INTERNAL_STORE)) {
  614. SSL_CTX_add_session(ssl->session_ctx.get(), session.get());
  615. }
  616. }
  617. if (session && !ssl_session_is_time_valid(ssl, session.get())) {
  618. // The session was from the cache, so remove it.
  619. SSL_CTX_remove_session(ssl->session_ctx.get(), session.get());
  620. session.reset();
  621. }
  622. *out_session = std::move(session);
  623. return ssl_hs_ok;
  624. }
  625. enum ssl_hs_wait_t ssl_get_prev_session(SSL_HANDSHAKE *hs,
  626. UniquePtr<SSL_SESSION> *out_session,
  627. bool *out_tickets_supported,
  628. bool *out_renew_ticket,
  629. const SSL_CLIENT_HELLO *client_hello) {
  630. // This is used only by servers.
  631. assert(hs->ssl->server);
  632. UniquePtr<SSL_SESSION> session;
  633. bool renew_ticket = false;
  634. // If tickets are disabled, always behave as if no tickets are present.
  635. CBS ticket;
  636. const bool tickets_supported =
  637. !(SSL_get_options(hs->ssl) & SSL_OP_NO_TICKET) &&
  638. ssl_client_hello_get_extension(client_hello, &ticket,
  639. TLSEXT_TYPE_session_ticket);
  640. if (tickets_supported && CBS_len(&ticket) != 0) {
  641. switch (ssl_process_ticket(hs, &session, &renew_ticket, ticket,
  642. MakeConstSpan(client_hello->session_id,
  643. client_hello->session_id_len))) {
  644. case ssl_ticket_aead_success:
  645. break;
  646. case ssl_ticket_aead_ignore_ticket:
  647. assert(!session);
  648. break;
  649. case ssl_ticket_aead_error:
  650. return ssl_hs_error;
  651. case ssl_ticket_aead_retry:
  652. return ssl_hs_pending_ticket;
  653. }
  654. } else {
  655. // The client didn't send a ticket, so the session ID is a real ID.
  656. enum ssl_hs_wait_t lookup_ret = ssl_lookup_session(
  657. hs, &session,
  658. MakeConstSpan(client_hello->session_id, client_hello->session_id_len));
  659. if (lookup_ret != ssl_hs_ok) {
  660. return lookup_ret;
  661. }
  662. }
  663. *out_session = std::move(session);
  664. *out_tickets_supported = tickets_supported;
  665. *out_renew_ticket = renew_ticket;
  666. return ssl_hs_ok;
  667. }
  668. static int remove_session_lock(SSL_CTX *ctx, SSL_SESSION *session, int lock) {
  669. int ret = 0;
  670. if (session != NULL && session->session_id_length != 0) {
  671. if (lock) {
  672. CRYPTO_MUTEX_lock_write(&ctx->lock);
  673. }
  674. SSL_SESSION *found_session = lh_SSL_SESSION_retrieve(ctx->sessions,
  675. session);
  676. if (found_session == session) {
  677. ret = 1;
  678. found_session = lh_SSL_SESSION_delete(ctx->sessions, session);
  679. SSL_SESSION_list_remove(ctx, session);
  680. }
  681. if (lock) {
  682. CRYPTO_MUTEX_unlock_write(&ctx->lock);
  683. }
  684. if (ret) {
  685. if (ctx->remove_session_cb != NULL) {
  686. ctx->remove_session_cb(ctx, found_session);
  687. }
  688. SSL_SESSION_free(found_session);
  689. }
  690. }
  691. return ret;
  692. }
  693. void ssl_set_session(SSL *ssl, SSL_SESSION *session) {
  694. if (ssl->session.get() == session) {
  695. return;
  696. }
  697. ssl->session = UpRef(session);
  698. }
  699. // locked by SSL_CTX in the calling function
  700. static void SSL_SESSION_list_remove(SSL_CTX *ctx, SSL_SESSION *session) {
  701. if (session->next == NULL || session->prev == NULL) {
  702. return;
  703. }
  704. if (session->next == (SSL_SESSION *)&ctx->session_cache_tail) {
  705. // last element in list
  706. if (session->prev == (SSL_SESSION *)&ctx->session_cache_head) {
  707. // only one element in list
  708. ctx->session_cache_head = NULL;
  709. ctx->session_cache_tail = NULL;
  710. } else {
  711. ctx->session_cache_tail = session->prev;
  712. session->prev->next = (SSL_SESSION *)&(ctx->session_cache_tail);
  713. }
  714. } else {
  715. if (session->prev == (SSL_SESSION *)&ctx->session_cache_head) {
  716. // first element in list
  717. ctx->session_cache_head = session->next;
  718. session->next->prev = (SSL_SESSION *)&(ctx->session_cache_head);
  719. } else { // middle of list
  720. session->next->prev = session->prev;
  721. session->prev->next = session->next;
  722. }
  723. }
  724. session->prev = session->next = NULL;
  725. }
  726. static void SSL_SESSION_list_add(SSL_CTX *ctx, SSL_SESSION *session) {
  727. if (session->next != NULL && session->prev != NULL) {
  728. SSL_SESSION_list_remove(ctx, session);
  729. }
  730. if (ctx->session_cache_head == NULL) {
  731. ctx->session_cache_head = session;
  732. ctx->session_cache_tail = session;
  733. session->prev = (SSL_SESSION *)&(ctx->session_cache_head);
  734. session->next = (SSL_SESSION *)&(ctx->session_cache_tail);
  735. } else {
  736. session->next = ctx->session_cache_head;
  737. session->next->prev = session;
  738. session->prev = (SSL_SESSION *)&(ctx->session_cache_head);
  739. ctx->session_cache_head = session;
  740. }
  741. }
  742. BSSL_NAMESPACE_END
  743. using namespace bssl;
  744. ssl_session_st::ssl_session_st(const SSL_X509_METHOD *method)
  745. : x509_method(method),
  746. extended_master_secret(false),
  747. peer_sha256_valid(false),
  748. not_resumable(false),
  749. ticket_age_add_valid(false),
  750. is_server(false) {
  751. CRYPTO_new_ex_data(&ex_data);
  752. time = ::time(nullptr);
  753. }
  754. ssl_session_st::~ssl_session_st() {
  755. CRYPTO_free_ex_data(&g_ex_data_class, this, &ex_data);
  756. x509_method->session_clear(this);
  757. }
  758. SSL_SESSION *SSL_SESSION_new(const SSL_CTX *ctx) {
  759. return ssl_session_new(ctx->x509_method).release();
  760. }
  761. int SSL_SESSION_up_ref(SSL_SESSION *session) {
  762. CRYPTO_refcount_inc(&session->references);
  763. return 1;
  764. }
  765. void SSL_SESSION_free(SSL_SESSION *session) {
  766. if (session == NULL ||
  767. !CRYPTO_refcount_dec_and_test_zero(&session->references)) {
  768. return;
  769. }
  770. session->~ssl_session_st();
  771. OPENSSL_free(session);
  772. }
  773. const uint8_t *SSL_SESSION_get_id(const SSL_SESSION *session,
  774. unsigned *out_len) {
  775. if (out_len != NULL) {
  776. *out_len = session->session_id_length;
  777. }
  778. return session->session_id;
  779. }
  780. int SSL_SESSION_set1_id(SSL_SESSION *session, const uint8_t *sid,
  781. size_t sid_len) {
  782. if (sid_len > SSL_MAX_SSL_SESSION_ID_LENGTH) {
  783. OPENSSL_PUT_ERROR(SSL, SSL_R_SSL_SESSION_ID_TOO_LONG);
  784. return 0;
  785. }
  786. // Use memmove in case someone passes in the output of |SSL_SESSION_get_id|.
  787. OPENSSL_memmove(session->session_id, sid, sid_len);
  788. session->session_id_length = sid_len;
  789. return 1;
  790. }
  791. uint32_t SSL_SESSION_get_timeout(const SSL_SESSION *session) {
  792. return session->timeout;
  793. }
  794. uint64_t SSL_SESSION_get_time(const SSL_SESSION *session) {
  795. if (session == NULL) {
  796. // NULL should crash, but silently accept it here for compatibility.
  797. return 0;
  798. }
  799. return session->time;
  800. }
  801. X509 *SSL_SESSION_get0_peer(const SSL_SESSION *session) {
  802. return session->x509_peer;
  803. }
  804. const STACK_OF(CRYPTO_BUFFER) *
  805. SSL_SESSION_get0_peer_certificates(const SSL_SESSION *session) {
  806. return session->certs.get();
  807. }
  808. void SSL_SESSION_get0_signed_cert_timestamp_list(const SSL_SESSION *session,
  809. const uint8_t **out,
  810. size_t *out_len) {
  811. if (session->signed_cert_timestamp_list) {
  812. *out = CRYPTO_BUFFER_data(session->signed_cert_timestamp_list.get());
  813. *out_len = CRYPTO_BUFFER_len(session->signed_cert_timestamp_list.get());
  814. } else {
  815. *out = nullptr;
  816. *out_len = 0;
  817. }
  818. }
  819. void SSL_SESSION_get0_ocsp_response(const SSL_SESSION *session,
  820. const uint8_t **out, size_t *out_len) {
  821. if (session->ocsp_response) {
  822. *out = CRYPTO_BUFFER_data(session->ocsp_response.get());
  823. *out_len = CRYPTO_BUFFER_len(session->ocsp_response.get());
  824. } else {
  825. *out = nullptr;
  826. *out_len = 0;
  827. }
  828. }
  829. size_t SSL_SESSION_get_master_key(const SSL_SESSION *session, uint8_t *out,
  830. size_t max_out) {
  831. // TODO(davidben): Fix master_key_length's type and remove these casts.
  832. if (max_out == 0) {
  833. return (size_t)session->master_key_length;
  834. }
  835. if (max_out > (size_t)session->master_key_length) {
  836. max_out = (size_t)session->master_key_length;
  837. }
  838. OPENSSL_memcpy(out, session->master_key, max_out);
  839. return max_out;
  840. }
  841. uint64_t SSL_SESSION_set_time(SSL_SESSION *session, uint64_t time) {
  842. if (session == NULL) {
  843. return 0;
  844. }
  845. session->time = time;
  846. return time;
  847. }
  848. uint32_t SSL_SESSION_set_timeout(SSL_SESSION *session, uint32_t timeout) {
  849. if (session == NULL) {
  850. return 0;
  851. }
  852. session->timeout = timeout;
  853. session->auth_timeout = timeout;
  854. return 1;
  855. }
  856. const uint8_t *SSL_SESSION_get0_id_context(const SSL_SESSION *session,
  857. unsigned *out_len) {
  858. if (out_len != NULL) {
  859. *out_len = session->sid_ctx_length;
  860. }
  861. return session->sid_ctx;
  862. }
  863. int SSL_SESSION_set1_id_context(SSL_SESSION *session, const uint8_t *sid_ctx,
  864. size_t sid_ctx_len) {
  865. if (sid_ctx_len > sizeof(session->sid_ctx)) {
  866. OPENSSL_PUT_ERROR(SSL, SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
  867. return 0;
  868. }
  869. static_assert(sizeof(session->sid_ctx) < 256, "sid_ctx_len does not fit");
  870. session->sid_ctx_length = (uint8_t)sid_ctx_len;
  871. OPENSSL_memcpy(session->sid_ctx, sid_ctx, sid_ctx_len);
  872. return 1;
  873. }
  874. int SSL_SESSION_should_be_single_use(const SSL_SESSION *session) {
  875. return ssl_session_protocol_version(session) >= TLS1_3_VERSION;
  876. }
  877. int SSL_SESSION_is_resumable(const SSL_SESSION *session) {
  878. return !session->not_resumable;
  879. }
  880. int SSL_SESSION_has_ticket(const SSL_SESSION *session) {
  881. return !session->ticket.empty();
  882. }
  883. void SSL_SESSION_get0_ticket(const SSL_SESSION *session,
  884. const uint8_t **out_ticket, size_t *out_len) {
  885. if (out_ticket != nullptr) {
  886. *out_ticket = session->ticket.data();
  887. }
  888. *out_len = session->ticket.size();
  889. }
  890. int SSL_SESSION_set_ticket(SSL_SESSION *session, const uint8_t *ticket,
  891. size_t ticket_len) {
  892. return session->ticket.CopyFrom(MakeConstSpan(ticket, ticket_len));
  893. }
  894. uint32_t SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *session) {
  895. return session->ticket_lifetime_hint;
  896. }
  897. const SSL_CIPHER *SSL_SESSION_get0_cipher(const SSL_SESSION *session) {
  898. return session->cipher;
  899. }
  900. int SSL_SESSION_has_peer_sha256(const SSL_SESSION *session) {
  901. return session->peer_sha256_valid;
  902. }
  903. void SSL_SESSION_get0_peer_sha256(const SSL_SESSION *session,
  904. const uint8_t **out_ptr, size_t *out_len) {
  905. if (session->peer_sha256_valid) {
  906. *out_ptr = session->peer_sha256;
  907. *out_len = sizeof(session->peer_sha256);
  908. } else {
  909. *out_ptr = nullptr;
  910. *out_len = 0;
  911. }
  912. }
  913. int SSL_SESSION_early_data_capable(const SSL_SESSION *session) {
  914. return ssl_session_protocol_version(session) >= TLS1_3_VERSION &&
  915. session->ticket_max_early_data != 0;
  916. }
  917. SSL_SESSION *SSL_magic_pending_session_ptr(void) {
  918. return (SSL_SESSION *)&g_pending_session_magic;
  919. }
  920. SSL_SESSION *SSL_get_session(const SSL *ssl) {
  921. // Once the handshake completes we return the established session. Otherwise
  922. // we return the intermediate session, either |session| (for resumption) or
  923. // |new_session| if doing a full handshake.
  924. if (!SSL_in_init(ssl)) {
  925. return ssl->s3->established_session.get();
  926. }
  927. SSL_HANDSHAKE *hs = ssl->s3->hs.get();
  928. if (hs->early_session) {
  929. return hs->early_session.get();
  930. }
  931. if (hs->new_session) {
  932. return hs->new_session.get();
  933. }
  934. return ssl->session.get();
  935. }
  936. SSL_SESSION *SSL_get1_session(SSL *ssl) {
  937. SSL_SESSION *ret = SSL_get_session(ssl);
  938. if (ret != NULL) {
  939. SSL_SESSION_up_ref(ret);
  940. }
  941. return ret;
  942. }
  943. int SSL_SESSION_get_ex_new_index(long argl, void *argp,
  944. CRYPTO_EX_unused *unused,
  945. CRYPTO_EX_dup *dup_unused,
  946. CRYPTO_EX_free *free_func) {
  947. int index;
  948. if (!CRYPTO_get_ex_new_index(&g_ex_data_class, &index, argl, argp,
  949. free_func)) {
  950. return -1;
  951. }
  952. return index;
  953. }
  954. int SSL_SESSION_set_ex_data(SSL_SESSION *session, int idx, void *arg) {
  955. return CRYPTO_set_ex_data(&session->ex_data, idx, arg);
  956. }
  957. void *SSL_SESSION_get_ex_data(const SSL_SESSION *session, int idx) {
  958. return CRYPTO_get_ex_data(&session->ex_data, idx);
  959. }
  960. int SSL_CTX_add_session(SSL_CTX *ctx, SSL_SESSION *session) {
  961. // Although |session| is inserted into two structures (a doubly-linked list
  962. // and the hash table), |ctx| only takes one reference.
  963. UniquePtr<SSL_SESSION> owned_session = UpRef(session);
  964. SSL_SESSION *old_session;
  965. MutexWriteLock lock(&ctx->lock);
  966. if (!lh_SSL_SESSION_insert(ctx->sessions, &old_session, session)) {
  967. return 0;
  968. }
  969. // |ctx->sessions| took ownership of |session| and gave us back a reference to
  970. // |old_session|. (|old_session| may be the same as |session|, in which case
  971. // we traded identical references with |ctx->sessions|.)
  972. owned_session.release();
  973. owned_session.reset(old_session);
  974. if (old_session != NULL) {
  975. if (old_session == session) {
  976. // |session| was already in the cache. There are no linked list pointers
  977. // to update.
  978. return 0;
  979. }
  980. // There was a session ID collision. |old_session| was replaced with
  981. // |session| in the hash table, so |old_session| must be removed from the
  982. // linked list to match.
  983. SSL_SESSION_list_remove(ctx, old_session);
  984. }
  985. SSL_SESSION_list_add(ctx, session);
  986. // Enforce any cache size limits.
  987. if (SSL_CTX_sess_get_cache_size(ctx) > 0) {
  988. while (lh_SSL_SESSION_num_items(ctx->sessions) >
  989. SSL_CTX_sess_get_cache_size(ctx)) {
  990. if (!remove_session_lock(ctx, ctx->session_cache_tail, 0)) {
  991. break;
  992. }
  993. }
  994. }
  995. return 1;
  996. }
  997. int SSL_CTX_remove_session(SSL_CTX *ctx, SSL_SESSION *session) {
  998. return remove_session_lock(ctx, session, 1);
  999. }
  1000. int SSL_set_session(SSL *ssl, SSL_SESSION *session) {
  1001. // SSL_set_session may only be called before the handshake has started.
  1002. if (ssl->s3->initial_handshake_complete ||
  1003. ssl->s3->hs == NULL ||
  1004. ssl->s3->hs->state != 0) {
  1005. abort();
  1006. }
  1007. ssl_set_session(ssl, session);
  1008. return 1;
  1009. }
  1010. uint32_t SSL_CTX_set_timeout(SSL_CTX *ctx, uint32_t timeout) {
  1011. if (ctx == NULL) {
  1012. return 0;
  1013. }
  1014. // Historically, zero was treated as |SSL_DEFAULT_SESSION_TIMEOUT|.
  1015. if (timeout == 0) {
  1016. timeout = SSL_DEFAULT_SESSION_TIMEOUT;
  1017. }
  1018. uint32_t old_timeout = ctx->session_timeout;
  1019. ctx->session_timeout = timeout;
  1020. return old_timeout;
  1021. }
  1022. uint32_t SSL_CTX_get_timeout(const SSL_CTX *ctx) {
  1023. if (ctx == NULL) {
  1024. return 0;
  1025. }
  1026. return ctx->session_timeout;
  1027. }
  1028. void SSL_CTX_set_session_psk_dhe_timeout(SSL_CTX *ctx, uint32_t timeout) {
  1029. ctx->session_psk_dhe_timeout = timeout;
  1030. }
  1031. typedef struct timeout_param_st {
  1032. SSL_CTX *ctx;
  1033. uint64_t time;
  1034. LHASH_OF(SSL_SESSION) *cache;
  1035. } TIMEOUT_PARAM;
  1036. static void timeout_doall_arg(SSL_SESSION *session, void *void_param) {
  1037. TIMEOUT_PARAM *param = reinterpret_cast<TIMEOUT_PARAM *>(void_param);
  1038. if (param->time == 0 ||
  1039. session->time + session->timeout < session->time ||
  1040. param->time > (session->time + session->timeout)) {
  1041. // The reason we don't call SSL_CTX_remove_session() is to
  1042. // save on locking overhead
  1043. (void) lh_SSL_SESSION_delete(param->cache, session);
  1044. SSL_SESSION_list_remove(param->ctx, session);
  1045. if (param->ctx->remove_session_cb != NULL) {
  1046. param->ctx->remove_session_cb(param->ctx, session);
  1047. }
  1048. SSL_SESSION_free(session);
  1049. }
  1050. }
  1051. void SSL_CTX_flush_sessions(SSL_CTX *ctx, uint64_t time) {
  1052. TIMEOUT_PARAM tp;
  1053. tp.ctx = ctx;
  1054. tp.cache = ctx->sessions;
  1055. if (tp.cache == NULL) {
  1056. return;
  1057. }
  1058. tp.time = time;
  1059. MutexWriteLock lock(&ctx->lock);
  1060. lh_SSL_SESSION_doall_arg(tp.cache, timeout_doall_arg, &tp);
  1061. }
  1062. void SSL_CTX_sess_set_new_cb(SSL_CTX *ctx,
  1063. int (*cb)(SSL *ssl, SSL_SESSION *session)) {
  1064. ctx->new_session_cb = cb;
  1065. }
  1066. int (*SSL_CTX_sess_get_new_cb(SSL_CTX *ctx))(SSL *ssl, SSL_SESSION *session) {
  1067. return ctx->new_session_cb;
  1068. }
  1069. void SSL_CTX_sess_set_remove_cb(
  1070. SSL_CTX *ctx, void (*cb)(SSL_CTX *ctx, SSL_SESSION *session)) {
  1071. ctx->remove_session_cb = cb;
  1072. }
  1073. void (*SSL_CTX_sess_get_remove_cb(SSL_CTX *ctx))(SSL_CTX *ctx,
  1074. SSL_SESSION *session) {
  1075. return ctx->remove_session_cb;
  1076. }
  1077. void SSL_CTX_sess_set_get_cb(SSL_CTX *ctx,
  1078. SSL_SESSION *(*cb)(SSL *ssl, const uint8_t *id,
  1079. int id_len, int *out_copy)) {
  1080. ctx->get_session_cb = cb;
  1081. }
  1082. SSL_SESSION *(*SSL_CTX_sess_get_get_cb(SSL_CTX *ctx))(SSL *ssl,
  1083. const uint8_t *id,
  1084. int id_len,
  1085. int *out_copy) {
  1086. return ctx->get_session_cb;
  1087. }
  1088. void SSL_CTX_set_info_callback(
  1089. SSL_CTX *ctx, void (*cb)(const SSL *ssl, int type, int value)) {
  1090. ctx->info_callback = cb;
  1091. }
  1092. void (*SSL_CTX_get_info_callback(SSL_CTX *ctx))(const SSL *ssl, int type,
  1093. int value) {
  1094. return ctx->info_callback;
  1095. }
  1096. void SSL_CTX_set_channel_id_cb(SSL_CTX *ctx,
  1097. void (*cb)(SSL *ssl, EVP_PKEY **pkey)) {
  1098. ctx->channel_id_cb = cb;
  1099. }
  1100. void (*SSL_CTX_get_channel_id_cb(SSL_CTX *ctx))(SSL *ssl, EVP_PKEY **pkey) {
  1101. return ctx->channel_id_cb;
  1102. }