xref: /aosp_15_r20/external/boringssl/src/ssl/ssl_session.cc (revision 8fb009dc861624b67b6cdb62ea21f0f22d0c584b)
1 /* Copyright (C) 1995-1998 Eric Young ([email protected])
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young ([email protected]).
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 ([email protected]).
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 ([email protected])"
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 ([email protected])"
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  *    [email protected].
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  * ([email protected]).  This product includes software written by Tim
107  * Hudson ([email protected]).
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 
136 #include <openssl/ssl.h>
137 
138 #include <assert.h>
139 #include <stdlib.h>
140 #include <string.h>
141 
142 #include <utility>
143 
144 #include <openssl/err.h>
145 #include <openssl/hmac.h>
146 #include <openssl/lhash.h>
147 #include <openssl/mem.h>
148 #include <openssl/rand.h>
149 
150 #include "internal.h"
151 #include "../crypto/internal.h"
152 
153 
154 BSSL_NAMESPACE_BEGIN
155 
156 // The address of this is a magic value, a pointer to which is returned by
157 // SSL_magic_pending_session_ptr(). It allows a session callback to indicate
158 // that it needs to asynchronously fetch session information.
159 static const char g_pending_session_magic = 0;
160 
161 static CRYPTO_EX_DATA_CLASS g_ex_data_class =
162     CRYPTO_EX_DATA_CLASS_INIT_WITH_APP_DATA;
163 
164 static void SSL_SESSION_list_remove(SSL_CTX *ctx, SSL_SESSION *session);
165 static void SSL_SESSION_list_add(SSL_CTX *ctx, SSL_SESSION *session);
166 
ssl_session_new(const SSL_X509_METHOD * x509_method)167 UniquePtr<SSL_SESSION> ssl_session_new(const SSL_X509_METHOD *x509_method) {
168   return MakeUnique<SSL_SESSION>(x509_method);
169 }
170 
ssl_hash_session_id(Span<const uint8_t> session_id)171 uint32_t ssl_hash_session_id(Span<const uint8_t> session_id) {
172   // Take the first four bytes of |session_id|. Session IDs are generated by the
173   // server randomly, so we can assume even using the first four bytes results
174   // in a good distribution.
175   uint8_t tmp_storage[sizeof(uint32_t)];
176   if (session_id.size() < sizeof(tmp_storage)) {
177     OPENSSL_memset(tmp_storage, 0, sizeof(tmp_storage));
178     OPENSSL_memcpy(tmp_storage, session_id.data(), session_id.size());
179     session_id = tmp_storage;
180   }
181 
182   uint32_t hash =
183       ((uint32_t)session_id[0]) |
184       ((uint32_t)session_id[1] << 8) |
185       ((uint32_t)session_id[2] << 16) |
186       ((uint32_t)session_id[3] << 24);
187 
188   return hash;
189 }
190 
SSL_SESSION_dup(SSL_SESSION * session,int dup_flags)191 UniquePtr<SSL_SESSION> SSL_SESSION_dup(SSL_SESSION *session, int dup_flags) {
192   UniquePtr<SSL_SESSION> new_session = ssl_session_new(session->x509_method);
193   if (!new_session) {
194     return nullptr;
195   }
196 
197   new_session->is_server = session->is_server;
198   new_session->ssl_version = session->ssl_version;
199   new_session->is_quic = session->is_quic;
200   new_session->sid_ctx_length = session->sid_ctx_length;
201   OPENSSL_memcpy(new_session->sid_ctx, session->sid_ctx, session->sid_ctx_length);
202 
203   // Copy the key material.
204   new_session->secret_length = session->secret_length;
205   OPENSSL_memcpy(new_session->secret, session->secret, session->secret_length);
206   new_session->cipher = session->cipher;
207 
208   // Copy authentication state.
209   if (session->psk_identity != nullptr) {
210     new_session->psk_identity.reset(
211         OPENSSL_strdup(session->psk_identity.get()));
212     if (new_session->psk_identity == nullptr) {
213       return nullptr;
214     }
215   }
216   if (session->certs != nullptr) {
217     auto buf_up_ref = [](const CRYPTO_BUFFER *buf) {
218       CRYPTO_BUFFER_up_ref(const_cast<CRYPTO_BUFFER *>(buf));
219       return const_cast<CRYPTO_BUFFER*>(buf);
220     };
221     new_session->certs.reset(sk_CRYPTO_BUFFER_deep_copy(
222         session->certs.get(), buf_up_ref, CRYPTO_BUFFER_free));
223     if (new_session->certs == nullptr) {
224       return nullptr;
225     }
226   }
227 
228   if (!session->x509_method->session_dup(new_session.get(), session)) {
229     return nullptr;
230   }
231 
232   new_session->verify_result = session->verify_result;
233 
234   new_session->ocsp_response = UpRef(session->ocsp_response);
235   new_session->signed_cert_timestamp_list =
236       UpRef(session->signed_cert_timestamp_list);
237 
238   OPENSSL_memcpy(new_session->peer_sha256, session->peer_sha256,
239                  SHA256_DIGEST_LENGTH);
240   new_session->peer_sha256_valid = session->peer_sha256_valid;
241 
242   new_session->peer_signature_algorithm = session->peer_signature_algorithm;
243 
244   new_session->timeout = session->timeout;
245   new_session->auth_timeout = session->auth_timeout;
246   new_session->time = session->time;
247 
248   // Copy non-authentication connection properties.
249   if (dup_flags & SSL_SESSION_INCLUDE_NONAUTH) {
250     new_session->session_id_length = session->session_id_length;
251     OPENSSL_memcpy(new_session->session_id, session->session_id,
252                    session->session_id_length);
253 
254     new_session->group_id = session->group_id;
255 
256     OPENSSL_memcpy(new_session->original_handshake_hash,
257                    session->original_handshake_hash,
258                    session->original_handshake_hash_len);
259     new_session->original_handshake_hash_len =
260         session->original_handshake_hash_len;
261     new_session->ticket_lifetime_hint = session->ticket_lifetime_hint;
262     new_session->ticket_age_add = session->ticket_age_add;
263     new_session->ticket_max_early_data = session->ticket_max_early_data;
264     new_session->extended_master_secret = session->extended_master_secret;
265     new_session->has_application_settings = session->has_application_settings;
266 
267     if (!new_session->early_alpn.CopyFrom(session->early_alpn) ||
268         !new_session->quic_early_data_context.CopyFrom(
269             session->quic_early_data_context) ||
270         !new_session->local_application_settings.CopyFrom(
271             session->local_application_settings) ||
272         !new_session->peer_application_settings.CopyFrom(
273             session->peer_application_settings)) {
274       return nullptr;
275     }
276   }
277 
278   // Copy the ticket.
279   if (dup_flags & SSL_SESSION_INCLUDE_TICKET &&
280       !new_session->ticket.CopyFrom(session->ticket)) {
281     return nullptr;
282   }
283 
284   // The new_session does not get a copy of the ex_data.
285 
286   new_session->not_resumable = true;
287   return new_session;
288 }
289 
ssl_session_rebase_time(SSL * ssl,SSL_SESSION * session)290 void ssl_session_rebase_time(SSL *ssl, SSL_SESSION *session) {
291   struct OPENSSL_timeval now;
292   ssl_get_current_time(ssl, &now);
293 
294   // To avoid overflows and underflows, if we've gone back in time, update the
295   // time, but mark the session expired.
296   if (session->time > now.tv_sec) {
297     session->time = now.tv_sec;
298     session->timeout = 0;
299     session->auth_timeout = 0;
300     return;
301   }
302 
303   // Adjust the session time and timeouts. If the session has already expired,
304   // clamp the timeouts at zero.
305   uint64_t delta = now.tv_sec - session->time;
306   session->time = now.tv_sec;
307   if (session->timeout < delta) {
308     session->timeout = 0;
309   } else {
310     session->timeout -= delta;
311   }
312   if (session->auth_timeout < delta) {
313     session->auth_timeout = 0;
314   } else {
315     session->auth_timeout -= delta;
316   }
317 }
318 
ssl_session_renew_timeout(SSL * ssl,SSL_SESSION * session,uint32_t timeout)319 void ssl_session_renew_timeout(SSL *ssl, SSL_SESSION *session,
320                                uint32_t timeout) {
321   // Rebase the timestamp relative to the current time so |timeout| is measured
322   // correctly.
323   ssl_session_rebase_time(ssl, session);
324 
325   if (session->timeout > timeout) {
326     return;
327   }
328 
329   session->timeout = timeout;
330   if (session->timeout > session->auth_timeout) {
331     session->timeout = session->auth_timeout;
332   }
333 }
334 
ssl_session_protocol_version(const SSL_SESSION * session)335 uint16_t ssl_session_protocol_version(const SSL_SESSION *session) {
336   uint16_t ret;
337   if (!ssl_protocol_version_from_wire(&ret, session->ssl_version)) {
338     // An |SSL_SESSION| will never have an invalid version. This is enforced by
339     // the parser.
340     assert(0);
341     return 0;
342   }
343 
344   return ret;
345 }
346 
ssl_session_get_digest(const SSL_SESSION * session)347 const EVP_MD *ssl_session_get_digest(const SSL_SESSION *session) {
348   return ssl_get_handshake_digest(ssl_session_protocol_version(session),
349                                   session->cipher);
350 }
351 
ssl_get_new_session(SSL_HANDSHAKE * hs)352 bool ssl_get_new_session(SSL_HANDSHAKE *hs) {
353   SSL *const ssl = hs->ssl;
354   if (ssl->mode & SSL_MODE_NO_SESSION_CREATION) {
355     OPENSSL_PUT_ERROR(SSL, SSL_R_SESSION_MAY_NOT_BE_CREATED);
356     return false;
357   }
358 
359   UniquePtr<SSL_SESSION> session = ssl_session_new(ssl->ctx->x509_method);
360   if (session == NULL) {
361     return false;
362   }
363 
364   session->is_server = ssl->server;
365   session->ssl_version = ssl->version;
366   session->is_quic = ssl->quic_method != nullptr;
367 
368   // Fill in the time from the |SSL_CTX|'s clock.
369   struct OPENSSL_timeval now;
370   ssl_get_current_time(ssl, &now);
371   session->time = now.tv_sec;
372 
373   uint16_t version = ssl_protocol_version(ssl);
374   if (version >= TLS1_3_VERSION) {
375     // TLS 1.3 uses tickets as authenticators, so we are willing to use them for
376     // longer.
377     session->timeout = ssl->session_ctx->session_psk_dhe_timeout;
378     session->auth_timeout = SSL_DEFAULT_SESSION_AUTH_TIMEOUT;
379   } else {
380     // TLS 1.2 resumption does not incorporate new key material, so we use a
381     // much shorter timeout.
382     session->timeout = ssl->session_ctx->session_timeout;
383     session->auth_timeout = ssl->session_ctx->session_timeout;
384   }
385 
386   if (hs->config->cert->sid_ctx_length > sizeof(session->sid_ctx)) {
387     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
388     return false;
389   }
390   OPENSSL_memcpy(session->sid_ctx, hs->config->cert->sid_ctx,
391                  hs->config->cert->sid_ctx_length);
392   session->sid_ctx_length = hs->config->cert->sid_ctx_length;
393 
394   // The session is marked not resumable until it is completely filled in.
395   session->not_resumable = true;
396   session->verify_result = X509_V_ERR_INVALID_CALL;
397 
398   hs->new_session = std::move(session);
399   ssl_set_session(ssl, NULL);
400   return true;
401 }
402 
ssl_ctx_rotate_ticket_encryption_key(SSL_CTX * ctx)403 bool ssl_ctx_rotate_ticket_encryption_key(SSL_CTX *ctx) {
404   OPENSSL_timeval now;
405   ssl_ctx_get_current_time(ctx, &now);
406   {
407     // Avoid acquiring a write lock in the common case (i.e. a non-default key
408     // is used or the default keys have not expired yet).
409     MutexReadLock lock(&ctx->lock);
410     if (ctx->ticket_key_current &&
411         (ctx->ticket_key_current->next_rotation_tv_sec == 0 ||
412          ctx->ticket_key_current->next_rotation_tv_sec > now.tv_sec) &&
413         (!ctx->ticket_key_prev ||
414          ctx->ticket_key_prev->next_rotation_tv_sec > now.tv_sec)) {
415       return true;
416     }
417   }
418 
419   MutexWriteLock lock(&ctx->lock);
420   if (!ctx->ticket_key_current ||
421       (ctx->ticket_key_current->next_rotation_tv_sec != 0 &&
422        ctx->ticket_key_current->next_rotation_tv_sec <= now.tv_sec)) {
423     // The current key has not been initialized or it is expired.
424     auto new_key = bssl::MakeUnique<TicketKey>();
425     if (!new_key) {
426       return false;
427     }
428     RAND_bytes(new_key->name, 16);
429     RAND_bytes(new_key->hmac_key, 16);
430     RAND_bytes(new_key->aes_key, 16);
431     new_key->next_rotation_tv_sec =
432         now.tv_sec + SSL_DEFAULT_TICKET_KEY_ROTATION_INTERVAL;
433     if (ctx->ticket_key_current) {
434       // The current key expired. Rotate it to prev and bump up its rotation
435       // timestamp. Note that even with the new rotation time it may still be
436       // expired and get dropped below.
437       ctx->ticket_key_current->next_rotation_tv_sec +=
438           SSL_DEFAULT_TICKET_KEY_ROTATION_INTERVAL;
439       ctx->ticket_key_prev = std::move(ctx->ticket_key_current);
440     }
441     ctx->ticket_key_current = std::move(new_key);
442   }
443 
444   // Drop an expired prev key.
445   if (ctx->ticket_key_prev &&
446       ctx->ticket_key_prev->next_rotation_tv_sec <= now.tv_sec) {
447     ctx->ticket_key_prev.reset();
448   }
449 
450   return true;
451 }
452 
ssl_encrypt_ticket_with_cipher_ctx(SSL_HANDSHAKE * hs,CBB * out,const uint8_t * session_buf,size_t session_len)453 static int ssl_encrypt_ticket_with_cipher_ctx(SSL_HANDSHAKE *hs, CBB *out,
454                                               const uint8_t *session_buf,
455                                               size_t session_len) {
456   ScopedEVP_CIPHER_CTX ctx;
457   ScopedHMAC_CTX hctx;
458 
459   // If the session is too long, emit a dummy value rather than abort the
460   // connection.
461   static const size_t kMaxTicketOverhead =
462       16 + EVP_MAX_IV_LENGTH + EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE;
463   if (session_len > 0xffff - kMaxTicketOverhead) {
464     static const char kTicketPlaceholder[] = "TICKET TOO LARGE";
465     return CBB_add_bytes(out, (const uint8_t *)kTicketPlaceholder,
466                          strlen(kTicketPlaceholder));
467   }
468 
469   // Initialize HMAC and cipher contexts. If callback present it does all the
470   // work otherwise use generated values from parent ctx.
471   SSL_CTX *tctx = hs->ssl->session_ctx.get();
472   uint8_t iv[EVP_MAX_IV_LENGTH];
473   uint8_t key_name[16];
474   if (tctx->ticket_key_cb != NULL) {
475     if (tctx->ticket_key_cb(hs->ssl, key_name, iv, ctx.get(), hctx.get(),
476                             1 /* encrypt */) < 0) {
477       return 0;
478     }
479   } else {
480     // Rotate ticket key if necessary.
481     if (!ssl_ctx_rotate_ticket_encryption_key(tctx)) {
482       return 0;
483     }
484     MutexReadLock lock(&tctx->lock);
485     if (!RAND_bytes(iv, 16) ||
486         !EVP_EncryptInit_ex(ctx.get(), EVP_aes_128_cbc(), NULL,
487                             tctx->ticket_key_current->aes_key, iv) ||
488         !HMAC_Init_ex(hctx.get(), tctx->ticket_key_current->hmac_key, 16,
489                       tlsext_tick_md(), NULL)) {
490       return 0;
491     }
492     OPENSSL_memcpy(key_name, tctx->ticket_key_current->name, 16);
493   }
494 
495   uint8_t *ptr;
496   if (!CBB_add_bytes(out, key_name, 16) ||
497       !CBB_add_bytes(out, iv, EVP_CIPHER_CTX_iv_length(ctx.get())) ||
498       !CBB_reserve(out, &ptr, session_len + EVP_MAX_BLOCK_LENGTH)) {
499     return 0;
500   }
501 
502   size_t total = 0;
503 #if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
504   OPENSSL_memcpy(ptr, session_buf, session_len);
505   total = session_len;
506 #else
507   int len;
508   if (!EVP_EncryptUpdate(ctx.get(), ptr + total, &len, session_buf, session_len)) {
509     return 0;
510   }
511   total += len;
512   if (!EVP_EncryptFinal_ex(ctx.get(), ptr + total, &len)) {
513     return 0;
514   }
515   total += len;
516 #endif
517   if (!CBB_did_write(out, total)) {
518     return 0;
519   }
520 
521   unsigned hlen;
522   if (!HMAC_Update(hctx.get(), CBB_data(out), CBB_len(out)) ||
523       !CBB_reserve(out, &ptr, EVP_MAX_MD_SIZE) ||
524       !HMAC_Final(hctx.get(), ptr, &hlen) ||
525       !CBB_did_write(out, hlen)) {
526     return 0;
527   }
528 
529   return 1;
530 }
531 
ssl_encrypt_ticket_with_method(SSL_HANDSHAKE * hs,CBB * out,const uint8_t * session_buf,size_t session_len)532 static int ssl_encrypt_ticket_with_method(SSL_HANDSHAKE *hs, CBB *out,
533                                           const uint8_t *session_buf,
534                                           size_t session_len) {
535   SSL *const ssl = hs->ssl;
536   const SSL_TICKET_AEAD_METHOD *method = ssl->session_ctx->ticket_aead_method;
537   const size_t max_overhead = method->max_overhead(ssl);
538   const size_t max_out = session_len + max_overhead;
539   if (max_out < max_overhead) {
540     OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
541     return 0;
542   }
543 
544   uint8_t *ptr;
545   if (!CBB_reserve(out, &ptr, max_out)) {
546     return 0;
547   }
548 
549   size_t out_len;
550   if (!method->seal(ssl, ptr, &out_len, max_out, session_buf,
551                     session_len)) {
552     OPENSSL_PUT_ERROR(SSL, SSL_R_TICKET_ENCRYPTION_FAILED);
553     return 0;
554   }
555 
556   if (!CBB_did_write(out, out_len)) {
557     return 0;
558   }
559 
560   return 1;
561 }
562 
ssl_encrypt_ticket(SSL_HANDSHAKE * hs,CBB * out,const SSL_SESSION * session)563 bool ssl_encrypt_ticket(SSL_HANDSHAKE *hs, CBB *out,
564                        const SSL_SESSION *session) {
565   // Serialize the SSL_SESSION to be encoded into the ticket.
566   uint8_t *session_buf = nullptr;
567   size_t session_len;
568   if (!SSL_SESSION_to_bytes_for_ticket(session, &session_buf, &session_len)) {
569     return false;
570   }
571   bssl::UniquePtr<uint8_t> free_session_buf(session_buf);
572 
573   if (hs->ssl->session_ctx->ticket_aead_method) {
574     return ssl_encrypt_ticket_with_method(hs, out, session_buf, session_len);
575   } else {
576     return ssl_encrypt_ticket_with_cipher_ctx(hs, out, session_buf,
577                                               session_len);
578   }
579 }
580 
ssl_session_is_context_valid(const SSL_HANDSHAKE * hs,const SSL_SESSION * session)581 bool ssl_session_is_context_valid(const SSL_HANDSHAKE *hs,
582                                   const SSL_SESSION *session) {
583   if (session == NULL) {
584     return false;
585   }
586 
587   return session->sid_ctx_length == hs->config->cert->sid_ctx_length &&
588          OPENSSL_memcmp(session->sid_ctx, hs->config->cert->sid_ctx,
589                         hs->config->cert->sid_ctx_length) == 0;
590 }
591 
ssl_session_is_time_valid(const SSL * ssl,const SSL_SESSION * session)592 bool ssl_session_is_time_valid(const SSL *ssl, const SSL_SESSION *session) {
593   if (session == NULL) {
594     return false;
595   }
596 
597   struct OPENSSL_timeval now;
598   ssl_get_current_time(ssl, &now);
599 
600   // Reject tickets from the future to avoid underflow.
601   if (now.tv_sec < session->time) {
602     return false;
603   }
604 
605   return session->timeout > now.tv_sec - session->time;
606 }
607 
ssl_session_is_resumable(const SSL_HANDSHAKE * hs,const SSL_SESSION * session)608 bool ssl_session_is_resumable(const SSL_HANDSHAKE *hs,
609                               const SSL_SESSION *session) {
610   const SSL *const ssl = hs->ssl;
611   return ssl_session_is_context_valid(hs, session) &&
612          // The session must have been created by the same type of end point as
613          // we're now using it with.
614          ssl->server == session->is_server &&
615          // The session must not be expired.
616          ssl_session_is_time_valid(ssl, session) &&
617          // Only resume if the session's version matches the negotiated
618          // version.
619          ssl->version == session->ssl_version &&
620          // Only resume if the session's cipher matches the negotiated one. This
621          // is stricter than necessary for TLS 1.3, which allows cross-cipher
622          // resumption if the PRF hashes match. We require an exact match for
623          // simplicity. If loosening this, the 0-RTT accept logic must be
624          // updated to check the cipher.
625          hs->new_cipher == session->cipher &&
626          // If the session contains a client certificate (either the full
627          // certificate or just the hash) then require that the form of the
628          // certificate matches the current configuration.
629          ((sk_CRYPTO_BUFFER_num(session->certs.get()) == 0 &&
630            !session->peer_sha256_valid) ||
631           session->peer_sha256_valid ==
632               hs->config->retain_only_sha256_of_client_certs) &&
633          // Only resume if the underlying transport protocol hasn't changed.
634          // This is to prevent cross-protocol resumption between QUIC and TCP.
635          (hs->ssl->quic_method != nullptr) == session->is_quic;
636 }
637 
638 // ssl_lookup_session looks up |session_id| in the session cache and sets
639 // |*out_session| to an |SSL_SESSION| object if found.
ssl_lookup_session(SSL_HANDSHAKE * hs,UniquePtr<SSL_SESSION> * out_session,Span<const uint8_t> session_id)640 static enum ssl_hs_wait_t ssl_lookup_session(
641     SSL_HANDSHAKE *hs, UniquePtr<SSL_SESSION> *out_session,
642     Span<const uint8_t> session_id) {
643   SSL *const ssl = hs->ssl;
644   out_session->reset();
645 
646   if (session_id.empty() || session_id.size() > SSL_MAX_SSL_SESSION_ID_LENGTH) {
647     return ssl_hs_ok;
648   }
649 
650   UniquePtr<SSL_SESSION> session;
651   // Try the internal cache, if it exists.
652   if (!(ssl->session_ctx->session_cache_mode &
653         SSL_SESS_CACHE_NO_INTERNAL_LOOKUP)) {
654     uint32_t hash = ssl_hash_session_id(session_id);
655     auto cmp = [](const void *key, const SSL_SESSION *sess) -> int {
656       Span<const uint8_t> key_id =
657           *reinterpret_cast<const Span<const uint8_t> *>(key);
658       Span<const uint8_t> sess_id =
659           MakeConstSpan(sess->session_id, sess->session_id_length);
660       return key_id == sess_id ? 0 : 1;
661     };
662     MutexReadLock lock(&ssl->session_ctx->lock);
663     // |lh_SSL_SESSION_retrieve_key| returns a non-owning pointer.
664     session = UpRef(lh_SSL_SESSION_retrieve_key(ssl->session_ctx->sessions,
665                                                 &session_id, hash, cmp));
666     // TODO(davidben): This should probably move it to the front of the list.
667   }
668 
669   // Fall back to the external cache, if it exists.
670   if (!session && ssl->session_ctx->get_session_cb != nullptr) {
671     int copy = 1;
672     session.reset(ssl->session_ctx->get_session_cb(ssl, session_id.data(),
673                                                    session_id.size(), &copy));
674     if (!session) {
675       return ssl_hs_ok;
676     }
677 
678     if (session.get() == SSL_magic_pending_session_ptr()) {
679       session.release();  // This pointer is not actually owned.
680       return ssl_hs_pending_session;
681     }
682 
683     // Increment reference count now if the session callback asks us to do so
684     // (note that if the session structures returned by the callback are shared
685     // between threads, it must handle the reference count itself [i.e. copy ==
686     // 0], or things won't be thread-safe).
687     if (copy) {
688       SSL_SESSION_up_ref(session.get());
689     }
690 
691     // Add the externally cached session to the internal cache if necessary.
692     if (!(ssl->session_ctx->session_cache_mode &
693           SSL_SESS_CACHE_NO_INTERNAL_STORE)) {
694       SSL_CTX_add_session(ssl->session_ctx.get(), session.get());
695     }
696   }
697 
698   if (session && !ssl_session_is_time_valid(ssl, session.get())) {
699     // The session was from the cache, so remove it.
700     SSL_CTX_remove_session(ssl->session_ctx.get(), session.get());
701     session.reset();
702   }
703 
704   *out_session = std::move(session);
705   return ssl_hs_ok;
706 }
707 
ssl_get_prev_session(SSL_HANDSHAKE * hs,UniquePtr<SSL_SESSION> * out_session,bool * out_tickets_supported,bool * out_renew_ticket,const SSL_CLIENT_HELLO * client_hello)708 enum ssl_hs_wait_t ssl_get_prev_session(SSL_HANDSHAKE *hs,
709                                         UniquePtr<SSL_SESSION> *out_session,
710                                         bool *out_tickets_supported,
711                                         bool *out_renew_ticket,
712                                         const SSL_CLIENT_HELLO *client_hello) {
713   // This is used only by servers.
714   assert(hs->ssl->server);
715   UniquePtr<SSL_SESSION> session;
716   bool renew_ticket = false;
717 
718   // If tickets are disabled, always behave as if no tickets are present.
719   CBS ticket;
720   const bool tickets_supported =
721       !(SSL_get_options(hs->ssl) & SSL_OP_NO_TICKET) &&
722       ssl_client_hello_get_extension(client_hello, &ticket,
723                                      TLSEXT_TYPE_session_ticket);
724   if (tickets_supported && CBS_len(&ticket) != 0) {
725     switch (ssl_process_ticket(hs, &session, &renew_ticket, ticket,
726                                MakeConstSpan(client_hello->session_id,
727                                              client_hello->session_id_len))) {
728       case ssl_ticket_aead_success:
729         break;
730       case ssl_ticket_aead_ignore_ticket:
731         assert(!session);
732         break;
733       case ssl_ticket_aead_error:
734         return ssl_hs_error;
735       case ssl_ticket_aead_retry:
736         return ssl_hs_pending_ticket;
737     }
738   } else {
739     // The client didn't send a ticket, so the session ID is a real ID.
740     enum ssl_hs_wait_t lookup_ret = ssl_lookup_session(
741         hs, &session,
742         MakeConstSpan(client_hello->session_id, client_hello->session_id_len));
743     if (lookup_ret != ssl_hs_ok) {
744       return lookup_ret;
745     }
746   }
747 
748   *out_session = std::move(session);
749   *out_tickets_supported = tickets_supported;
750   *out_renew_ticket = renew_ticket;
751   return ssl_hs_ok;
752 }
753 
remove_session(SSL_CTX * ctx,SSL_SESSION * session,bool lock)754 static bool remove_session(SSL_CTX *ctx, SSL_SESSION *session, bool lock) {
755   if (session == nullptr || session->session_id_length == 0) {
756     return false;
757   }
758 
759   if (lock) {
760     CRYPTO_MUTEX_lock_write(&ctx->lock);
761   }
762 
763   SSL_SESSION *found_session = lh_SSL_SESSION_retrieve(ctx->sessions, session);
764   bool found = found_session == session;
765   if (found) {
766     found_session = lh_SSL_SESSION_delete(ctx->sessions, session);
767     SSL_SESSION_list_remove(ctx, session);
768   }
769 
770   if (lock) {
771     CRYPTO_MUTEX_unlock_write(&ctx->lock);
772   }
773 
774   if (found) {
775     // TODO(https://crbug.com/boringssl/251): Callbacks should not be called
776     // under a lock.
777     if (ctx->remove_session_cb != nullptr) {
778       ctx->remove_session_cb(ctx, found_session);
779     }
780     SSL_SESSION_free(found_session);
781   }
782 
783   return found;
784 }
785 
ssl_set_session(SSL * ssl,SSL_SESSION * session)786 void ssl_set_session(SSL *ssl, SSL_SESSION *session) {
787   if (ssl->session.get() == session) {
788     return;
789   }
790 
791   ssl->session = UpRef(session);
792 }
793 
794 // locked by SSL_CTX in the calling function
SSL_SESSION_list_remove(SSL_CTX * ctx,SSL_SESSION * session)795 static void SSL_SESSION_list_remove(SSL_CTX *ctx, SSL_SESSION *session) {
796   if (session->next == NULL || session->prev == NULL) {
797     return;
798   }
799 
800   if (session->next == (SSL_SESSION *)&ctx->session_cache_tail) {
801     // last element in list
802     if (session->prev == (SSL_SESSION *)&ctx->session_cache_head) {
803       // only one element in list
804       ctx->session_cache_head = NULL;
805       ctx->session_cache_tail = NULL;
806     } else {
807       ctx->session_cache_tail = session->prev;
808       session->prev->next = (SSL_SESSION *)&(ctx->session_cache_tail);
809     }
810   } else {
811     if (session->prev == (SSL_SESSION *)&ctx->session_cache_head) {
812       // first element in list
813       ctx->session_cache_head = session->next;
814       session->next->prev = (SSL_SESSION *)&(ctx->session_cache_head);
815     } else {  // middle of list
816       session->next->prev = session->prev;
817       session->prev->next = session->next;
818     }
819   }
820   session->prev = session->next = NULL;
821 }
822 
SSL_SESSION_list_add(SSL_CTX * ctx,SSL_SESSION * session)823 static void SSL_SESSION_list_add(SSL_CTX *ctx, SSL_SESSION *session) {
824   if (session->next != NULL && session->prev != NULL) {
825     SSL_SESSION_list_remove(ctx, session);
826   }
827 
828   if (ctx->session_cache_head == NULL) {
829     ctx->session_cache_head = session;
830     ctx->session_cache_tail = session;
831     session->prev = (SSL_SESSION *)&(ctx->session_cache_head);
832     session->next = (SSL_SESSION *)&(ctx->session_cache_tail);
833   } else {
834     session->next = ctx->session_cache_head;
835     session->next->prev = session;
836     session->prev = (SSL_SESSION *)&(ctx->session_cache_head);
837     ctx->session_cache_head = session;
838   }
839 }
840 
add_session_locked(SSL_CTX * ctx,UniquePtr<SSL_SESSION> session)841 static bool add_session_locked(SSL_CTX *ctx, UniquePtr<SSL_SESSION> session) {
842   SSL_SESSION *new_session = session.get();
843   SSL_SESSION *old_session;
844   if (!lh_SSL_SESSION_insert(ctx->sessions, &old_session, new_session)) {
845     return false;
846   }
847   // |ctx->sessions| took ownership of |new_session| and gave us back a
848   // reference to |old_session|. (|old_session| may be the same as
849   // |new_session|, in which case we traded identical references with
850   // |ctx->sessions|.)
851   session.release();
852   session.reset(old_session);
853 
854   if (old_session != nullptr) {
855     if (old_session == new_session) {
856       // |session| was already in the cache. There are no linked list pointers
857       // to update.
858       return false;
859     }
860 
861     // There was a session ID collision. |old_session| was replaced with
862     // |session| in the hash table, so |old_session| must be removed from the
863     // linked list to match.
864     SSL_SESSION_list_remove(ctx, old_session);
865   }
866 
867   // This does not increment the reference count. Although |session| is inserted
868   // into two structures (a doubly-linked list and the hash table), |ctx| only
869   // takes one reference.
870   SSL_SESSION_list_add(ctx, new_session);
871 
872   // Enforce any cache size limits.
873   if (SSL_CTX_sess_get_cache_size(ctx) > 0) {
874     while (lh_SSL_SESSION_num_items(ctx->sessions) >
875            SSL_CTX_sess_get_cache_size(ctx)) {
876       if (!remove_session(ctx, ctx->session_cache_tail,
877                           /*lock=*/false)) {
878         break;
879       }
880     }
881   }
882 
883   return true;
884 }
885 
ssl_update_cache(SSL * ssl)886 void ssl_update_cache(SSL *ssl) {
887   SSL_CTX *ctx = ssl->session_ctx.get();
888   SSL_SESSION *session = ssl->s3->established_session.get();
889   int mode = SSL_is_server(ssl) ? SSL_SESS_CACHE_SERVER : SSL_SESS_CACHE_CLIENT;
890   if (!SSL_SESSION_is_resumable(session) ||
891       (ctx->session_cache_mode & mode) != mode) {
892     return;
893   }
894 
895   // Clients never use the internal session cache.
896   if (ssl->server &&
897       !(ctx->session_cache_mode & SSL_SESS_CACHE_NO_INTERNAL_STORE)) {
898     UniquePtr<SSL_SESSION> ref = UpRef(session);
899     bool remove_expired_sessions = false;
900     {
901       MutexWriteLock lock(&ctx->lock);
902       add_session_locked(ctx, std::move(ref));
903 
904       if (!(ctx->session_cache_mode & SSL_SESS_CACHE_NO_AUTO_CLEAR)) {
905         // Automatically flush the internal session cache every 255 connections.
906         ctx->handshakes_since_cache_flush++;
907         if (ctx->handshakes_since_cache_flush >= 255) {
908           remove_expired_sessions = true;
909           ctx->handshakes_since_cache_flush = 0;
910         }
911       }
912     }
913 
914     if (remove_expired_sessions) {
915       // |SSL_CTX_flush_sessions| takes the lock we just released. We could
916       // merge the critical sections, but we'd then call user code under a
917       // lock, or compute |now| earlier, even when not flushing.
918       OPENSSL_timeval now;
919       ssl_get_current_time(ssl, &now);
920       SSL_CTX_flush_sessions(ctx, now.tv_sec);
921     }
922   }
923 
924   if (ctx->new_session_cb != nullptr) {
925     UniquePtr<SSL_SESSION> ref = UpRef(session);
926     if (ctx->new_session_cb(ssl, ref.get())) {
927       // |new_session_cb|'s return value signals whether it took ownership.
928       ref.release();
929     }
930   }
931 }
932 
933 BSSL_NAMESPACE_END
934 
935 using namespace bssl;
936 
ssl_session_st(const SSL_X509_METHOD * method)937 ssl_session_st::ssl_session_st(const SSL_X509_METHOD *method)
938     : RefCounted(CheckSubClass()),
939       x509_method(method),
940       extended_master_secret(false),
941       peer_sha256_valid(false),
942       not_resumable(false),
943       ticket_age_add_valid(false),
944       is_server(false),
945       is_quic(false),
946       has_application_settings(false) {
947   CRYPTO_new_ex_data(&ex_data);
948   time = ::time(nullptr);
949 }
950 
~ssl_session_st()951 ssl_session_st::~ssl_session_st() {
952   CRYPTO_free_ex_data(&g_ex_data_class, this, &ex_data);
953   x509_method->session_clear(this);
954 }
955 
SSL_SESSION_new(const SSL_CTX * ctx)956 SSL_SESSION *SSL_SESSION_new(const SSL_CTX *ctx) {
957   return ssl_session_new(ctx->x509_method).release();
958 }
959 
SSL_SESSION_up_ref(SSL_SESSION * session)960 int SSL_SESSION_up_ref(SSL_SESSION *session) {
961   session->UpRefInternal();
962   return 1;
963 }
964 
SSL_SESSION_free(SSL_SESSION * session)965 void SSL_SESSION_free(SSL_SESSION *session) {
966   if (session != nullptr) {
967     session->DecRefInternal();
968   }
969 }
970 
SSL_SESSION_get_id(const SSL_SESSION * session,unsigned * out_len)971 const uint8_t *SSL_SESSION_get_id(const SSL_SESSION *session,
972                                   unsigned *out_len) {
973   if (out_len != NULL) {
974     *out_len = session->session_id_length;
975   }
976   return session->session_id;
977 }
978 
SSL_SESSION_set1_id(SSL_SESSION * session,const uint8_t * sid,size_t sid_len)979 int SSL_SESSION_set1_id(SSL_SESSION *session, const uint8_t *sid,
980                         size_t sid_len) {
981   if (sid_len > SSL_MAX_SSL_SESSION_ID_LENGTH) {
982     OPENSSL_PUT_ERROR(SSL, SSL_R_SSL_SESSION_ID_TOO_LONG);
983     return 0;
984   }
985 
986   // Use memmove in case someone passes in the output of |SSL_SESSION_get_id|.
987   OPENSSL_memmove(session->session_id, sid, sid_len);
988   session->session_id_length = sid_len;
989   return 1;
990 }
991 
SSL_SESSION_get_timeout(const SSL_SESSION * session)992 uint32_t SSL_SESSION_get_timeout(const SSL_SESSION *session) {
993   return session->timeout;
994 }
995 
SSL_SESSION_get_time(const SSL_SESSION * session)996 uint64_t SSL_SESSION_get_time(const SSL_SESSION *session) {
997   if (session == NULL) {
998     // NULL should crash, but silently accept it here for compatibility.
999     return 0;
1000   }
1001   return session->time;
1002 }
1003 
SSL_SESSION_get0_peer(const SSL_SESSION * session)1004 X509 *SSL_SESSION_get0_peer(const SSL_SESSION *session) {
1005   return session->x509_peer;
1006 }
1007 
STACK_OF(CRYPTO_BUFFER)1008 const STACK_OF(CRYPTO_BUFFER) *
1009     SSL_SESSION_get0_peer_certificates(const SSL_SESSION *session) {
1010   return session->certs.get();
1011 }
1012 
SSL_SESSION_get0_signed_cert_timestamp_list(const SSL_SESSION * session,const uint8_t ** out,size_t * out_len)1013 void SSL_SESSION_get0_signed_cert_timestamp_list(const SSL_SESSION *session,
1014                                                  const uint8_t **out,
1015                                                  size_t *out_len) {
1016   if (session->signed_cert_timestamp_list) {
1017     *out = CRYPTO_BUFFER_data(session->signed_cert_timestamp_list.get());
1018     *out_len = CRYPTO_BUFFER_len(session->signed_cert_timestamp_list.get());
1019   } else {
1020     *out = nullptr;
1021     *out_len = 0;
1022   }
1023 }
1024 
SSL_SESSION_get0_ocsp_response(const SSL_SESSION * session,const uint8_t ** out,size_t * out_len)1025 void SSL_SESSION_get0_ocsp_response(const SSL_SESSION *session,
1026                                     const uint8_t **out, size_t *out_len) {
1027   if (session->ocsp_response) {
1028     *out = CRYPTO_BUFFER_data(session->ocsp_response.get());
1029     *out_len = CRYPTO_BUFFER_len(session->ocsp_response.get());
1030   } else {
1031     *out = nullptr;
1032     *out_len = 0;
1033   }
1034 }
1035 
SSL_SESSION_get_master_key(const SSL_SESSION * session,uint8_t * out,size_t max_out)1036 size_t SSL_SESSION_get_master_key(const SSL_SESSION *session, uint8_t *out,
1037                                   size_t max_out) {
1038   // TODO(davidben): Fix secret_length's type and remove these casts.
1039   if (max_out == 0) {
1040     return (size_t)session->secret_length;
1041   }
1042   if (max_out > (size_t)session->secret_length) {
1043     max_out = (size_t)session->secret_length;
1044   }
1045   OPENSSL_memcpy(out, session->secret, max_out);
1046   return max_out;
1047 }
1048 
SSL_SESSION_set_time(SSL_SESSION * session,uint64_t time)1049 uint64_t SSL_SESSION_set_time(SSL_SESSION *session, uint64_t time) {
1050   if (session == NULL) {
1051     return 0;
1052   }
1053 
1054   session->time = time;
1055   return time;
1056 }
1057 
SSL_SESSION_set_timeout(SSL_SESSION * session,uint32_t timeout)1058 uint32_t SSL_SESSION_set_timeout(SSL_SESSION *session, uint32_t timeout) {
1059   if (session == NULL) {
1060     return 0;
1061   }
1062 
1063   session->timeout = timeout;
1064   session->auth_timeout = timeout;
1065   return 1;
1066 }
1067 
SSL_SESSION_get0_id_context(const SSL_SESSION * session,unsigned * out_len)1068 const uint8_t *SSL_SESSION_get0_id_context(const SSL_SESSION *session,
1069                                            unsigned *out_len) {
1070   if (out_len != NULL) {
1071     *out_len = session->sid_ctx_length;
1072   }
1073   return session->sid_ctx;
1074 }
1075 
SSL_SESSION_set1_id_context(SSL_SESSION * session,const uint8_t * sid_ctx,size_t sid_ctx_len)1076 int SSL_SESSION_set1_id_context(SSL_SESSION *session, const uint8_t *sid_ctx,
1077                                 size_t sid_ctx_len) {
1078   if (sid_ctx_len > sizeof(session->sid_ctx)) {
1079     OPENSSL_PUT_ERROR(SSL, SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
1080     return 0;
1081   }
1082 
1083   static_assert(sizeof(session->sid_ctx) < 256, "sid_ctx_len does not fit");
1084   session->sid_ctx_length = (uint8_t)sid_ctx_len;
1085   OPENSSL_memcpy(session->sid_ctx, sid_ctx, sid_ctx_len);
1086 
1087   return 1;
1088 }
1089 
SSL_SESSION_should_be_single_use(const SSL_SESSION * session)1090 int SSL_SESSION_should_be_single_use(const SSL_SESSION *session) {
1091   return ssl_session_protocol_version(session) >= TLS1_3_VERSION;
1092 }
1093 
SSL_SESSION_is_resumable(const SSL_SESSION * session)1094 int SSL_SESSION_is_resumable(const SSL_SESSION *session) {
1095   return !session->not_resumable &&
1096          (session->session_id_length != 0 || !session->ticket.empty());
1097 }
1098 
SSL_SESSION_has_ticket(const SSL_SESSION * session)1099 int SSL_SESSION_has_ticket(const SSL_SESSION *session) {
1100   return !session->ticket.empty();
1101 }
1102 
SSL_SESSION_get0_ticket(const SSL_SESSION * session,const uint8_t ** out_ticket,size_t * out_len)1103 void SSL_SESSION_get0_ticket(const SSL_SESSION *session,
1104                              const uint8_t **out_ticket, size_t *out_len) {
1105   if (out_ticket != nullptr) {
1106     *out_ticket = session->ticket.data();
1107   }
1108   *out_len = session->ticket.size();
1109 }
1110 
SSL_SESSION_set_ticket(SSL_SESSION * session,const uint8_t * ticket,size_t ticket_len)1111 int SSL_SESSION_set_ticket(SSL_SESSION *session, const uint8_t *ticket,
1112                            size_t ticket_len) {
1113   return session->ticket.CopyFrom(MakeConstSpan(ticket, ticket_len));
1114 }
1115 
SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION * session)1116 uint32_t SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *session) {
1117   return session->ticket_lifetime_hint;
1118 }
1119 
SSL_SESSION_get0_cipher(const SSL_SESSION * session)1120 const SSL_CIPHER *SSL_SESSION_get0_cipher(const SSL_SESSION *session) {
1121   return session->cipher;
1122 }
1123 
SSL_SESSION_has_peer_sha256(const SSL_SESSION * session)1124 int SSL_SESSION_has_peer_sha256(const SSL_SESSION *session) {
1125   return session->peer_sha256_valid;
1126 }
1127 
SSL_SESSION_get0_peer_sha256(const SSL_SESSION * session,const uint8_t ** out_ptr,size_t * out_len)1128 void SSL_SESSION_get0_peer_sha256(const SSL_SESSION *session,
1129                                   const uint8_t **out_ptr, size_t *out_len) {
1130   if (session->peer_sha256_valid) {
1131     *out_ptr = session->peer_sha256;
1132     *out_len = sizeof(session->peer_sha256);
1133   } else {
1134     *out_ptr = nullptr;
1135     *out_len = 0;
1136   }
1137 }
1138 
SSL_SESSION_early_data_capable(const SSL_SESSION * session)1139 int SSL_SESSION_early_data_capable(const SSL_SESSION *session) {
1140   return ssl_session_protocol_version(session) >= TLS1_3_VERSION &&
1141          session->ticket_max_early_data != 0;
1142 }
1143 
SSL_SESSION_copy_without_early_data(SSL_SESSION * session)1144 SSL_SESSION *SSL_SESSION_copy_without_early_data(SSL_SESSION *session) {
1145   if (!SSL_SESSION_early_data_capable(session)) {
1146     return UpRef(session).release();
1147   }
1148 
1149   bssl::UniquePtr<SSL_SESSION> copy =
1150       SSL_SESSION_dup(session, SSL_SESSION_DUP_ALL);
1151   if (!copy) {
1152     return nullptr;
1153   }
1154 
1155   copy->ticket_max_early_data = 0;
1156   // Copied sessions are non-resumable until they're completely filled in.
1157   copy->not_resumable = session->not_resumable;
1158   assert(!SSL_SESSION_early_data_capable(copy.get()));
1159   return copy.release();
1160 }
1161 
SSL_magic_pending_session_ptr(void)1162 SSL_SESSION *SSL_magic_pending_session_ptr(void) {
1163   return (SSL_SESSION *)&g_pending_session_magic;
1164 }
1165 
SSL_get_session(const SSL * ssl)1166 SSL_SESSION *SSL_get_session(const SSL *ssl) {
1167   // Once the initially handshake completes, we return the most recently
1168   // established session. In particular, if there is a pending renegotiation, we
1169   // do not return information about it until it completes.
1170   //
1171   // Code in the handshake must either use |hs->new_session| (if updating a
1172   // partial session) or |ssl_handshake_session| (if trying to query properties
1173   // consistently across TLS 1.2 resumption and other handshakes).
1174   if (ssl->s3->established_session != nullptr) {
1175     return ssl->s3->established_session.get();
1176   }
1177 
1178   // Otherwise, we must be in the initial handshake.
1179   SSL_HANDSHAKE *hs = ssl->s3->hs.get();
1180   assert(hs != nullptr);
1181   assert(!ssl->s3->initial_handshake_complete);
1182 
1183   // Return the 0-RTT session, if in the 0-RTT state. While the handshake has
1184   // not actually completed, the public accessors all report properties as if
1185   // it has.
1186   if (hs->early_session) {
1187     return hs->early_session.get();
1188   }
1189 
1190   // Otherwise, return the partial session.
1191   return (SSL_SESSION *)ssl_handshake_session(hs);
1192 }
1193 
SSL_get1_session(SSL * ssl)1194 SSL_SESSION *SSL_get1_session(SSL *ssl) {
1195   SSL_SESSION *ret = SSL_get_session(ssl);
1196   if (ret != NULL) {
1197     SSL_SESSION_up_ref(ret);
1198   }
1199   return ret;
1200 }
1201 
SSL_SESSION_get_ex_new_index(long argl,void * argp,CRYPTO_EX_unused * unused,CRYPTO_EX_dup * dup_unused,CRYPTO_EX_free * free_func)1202 int SSL_SESSION_get_ex_new_index(long argl, void *argp,
1203                                  CRYPTO_EX_unused *unused,
1204                                  CRYPTO_EX_dup *dup_unused,
1205                                  CRYPTO_EX_free *free_func) {
1206   return CRYPTO_get_ex_new_index_ex(&g_ex_data_class, argl, argp, free_func);
1207 }
1208 
SSL_SESSION_set_ex_data(SSL_SESSION * session,int idx,void * arg)1209 int SSL_SESSION_set_ex_data(SSL_SESSION *session, int idx, void *arg) {
1210   return CRYPTO_set_ex_data(&session->ex_data, idx, arg);
1211 }
1212 
SSL_SESSION_get_ex_data(const SSL_SESSION * session,int idx)1213 void *SSL_SESSION_get_ex_data(const SSL_SESSION *session, int idx) {
1214   return CRYPTO_get_ex_data(&session->ex_data, idx);
1215 }
1216 
SSL_CTX_add_session(SSL_CTX * ctx,SSL_SESSION * session)1217 int SSL_CTX_add_session(SSL_CTX *ctx, SSL_SESSION *session) {
1218   UniquePtr<SSL_SESSION> owned_session = UpRef(session);
1219   MutexWriteLock lock(&ctx->lock);
1220   return add_session_locked(ctx, std::move(owned_session));
1221 }
1222 
SSL_CTX_remove_session(SSL_CTX * ctx,SSL_SESSION * session)1223 int SSL_CTX_remove_session(SSL_CTX *ctx, SSL_SESSION *session) {
1224   return remove_session(ctx, session, /*lock=*/true);
1225 }
1226 
SSL_set_session(SSL * ssl,SSL_SESSION * session)1227 int SSL_set_session(SSL *ssl, SSL_SESSION *session) {
1228   // SSL_set_session may only be called before the handshake has started.
1229   if (ssl->s3->initial_handshake_complete ||
1230       ssl->s3->hs == NULL ||
1231       ssl->s3->hs->state != 0) {
1232     abort();
1233   }
1234 
1235   ssl_set_session(ssl, session);
1236   return 1;
1237 }
1238 
SSL_CTX_set_timeout(SSL_CTX * ctx,uint32_t timeout)1239 uint32_t SSL_CTX_set_timeout(SSL_CTX *ctx, uint32_t timeout) {
1240   if (ctx == NULL) {
1241     return 0;
1242   }
1243 
1244   // Historically, zero was treated as |SSL_DEFAULT_SESSION_TIMEOUT|.
1245   if (timeout == 0) {
1246     timeout = SSL_DEFAULT_SESSION_TIMEOUT;
1247   }
1248 
1249   uint32_t old_timeout = ctx->session_timeout;
1250   ctx->session_timeout = timeout;
1251   return old_timeout;
1252 }
1253 
SSL_CTX_get_timeout(const SSL_CTX * ctx)1254 uint32_t SSL_CTX_get_timeout(const SSL_CTX *ctx) {
1255   if (ctx == NULL) {
1256     return 0;
1257   }
1258 
1259   return ctx->session_timeout;
1260 }
1261 
SSL_CTX_set_session_psk_dhe_timeout(SSL_CTX * ctx,uint32_t timeout)1262 void SSL_CTX_set_session_psk_dhe_timeout(SSL_CTX *ctx, uint32_t timeout) {
1263   ctx->session_psk_dhe_timeout = timeout;
1264 }
1265 
1266 typedef struct timeout_param_st {
1267   SSL_CTX *ctx;
1268   uint64_t time;
1269   LHASH_OF(SSL_SESSION) *cache;
1270 } TIMEOUT_PARAM;
1271 
timeout_doall_arg(SSL_SESSION * session,void * void_param)1272 static void timeout_doall_arg(SSL_SESSION *session, void *void_param) {
1273   TIMEOUT_PARAM *param = reinterpret_cast<TIMEOUT_PARAM *>(void_param);
1274 
1275   if (param->time == 0 ||
1276       session->time + session->timeout < session->time ||
1277       param->time > (session->time + session->timeout)) {
1278     // TODO(davidben): This can probably just call |remove_session|.
1279     (void) lh_SSL_SESSION_delete(param->cache, session);
1280     SSL_SESSION_list_remove(param->ctx, session);
1281     // TODO(https://crbug.com/boringssl/251): Callbacks should not be called
1282     // under a lock.
1283     if (param->ctx->remove_session_cb != NULL) {
1284       param->ctx->remove_session_cb(param->ctx, session);
1285     }
1286     SSL_SESSION_free(session);
1287   }
1288 }
1289 
SSL_CTX_flush_sessions(SSL_CTX * ctx,uint64_t time)1290 void SSL_CTX_flush_sessions(SSL_CTX *ctx, uint64_t time) {
1291   TIMEOUT_PARAM tp;
1292 
1293   tp.ctx = ctx;
1294   tp.cache = ctx->sessions;
1295   if (tp.cache == NULL) {
1296     return;
1297   }
1298   tp.time = time;
1299   MutexWriteLock lock(&ctx->lock);
1300   lh_SSL_SESSION_doall_arg(tp.cache, timeout_doall_arg, &tp);
1301 }
1302 
SSL_CTX_sess_set_new_cb(SSL_CTX * ctx,int (* cb)(SSL * ssl,SSL_SESSION * session))1303 void SSL_CTX_sess_set_new_cb(SSL_CTX *ctx,
1304                              int (*cb)(SSL *ssl, SSL_SESSION *session)) {
1305   ctx->new_session_cb = cb;
1306 }
1307 
SSL_CTX_sess_get_new_cb(SSL_CTX * ctx)1308 int (*SSL_CTX_sess_get_new_cb(SSL_CTX *ctx))(SSL *ssl, SSL_SESSION *session) {
1309   return ctx->new_session_cb;
1310 }
1311 
SSL_CTX_sess_set_remove_cb(SSL_CTX * ctx,void (* cb)(SSL_CTX * ctx,SSL_SESSION * session))1312 void SSL_CTX_sess_set_remove_cb(
1313     SSL_CTX *ctx, void (*cb)(SSL_CTX *ctx, SSL_SESSION *session)) {
1314   ctx->remove_session_cb = cb;
1315 }
1316 
SSL_CTX_sess_get_remove_cb(SSL_CTX * ctx)1317 void (*SSL_CTX_sess_get_remove_cb(SSL_CTX *ctx))(SSL_CTX *ctx,
1318                                                  SSL_SESSION *session) {
1319   return ctx->remove_session_cb;
1320 }
1321 
SSL_CTX_sess_set_get_cb(SSL_CTX * ctx,SSL_SESSION * (* cb)(SSL * ssl,const uint8_t * id,int id_len,int * out_copy))1322 void SSL_CTX_sess_set_get_cb(SSL_CTX *ctx,
1323                              SSL_SESSION *(*cb)(SSL *ssl, const uint8_t *id,
1324                                                 int id_len, int *out_copy)) {
1325   ctx->get_session_cb = cb;
1326 }
1327 
SSL_CTX_sess_get_get_cb(SSL_CTX * ctx)1328 SSL_SESSION *(*SSL_CTX_sess_get_get_cb(SSL_CTX *ctx))(SSL *ssl,
1329                                                       const uint8_t *id,
1330                                                       int id_len,
1331                                                       int *out_copy) {
1332   return ctx->get_session_cb;
1333 }
1334 
SSL_CTX_set_info_callback(SSL_CTX * ctx,void (* cb)(const SSL * ssl,int type,int value))1335 void SSL_CTX_set_info_callback(
1336     SSL_CTX *ctx, void (*cb)(const SSL *ssl, int type, int value)) {
1337   ctx->info_callback = cb;
1338 }
1339 
SSL_CTX_get_info_callback(SSL_CTX * ctx)1340 void (*SSL_CTX_get_info_callback(SSL_CTX *ctx))(const SSL *ssl, int type,
1341                                                 int value) {
1342   return ctx->info_callback;
1343 }
1344