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