ssl_sess.c revision 1.120
1/* $OpenBSD: ssl_sess.c,v 1.120 2022/10/20 15:22:51 tb Exp $ */
2/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3 * All rights reserved.
4 *
5 * This package is an SSL implementation written
6 * by Eric Young (eay@cryptsoft.com).
7 * The implementation was written so as to conform with Netscapes SSL.
8 *
9 * This library is free for commercial and non-commercial use as long as
10 * the following conditions are aheared to.  The following conditions
11 * apply to all code found in this distribution, be it the RC4, RSA,
12 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13 * included with this distribution is covered by the same copyright terms
14 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15 *
16 * Copyright remains Eric Young's, and as such any Copyright notices in
17 * the code are not to be removed.
18 * If this package is used in a product, Eric Young should be given attribution
19 * as the author of the parts of the library used.
20 * This can be in the form of a textual message at program startup or
21 * in documentation (online or textual) provided with the package.
22 *
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
25 * are met:
26 * 1. Redistributions of source code must retain the copyright
27 *    notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 *    notice, this list of conditions and the following disclaimer in the
30 *    documentation and/or other materials provided with the distribution.
31 * 3. All advertising materials mentioning features or use of this software
32 *    must display the following acknowledgement:
33 *    "This product includes cryptographic software written by
34 *     Eric Young (eay@cryptsoft.com)"
35 *    The word 'cryptographic' can be left out if the rouines from the library
36 *    being used are not cryptographic related :-).
37 * 4. If you include any Windows specific code (or a derivative thereof) from
38 *    the apps directory (application code) you must include an acknowledgement:
39 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40 *
41 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51 * SUCH DAMAGE.
52 *
53 * The licence and distribution terms for any publically available version or
54 * derivative of this code cannot be changed.  i.e. this code cannot simply be
55 * copied and put under another distribution licence
56 * [including the GNU Public Licence.]
57 */
58/* ====================================================================
59 * Copyright (c) 1998-2006 The OpenSSL Project.  All rights reserved.
60 *
61 * Redistribution and use in source and binary forms, with or without
62 * modification, are permitted provided that the following conditions
63 * are met:
64 *
65 * 1. Redistributions of source code must retain the above copyright
66 *    notice, this list of conditions and the following disclaimer.
67 *
68 * 2. Redistributions in binary form must reproduce the above copyright
69 *    notice, this list of conditions and the following disclaimer in
70 *    the documentation and/or other materials provided with the
71 *    distribution.
72 *
73 * 3. All advertising materials mentioning features or use of this
74 *    software must display the following acknowledgment:
75 *    "This product includes software developed by the OpenSSL Project
76 *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77 *
78 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79 *    endorse or promote products derived from this software without
80 *    prior written permission. For written permission, please contact
81 *    openssl-core@openssl.org.
82 *
83 * 5. Products derived from this software may not be called "OpenSSL"
84 *    nor may "OpenSSL" appear in their names without prior written
85 *    permission of the OpenSSL Project.
86 *
87 * 6. Redistributions of any form whatsoever must retain the following
88 *    acknowledgment:
89 *    "This product includes software developed by the OpenSSL Project
90 *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91 *
92 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103 * OF THE POSSIBILITY OF SUCH DAMAGE.
104 * ====================================================================
105 *
106 * This product includes cryptographic software written by Eric Young
107 * (eay@cryptsoft.com).  This product includes software written by Tim
108 * Hudson (tjh@cryptsoft.com).
109 *
110 */
111/* ====================================================================
112 * Copyright 2005 Nokia. All rights reserved.
113 *
114 * The portions of the attached software ("Contribution") is developed by
115 * Nokia Corporation and is licensed pursuant to the OpenSSL open source
116 * license.
117 *
118 * The Contribution, originally written by Mika Kousa and Pasi Eronen of
119 * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
120 * support (see RFC 4279) to OpenSSL.
121 *
122 * No patent licenses or other rights except those expressly stated in
123 * the OpenSSL open source license shall be deemed granted or received
124 * expressly, by implication, estoppel, or otherwise.
125 *
126 * No assurances are provided by Nokia that the Contribution does not
127 * infringe the patent or other intellectual property rights of any third
128 * party or that the license provides you with all the necessary rights
129 * to make use of the Contribution.
130 *
131 * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
132 * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
133 * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
134 * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
135 * OTHERWISE.
136 */
137
138#include <openssl/lhash.h>
139#include <openssl/opensslconf.h>
140
141#ifndef OPENSSL_NO_ENGINE
142#include <openssl/engine.h>
143#endif
144
145#include "ssl_locl.h"
146
147static void SSL_SESSION_list_remove(SSL_CTX *ctx, SSL_SESSION *s);
148static void SSL_SESSION_list_add(SSL_CTX *ctx, SSL_SESSION *s);
149static int remove_session_lock(SSL_CTX *ctx, SSL_SESSION *c, int lck);
150
151/* aka SSL_get0_session; gets 0 objects, just returns a copy of the pointer */
152SSL_SESSION *
153SSL_get_session(const SSL *ssl)
154{
155	return (ssl->session);
156}
157
158/* variant of SSL_get_session: caller really gets something */
159SSL_SESSION *
160SSL_get1_session(SSL *ssl)
161{
162	SSL_SESSION *sess;
163
164	/*
165	 * Need to lock this all up rather than just use CRYPTO_add so that
166	 * somebody doesn't free ssl->session between when we check it's
167	 * non-null and when we up the reference count.
168	 */
169	CRYPTO_w_lock(CRYPTO_LOCK_SSL_SESSION);
170	sess = ssl->session;
171	if (sess)
172		sess->references++;
173	CRYPTO_w_unlock(CRYPTO_LOCK_SSL_SESSION);
174
175	return (sess);
176}
177
178int
179SSL_SESSION_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func,
180    CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func)
181{
182	return CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL_SESSION,
183	    argl, argp, new_func, dup_func, free_func);
184}
185
186int
187SSL_SESSION_set_ex_data(SSL_SESSION *s, int idx, void *arg)
188{
189	return (CRYPTO_set_ex_data(&s->ex_data, idx, arg));
190}
191
192void *
193SSL_SESSION_get_ex_data(const SSL_SESSION *s, int idx)
194{
195	return (CRYPTO_get_ex_data(&s->ex_data, idx));
196}
197
198uint32_t
199SSL_SESSION_get_max_early_data(const SSL_SESSION *s)
200{
201	return 0;
202}
203
204int
205SSL_SESSION_set_max_early_data(SSL_SESSION *s, uint32_t max_early_data)
206{
207	return 1;
208}
209
210SSL_SESSION *
211SSL_SESSION_new(void)
212{
213	SSL_SESSION *ss;
214
215	if (!OPENSSL_init_ssl(0, NULL)) {
216		SSLerrorx(SSL_R_LIBRARY_BUG);
217		return(NULL);
218	}
219
220	if ((ss = calloc(1, sizeof(*ss))) == NULL) {
221		SSLerrorx(ERR_R_MALLOC_FAILURE);
222		return (NULL);
223	}
224
225	ss->verify_result = 1; /* avoid 0 (= X509_V_OK) just in case */
226	ss->references = 1;
227	ss->timeout = 60 * 5 + 4; /* 5 minutes 4 seconds timeout by default */
228	ss->time = time(NULL);
229	ss->prev = NULL;
230	ss->next = NULL;
231	ss->tlsext_hostname = NULL;
232
233	ss->peer_cert_type = -1;
234
235	ss->tlsext_ecpointformatlist_length = 0;
236	ss->tlsext_ecpointformatlist = NULL;
237	ss->tlsext_supportedgroups_length = 0;
238	ss->tlsext_supportedgroups = NULL;
239
240	CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL_SESSION, ss, &ss->ex_data);
241
242	return (ss);
243}
244
245SSL_SESSION *
246ssl_session_dup(SSL_SESSION *sess, int include_ticket)
247{
248	SSL_SESSION *copy;
249	CBS cbs;
250
251	if ((copy = calloc(1, sizeof(*copy))) == NULL) {
252		SSLerrorx(ERR_R_MALLOC_FAILURE);
253		goto err;
254	}
255
256	copy->ssl_version = sess->ssl_version;
257
258	CBS_init(&cbs, sess->master_key, sess->master_key_length);
259	if (!CBS_write_bytes(&cbs, copy->master_key, sizeof(copy->master_key),
260	    &copy->master_key_length))
261		goto err;
262
263	CBS_init(&cbs, sess->session_id, sess->session_id_length);
264	if (!CBS_write_bytes(&cbs, copy->session_id, sizeof(copy->session_id),
265	    &copy->session_id_length))
266		goto err;
267
268	CBS_init(&cbs, sess->sid_ctx, sess->sid_ctx_length);
269	if (!CBS_write_bytes(&cbs, copy->sid_ctx, sizeof(copy->sid_ctx),
270	    &copy->sid_ctx_length))
271		goto err;
272
273	if (sess->peer_cert != NULL) {
274		if (!X509_up_ref(sess->peer_cert))
275			goto err;
276		copy->peer_cert = sess->peer_cert;
277	}
278	copy->peer_cert_type = sess->peer_cert_type;
279
280	copy->verify_result = sess->verify_result;
281
282	copy->timeout = sess->timeout;
283	copy->time = sess->time;
284	copy->references = 1;
285
286	copy->cipher = sess->cipher;
287	copy->cipher_id = sess->cipher_id;
288
289	if (sess->ciphers != NULL) {
290		if ((copy->ciphers = sk_SSL_CIPHER_dup(sess->ciphers)) == NULL)
291			goto err;
292	}
293
294	if (sess->tlsext_hostname != NULL) {
295		copy->tlsext_hostname = strdup(sess->tlsext_hostname);
296		if (copy->tlsext_hostname == NULL)
297			goto err;
298	}
299
300	if (include_ticket) {
301		CBS_init(&cbs, sess->tlsext_tick, sess->tlsext_ticklen);
302		if (!CBS_stow(&cbs, &copy->tlsext_tick, &copy->tlsext_ticklen))
303			goto err;
304		copy->tlsext_tick_lifetime_hint =
305		    sess->tlsext_tick_lifetime_hint;
306
307		/*
308		 * XXX - copy sess->resumption_master_secret and all other
309		 * TLSv1.3 info here.
310		 */
311	}
312
313	if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL_SESSION, copy,
314	    &copy->ex_data))
315		goto err;
316
317	if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_SSL_SESSION, &copy->ex_data,
318	    &sess->ex_data))
319		goto err;
320
321	/* Omit prev/next: the new session gets its own slot in the cache. */
322
323	copy->not_resumable = sess->not_resumable;
324
325	CBS_init(&cbs, sess->tlsext_ecpointformatlist,
326	    sess->tlsext_ecpointformatlist_length);
327	if (!CBS_stow(&cbs, &copy->tlsext_ecpointformatlist,
328	    &copy->tlsext_ecpointformatlist_length))
329		goto err;
330
331	if (sess->tlsext_supportedgroups != NULL) {
332		if ((copy->tlsext_supportedgroups = calloc(sizeof(uint16_t),
333		    sess->tlsext_supportedgroups_length)) == NULL)
334			goto err;
335		memcpy(copy->tlsext_supportedgroups,
336		    sess->tlsext_supportedgroups,
337		    sizeof(uint16_t) * sess->tlsext_supportedgroups_length);
338		copy->tlsext_supportedgroups_length =
339		    sess->tlsext_supportedgroups_length;
340	}
341
342	return copy;
343
344 err:
345	SSL_SESSION_free(copy);
346
347	return NULL;
348}
349
350const unsigned char *
351SSL_SESSION_get_id(const SSL_SESSION *ss, unsigned int *len)
352{
353	if (len != NULL)
354		*len = (unsigned int)ss->session_id_length;
355	return ss->session_id;
356}
357
358const unsigned char *
359SSL_SESSION_get0_id_context(const SSL_SESSION *ss, unsigned int *len)
360{
361	if (len != NULL)
362		*len = (unsigned int)ss->sid_ctx_length;
363	return ss->sid_ctx;
364}
365
366unsigned int
367SSL_SESSION_get_compress_id(const SSL_SESSION *ss)
368{
369	return 0;
370}
371
372unsigned long
373SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
374{
375	return s->tlsext_tick_lifetime_hint;
376}
377
378int
379SSL_SESSION_has_ticket(const SSL_SESSION *s)
380{
381	return (s->tlsext_ticklen > 0) ? 1 : 0;
382}
383
384/*
385 * SSLv3/TLSv1 has 32 bytes (256 bits) of session ID space. As such, filling
386 * the ID with random gunk repeatedly until we have no conflict is going to
387 * complete in one iteration pretty much "most" of the time (btw:
388 * understatement). So, if it takes us 10 iterations and we still can't avoid
389 * a conflict - well that's a reasonable point to call it quits. Either the
390 * arc4random code is broken or someone is trying to open roughly very close to
391 * 2^128 (or 2^256) SSL sessions to our server. How you might store that many
392 * sessions is perhaps a more interesting question...
393 */
394
395#define MAX_SESS_ID_ATTEMPTS 10
396
397static int
398def_generate_session_id(const SSL *ssl, unsigned char *id, unsigned int *id_len)
399{
400	unsigned int retry = 0;
401
402	do {
403		arc4random_buf(id, *id_len);
404	} while (SSL_has_matching_session_id(ssl, id, *id_len) &&
405	    (++retry < MAX_SESS_ID_ATTEMPTS));
406
407	if (retry < MAX_SESS_ID_ATTEMPTS)
408		return 1;
409
410	/* else - woops a session_id match */
411	/* XXX We should also check the external cache --
412	 * but the probability of a collision is negligible, and
413	 * we could not prevent the concurrent creation of sessions
414	 * with identical IDs since we currently don't have means
415	 * to atomically check whether a session ID already exists
416	 * and make a reservation for it if it does not
417	 * (this problem applies to the internal cache as well).
418	 */
419	return 0;
420}
421
422int
423ssl_get_new_session(SSL *s, int session)
424{
425	unsigned int tmp;
426	SSL_SESSION *ss = NULL;
427	GEN_SESSION_CB cb = def_generate_session_id;
428
429	/* This gets used by clients and servers. */
430
431	if ((ss = SSL_SESSION_new()) == NULL)
432		return (0);
433
434	/* If the context has a default timeout, use it */
435	if (s->session_ctx->session_timeout == 0)
436		ss->timeout = SSL_get_default_timeout(s);
437	else
438		ss->timeout = s->session_ctx->session_timeout;
439
440	if (s->session != NULL) {
441		SSL_SESSION_free(s->session);
442		s->session = NULL;
443	}
444
445	if (session) {
446		switch (s->version) {
447		case TLS1_VERSION:
448		case TLS1_1_VERSION:
449		case TLS1_2_VERSION:
450		case DTLS1_VERSION:
451		case DTLS1_2_VERSION:
452			ss->ssl_version = s->version;
453			ss->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
454			break;
455		default:
456			SSLerror(s, SSL_R_UNSUPPORTED_SSL_VERSION);
457			SSL_SESSION_free(ss);
458			return (0);
459		}
460
461		/* If RFC4507 ticket use empty session ID. */
462		if (s->tlsext_ticket_expected) {
463			ss->session_id_length = 0;
464			goto sess_id_done;
465		}
466
467		/* Choose which callback will set the session ID. */
468		CRYPTO_r_lock(CRYPTO_LOCK_SSL_CTX);
469		if (s->generate_session_id)
470			cb = s->generate_session_id;
471		else if (s->session_ctx->generate_session_id)
472			cb = s->session_ctx->generate_session_id;
473		CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX);
474
475		/* Choose a session ID. */
476		tmp = ss->session_id_length;
477		if (!cb(s, ss->session_id, &tmp)) {
478			/* The callback failed */
479			SSLerror(s, SSL_R_SSL_SESSION_ID_CALLBACK_FAILED);
480			SSL_SESSION_free(ss);
481			return (0);
482		}
483
484		/*
485		 * Don't allow the callback to set the session length to zero.
486		 * nor set it higher than it was.
487		 */
488		if (tmp == 0 || tmp > ss->session_id_length) {
489			/* The callback set an illegal length */
490			SSLerror(s, SSL_R_SSL_SESSION_ID_HAS_BAD_LENGTH);
491			SSL_SESSION_free(ss);
492			return (0);
493		}
494		ss->session_id_length = tmp;
495
496		/* Finally, check for a conflict. */
497		if (SSL_has_matching_session_id(s, ss->session_id,
498		    ss->session_id_length)) {
499			SSLerror(s, SSL_R_SSL_SESSION_ID_CONFLICT);
500			SSL_SESSION_free(ss);
501			return (0);
502		}
503
504 sess_id_done:
505		if (s->tlsext_hostname) {
506			ss->tlsext_hostname = strdup(s->tlsext_hostname);
507			if (ss->tlsext_hostname == NULL) {
508				SSLerror(s, ERR_R_INTERNAL_ERROR);
509				SSL_SESSION_free(ss);
510				return 0;
511			}
512		}
513	} else {
514		ss->session_id_length = 0;
515	}
516
517	if (s->sid_ctx_length > sizeof ss->sid_ctx) {
518		SSLerror(s, ERR_R_INTERNAL_ERROR);
519		SSL_SESSION_free(ss);
520		return 0;
521	}
522
523	memcpy(ss->sid_ctx, s->sid_ctx, s->sid_ctx_length);
524	ss->sid_ctx_length = s->sid_ctx_length;
525	s->session = ss;
526	ss->ssl_version = s->version;
527	ss->verify_result = X509_V_OK;
528
529	return (1);
530}
531
532static SSL_SESSION *
533ssl_session_from_cache(SSL *s, CBS *session_id)
534{
535	SSL_SESSION *sess;
536	SSL_SESSION data;
537
538	if ((s->session_ctx->session_cache_mode &
539	     SSL_SESS_CACHE_NO_INTERNAL_LOOKUP))
540		return NULL;
541
542	memset(&data, 0, sizeof(data));
543
544	data.ssl_version = s->version;
545
546	if (!CBS_write_bytes(session_id, data.session_id,
547	    sizeof(data.session_id), &data.session_id_length))
548		return NULL;
549
550	CRYPTO_r_lock(CRYPTO_LOCK_SSL_CTX);
551	sess = lh_SSL_SESSION_retrieve(s->session_ctx->sessions, &data);
552	if (sess != NULL)
553		CRYPTO_add(&sess->references, 1, CRYPTO_LOCK_SSL_SESSION);
554	CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX);
555
556	if (sess == NULL)
557		s->session_ctx->stats.sess_miss++;
558
559	return sess;
560}
561
562static SSL_SESSION *
563ssl_session_from_callback(SSL *s, CBS *session_id)
564{
565	SSL_SESSION *sess;
566	int copy;
567
568	if (s->session_ctx->get_session_cb == NULL)
569		return NULL;
570
571	copy = 1;
572	if ((sess = s->session_ctx->get_session_cb(s,
573	    CBS_data(session_id), CBS_len(session_id), &copy)) == NULL)
574		return NULL;
575	/*
576	 * The copy handler may have set copy == 0 to indicate that the session
577	 * structures are shared between threads and that it handles the
578	 * reference count itself. If it didn't set copy to zero, we must
579	 * increment the reference count.
580	 */
581	if (copy)
582		CRYPTO_add(&sess->references, 1, CRYPTO_LOCK_SSL_SESSION);
583
584	s->session_ctx->stats.sess_cb_hit++;
585
586	/* Add the externally cached session to the internal cache as well. */
587	if (!(s->session_ctx->session_cache_mode &
588	    SSL_SESS_CACHE_NO_INTERNAL_STORE)) {
589		/*
590		 * The following should not return 1,
591		 * otherwise, things are very strange.
592		 */
593		SSL_CTX_add_session(s->session_ctx, sess);
594	}
595
596	return sess;
597}
598
599static SSL_SESSION *
600ssl_session_by_id(SSL *s, CBS *session_id)
601{
602	SSL_SESSION *sess;
603
604	if (CBS_len(session_id) == 0)
605		return NULL;
606
607	if ((sess = ssl_session_from_cache(s, session_id)) == NULL)
608		sess = ssl_session_from_callback(s, session_id);
609
610	return sess;
611}
612
613/*
614 * ssl_get_prev_session attempts to find an SSL_SESSION to be used to resume
615 * this connection. It is only called by servers.
616 *
617 *   session_id: points at the session ID in the ClientHello. This code will
618 *       read past the end of this in order to parse out the session ticket
619 *       extension, if any.
620 *   ext_block: a CBS for the ClientHello extensions block.
621 *   alert: alert that the caller should send in case of failure.
622 *
623 * Returns:
624 *   -1: error
625 *    0: a session may have been found.
626 *
627 * Side effects:
628 *   - If a session is found then s->session is pointed at it (after freeing
629 *     an existing session if need be) and s->verify_result is set from the
630 *     session.
631 *   - For both new and resumed sessions, s->tlsext_ticket_expected
632 *     indicates whether the server should issue a new session ticket or not.
633 */
634int
635ssl_get_prev_session(SSL *s, CBS *session_id, CBS *ext_block, int *alert)
636{
637	SSL_SESSION *sess = NULL;
638	int alert_desc = SSL_AD_INTERNAL_ERROR, fatal = 0;
639	int ticket_decrypted = 0;
640
641	/* This is used only by servers. */
642
643	if (CBS_len(session_id) > SSL_MAX_SSL_SESSION_ID_LENGTH)
644		goto err;
645
646	/* Sets s->tlsext_ticket_expected. */
647	switch (tls1_process_ticket(s, ext_block, &alert_desc, &sess)) {
648	case TLS1_TICKET_FATAL_ERROR:
649		fatal = 1;
650		goto err;
651	case TLS1_TICKET_NONE:
652	case TLS1_TICKET_EMPTY:
653		if ((sess = ssl_session_by_id(s, session_id)) == NULL)
654			goto err;
655		break;
656	case TLS1_TICKET_NOT_DECRYPTED:
657		goto err;
658	case TLS1_TICKET_DECRYPTED:
659		ticket_decrypted = 1;
660
661		/*
662		 * The session ID is used by some clients to detect that the
663		 * ticket has been accepted so we copy it into sess.
664		 */
665		if (!CBS_write_bytes(session_id, sess->session_id,
666		    sizeof(sess->session_id), &sess->session_id_length)) {
667			fatal = 1;
668			goto err;
669		}
670		break;
671	default:
672		SSLerror(s, ERR_R_INTERNAL_ERROR);
673		fatal = 1;
674		goto err;
675	}
676
677	/* Now sess is non-NULL and we own one of its reference counts. */
678
679	if (sess->sid_ctx_length != s->sid_ctx_length ||
680	    timingsafe_memcmp(sess->sid_ctx, s->sid_ctx,
681	    sess->sid_ctx_length) != 0) {
682		/*
683		 * We have the session requested by the client, but we don't
684		 * want to use it in this context. Treat it like a cache miss.
685		 */
686		goto err;
687	}
688
689	if ((s->verify_mode & SSL_VERIFY_PEER) && s->sid_ctx_length == 0) {
690		/*
691		 * We can't be sure if this session is being used out of
692		 * context, which is especially important for SSL_VERIFY_PEER.
693		 * The application should have used
694		 * SSL[_CTX]_set_session_id_context.
695		 *
696		 * For this error case, we generate an error instead of treating
697		 * the event like a cache miss (otherwise it would be easy for
698		 * applications to effectively disable the session cache by
699		 * accident without anyone noticing).
700		 */
701		SSLerror(s, SSL_R_SESSION_ID_CONTEXT_UNINITIALIZED);
702		fatal = 1;
703		goto err;
704	}
705
706	if (sess->cipher == NULL) {
707		sess->cipher = ssl3_get_cipher_by_id(sess->cipher_id);
708		if (sess->cipher == NULL)
709			goto err;
710	}
711
712	if (sess->timeout < (time(NULL) - sess->time)) {
713		s->session_ctx->stats.sess_timeout++;
714		if (!ticket_decrypted) {
715			/* The session was from the cache, so remove it. */
716			SSL_CTX_remove_session(s->session_ctx, sess);
717		}
718		goto err;
719	}
720
721	s->session_ctx->stats.sess_hit++;
722
723	SSL_SESSION_free(s->session);
724	s->session = sess;
725	s->verify_result = s->session->verify_result;
726
727	return 1;
728
729 err:
730	SSL_SESSION_free(sess);
731	if (ticket_decrypted) {
732		/*
733		 * The session was from a ticket. Issue a ticket for the new
734		 * session.
735		 */
736		s->tlsext_ticket_expected = 1;
737	}
738	if (fatal) {
739		*alert = alert_desc;
740		return -1;
741	}
742	return 0;
743}
744
745int
746SSL_CTX_add_session(SSL_CTX *ctx, SSL_SESSION *c)
747{
748	int ret = 0;
749	SSL_SESSION *s;
750
751	/*
752	 * Add just 1 reference count for the SSL_CTX's session cache
753	 * even though it has two ways of access: each session is in a
754	 * doubly linked list and an lhash.
755	 */
756	CRYPTO_add(&c->references, 1, CRYPTO_LOCK_SSL_SESSION);
757
758	/*
759	 * If session c is in already in cache, we take back the increment
760	 * later.
761	 */
762	CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
763	s = lh_SSL_SESSION_insert(ctx->sessions, c);
764
765	/*
766	 * s != NULL iff we already had a session with the given PID.
767	 * In this case, s == c should hold (then we did not really modify
768	 * ctx->sessions), or we're in trouble.
769	 */
770	if (s != NULL && s != c) {
771		/* We *are* in trouble ... */
772		SSL_SESSION_list_remove(ctx, s);
773		SSL_SESSION_free(s);
774		/*
775		 * ... so pretend the other session did not exist in cache
776		 * (we cannot handle two SSL_SESSION structures with identical
777		 * session ID in the same cache, which could happen e.g. when
778		 * two threads concurrently obtain the same session from an
779		 * external cache).
780		 */
781		s = NULL;
782	}
783
784	/* Put at the head of the queue unless it is already in the cache */
785	if (s == NULL)
786		SSL_SESSION_list_add(ctx, c);
787
788	if (s != NULL) {
789		/*
790		 * existing cache entry -- decrement previously incremented
791		 * reference count because it already takes into account the
792		 * cache.
793		 */
794		SSL_SESSION_free(s); /* s == c */
795		ret = 0;
796	} else {
797		/*
798		 * New cache entry -- remove old ones if cache has become
799		 * too large.
800		 */
801
802		ret = 1;
803
804		if (SSL_CTX_sess_get_cache_size(ctx) > 0) {
805			while (SSL_CTX_sess_number(ctx) >
806			    SSL_CTX_sess_get_cache_size(ctx)) {
807				if (!remove_session_lock(ctx,
808				    ctx->session_cache_tail, 0))
809					break;
810				else
811					ctx->stats.sess_cache_full++;
812			}
813		}
814	}
815	CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
816	return (ret);
817}
818
819int
820SSL_CTX_remove_session(SSL_CTX *ctx, SSL_SESSION *c)
821{
822	return remove_session_lock(ctx, c, 1);
823}
824
825static int
826remove_session_lock(SSL_CTX *ctx, SSL_SESSION *c, int lck)
827{
828	SSL_SESSION *r;
829	int ret = 0;
830
831	if (c == NULL || c->session_id_length == 0)
832		return 0;
833
834	if (lck)
835		CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
836	if ((r = lh_SSL_SESSION_retrieve(ctx->sessions, c)) == c) {
837		ret = 1;
838		r = lh_SSL_SESSION_delete(ctx->sessions, c);
839		SSL_SESSION_list_remove(ctx, c);
840	}
841	if (lck)
842		CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
843
844	if (ret) {
845		r->not_resumable = 1;
846		if (ctx->remove_session_cb != NULL)
847			ctx->remove_session_cb(ctx, r);
848		SSL_SESSION_free(r);
849	}
850
851	return ret;
852}
853
854void
855SSL_SESSION_free(SSL_SESSION *ss)
856{
857	int i;
858
859	if (ss == NULL)
860		return;
861
862	i = CRYPTO_add(&ss->references, -1, CRYPTO_LOCK_SSL_SESSION);
863	if (i > 0)
864		return;
865
866	CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL_SESSION, ss, &ss->ex_data);
867
868	explicit_bzero(ss->master_key, sizeof ss->master_key);
869	explicit_bzero(ss->session_id, sizeof ss->session_id);
870
871	X509_free(ss->peer_cert);
872
873	sk_SSL_CIPHER_free(ss->ciphers);
874
875	free(ss->tlsext_hostname);
876	free(ss->tlsext_tick);
877	free(ss->tlsext_ecpointformatlist);
878	free(ss->tlsext_supportedgroups);
879
880	tls13_secret_cleanup(&ss->resumption_master_secret);
881
882	freezero(ss, sizeof(*ss));
883}
884
885int
886SSL_SESSION_up_ref(SSL_SESSION *ss)
887{
888	int refs = CRYPTO_add(&ss->references, 1, CRYPTO_LOCK_SSL_SESSION);
889	return (refs > 1) ? 1 : 0;
890}
891
892int
893SSL_set_session(SSL *s, SSL_SESSION *session)
894{
895	const SSL_METHOD *method;
896
897	if (session == NULL) {
898		SSL_SESSION_free(s->session);
899		s->session = NULL;
900
901		return SSL_set_ssl_method(s, s->ctx->method);
902	}
903
904	if ((method = ssl_get_method(session->ssl_version)) == NULL) {
905		SSLerror(s, SSL_R_UNABLE_TO_FIND_SSL_METHOD);
906		return (0);
907	}
908
909	if (!SSL_set_ssl_method(s, method))
910		return (0);
911
912	CRYPTO_add(&session->references, 1, CRYPTO_LOCK_SSL_SESSION);
913	SSL_SESSION_free(s->session);
914	s->session = session;
915	s->verify_result = s->session->verify_result;
916
917	return (1);
918}
919
920size_t
921SSL_SESSION_get_master_key(const SSL_SESSION *ss, unsigned char *out,
922    size_t max_out)
923{
924	size_t len = ss->master_key_length;
925
926	if (out == NULL)
927		return len;
928
929	if (len > max_out)
930		len = max_out;
931
932	memcpy(out, ss->master_key, len);
933
934	return len;
935}
936
937long
938SSL_SESSION_set_timeout(SSL_SESSION *s, long t)
939{
940	if (s == NULL)
941		return (0);
942	s->timeout = t;
943	return (1);
944}
945
946long
947SSL_SESSION_get_timeout(const SSL_SESSION *s)
948{
949	if (s == NULL)
950		return (0);
951	return (s->timeout);
952}
953
954/* XXX 2038 */
955long
956SSL_SESSION_get_time(const SSL_SESSION *s)
957{
958	if (s == NULL)
959		return (0);
960	return (s->time);
961}
962
963/* XXX 2038 */
964long
965SSL_SESSION_set_time(SSL_SESSION *s, long t)
966{
967	if (s == NULL)
968		return (0);
969	s->time = t;
970	return (t);
971}
972
973int
974SSL_SESSION_get_protocol_version(const SSL_SESSION *s)
975{
976	return s->ssl_version;
977}
978
979const SSL_CIPHER *
980SSL_SESSION_get0_cipher(const SSL_SESSION *s)
981{
982	return s->cipher;
983}
984
985X509 *
986SSL_SESSION_get0_peer(SSL_SESSION *s)
987{
988	return s->peer_cert;
989}
990
991int
992SSL_SESSION_set1_id(SSL_SESSION *s, const unsigned char *sid,
993    unsigned int sid_len)
994{
995	if (sid_len > SSL_MAX_SSL_SESSION_ID_LENGTH) {
996		SSLerrorx(SSL_R_SSL_SESSION_ID_TOO_LONG);
997		return 0;
998	}
999	s->session_id_length = sid_len;
1000	memmove(s->session_id, sid, sid_len);
1001	return 1;
1002}
1003
1004int
1005SSL_SESSION_set1_id_context(SSL_SESSION *s, const unsigned char *sid_ctx,
1006    unsigned int sid_ctx_len)
1007{
1008	if (sid_ctx_len > SSL_MAX_SID_CTX_LENGTH) {
1009		SSLerrorx(SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
1010		return 0;
1011	}
1012	s->sid_ctx_length = sid_ctx_len;
1013	memcpy(s->sid_ctx, sid_ctx, sid_ctx_len);
1014
1015	return 1;
1016}
1017
1018int
1019SSL_SESSION_is_resumable(const SSL_SESSION *s)
1020{
1021	return 0;
1022}
1023
1024long
1025SSL_CTX_set_timeout(SSL_CTX *s, long t)
1026{
1027	long l;
1028
1029	if (s == NULL)
1030		return (0);
1031	l = s->session_timeout;
1032	s->session_timeout = t;
1033
1034	return (l);
1035}
1036
1037long
1038SSL_CTX_get_timeout(const SSL_CTX *s)
1039{
1040	if (s == NULL)
1041		return (0);
1042	return (s->session_timeout);
1043}
1044
1045int
1046SSL_set_session_secret_cb(SSL *s, int (*tls_session_secret_cb)(SSL *s,
1047    void *secret, int *secret_len, STACK_OF(SSL_CIPHER) *peer_ciphers,
1048    SSL_CIPHER **cipher, void *arg), void *arg)
1049{
1050	if (s == NULL)
1051		return (0);
1052	s->tls_session_secret_cb = tls_session_secret_cb;
1053	s->tls_session_secret_cb_arg = arg;
1054	return (1);
1055}
1056
1057int
1058SSL_set_session_ticket_ext_cb(SSL *s, tls_session_ticket_ext_cb_fn cb,
1059    void *arg)
1060{
1061	if (s == NULL)
1062		return (0);
1063	s->tls_session_ticket_ext_cb = cb;
1064	s->tls_session_ticket_ext_cb_arg = arg;
1065	return (1);
1066}
1067
1068int
1069SSL_set_session_ticket_ext(SSL *s, void *ext_data, int ext_len)
1070{
1071	if (s->version >= TLS1_VERSION) {
1072		free(s->tlsext_session_ticket);
1073		s->tlsext_session_ticket =
1074		    malloc(sizeof(TLS_SESSION_TICKET_EXT) + ext_len);
1075		if (!s->tlsext_session_ticket) {
1076			SSLerror(s, ERR_R_MALLOC_FAILURE);
1077			return 0;
1078		}
1079
1080		if (ext_data) {
1081			s->tlsext_session_ticket->length = ext_len;
1082			s->tlsext_session_ticket->data =
1083			    s->tlsext_session_ticket + 1;
1084			memcpy(s->tlsext_session_ticket->data,
1085			    ext_data, ext_len);
1086		} else {
1087			s->tlsext_session_ticket->length = 0;
1088			s->tlsext_session_ticket->data = NULL;
1089		}
1090
1091		return 1;
1092	}
1093
1094	return 0;
1095}
1096
1097typedef struct timeout_param_st {
1098	SSL_CTX *ctx;
1099	long time;
1100	struct lhash_st_SSL_SESSION *cache;
1101} TIMEOUT_PARAM;
1102
1103static void
1104timeout_doall_arg(SSL_SESSION *s, TIMEOUT_PARAM *p)
1105{
1106	if ((p->time == 0) || (p->time > (s->time + s->timeout))) {
1107		/* timeout */
1108		/* The reason we don't call SSL_CTX_remove_session() is to
1109		 * save on locking overhead */
1110		(void)lh_SSL_SESSION_delete(p->cache, s);
1111		SSL_SESSION_list_remove(p->ctx, s);
1112		s->not_resumable = 1;
1113		if (p->ctx->remove_session_cb != NULL)
1114			p->ctx->remove_session_cb(p->ctx, s);
1115		SSL_SESSION_free(s);
1116	}
1117}
1118
1119static void
1120timeout_LHASH_DOALL_ARG(void *arg1, void *arg2)
1121{
1122	SSL_SESSION *a = arg1;
1123	TIMEOUT_PARAM *b = arg2;
1124
1125	timeout_doall_arg(a, b);
1126}
1127
1128/* XXX 2038 */
1129void
1130SSL_CTX_flush_sessions(SSL_CTX *s, long t)
1131{
1132	unsigned long i;
1133	TIMEOUT_PARAM tp;
1134
1135	tp.ctx = s;
1136	tp.cache = s->sessions;
1137	if (tp.cache == NULL)
1138		return;
1139	tp.time = t;
1140	CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
1141	i = CHECKED_LHASH_OF(SSL_SESSION, tp.cache)->down_load;
1142	CHECKED_LHASH_OF(SSL_SESSION, tp.cache)->down_load = 0;
1143	lh_SSL_SESSION_doall_arg(tp.cache, timeout_LHASH_DOALL_ARG,
1144	TIMEOUT_PARAM, &tp);
1145	CHECKED_LHASH_OF(SSL_SESSION, tp.cache)->down_load = i;
1146	CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
1147}
1148
1149int
1150ssl_clear_bad_session(SSL *s)
1151{
1152	if ((s->session != NULL) && !(s->shutdown & SSL_SENT_SHUTDOWN) &&
1153	    !(SSL_in_init(s) || SSL_in_before(s))) {
1154		SSL_CTX_remove_session(s->ctx, s->session);
1155		return (1);
1156	} else
1157		return (0);
1158}
1159
1160/* locked by SSL_CTX in the calling function */
1161static void
1162SSL_SESSION_list_remove(SSL_CTX *ctx, SSL_SESSION *s)
1163{
1164	if (s->next == NULL || s->prev == NULL)
1165		return;
1166
1167	if (s->next == (SSL_SESSION *)&(ctx->session_cache_tail)) {
1168		/* last element in list */
1169		if (s->prev == (SSL_SESSION *)&(ctx->session_cache_head)) {
1170			/* only one element in list */
1171			ctx->session_cache_head = NULL;
1172			ctx->session_cache_tail = NULL;
1173		} else {
1174			ctx->session_cache_tail = s->prev;
1175			s->prev->next =
1176			    (SSL_SESSION *)&(ctx->session_cache_tail);
1177		}
1178	} else {
1179		if (s->prev == (SSL_SESSION *)&(ctx->session_cache_head)) {
1180			/* first element in list */
1181			ctx->session_cache_head = s->next;
1182			s->next->prev =
1183			    (SSL_SESSION *)&(ctx->session_cache_head);
1184		} else {
1185			/* middle of list */
1186			s->next->prev = s->prev;
1187			s->prev->next = s->next;
1188		}
1189	}
1190	s->prev = s->next = NULL;
1191}
1192
1193static void
1194SSL_SESSION_list_add(SSL_CTX *ctx, SSL_SESSION *s)
1195{
1196	if (s->next != NULL && s->prev != NULL)
1197		SSL_SESSION_list_remove(ctx, s);
1198
1199	if (ctx->session_cache_head == NULL) {
1200		ctx->session_cache_head = s;
1201		ctx->session_cache_tail = s;
1202		s->prev = (SSL_SESSION *)&(ctx->session_cache_head);
1203		s->next = (SSL_SESSION *)&(ctx->session_cache_tail);
1204	} else {
1205		s->next = ctx->session_cache_head;
1206		s->next->prev = s;
1207		s->prev = (SSL_SESSION *)&(ctx->session_cache_head);
1208		ctx->session_cache_head = s;
1209	}
1210}
1211
1212void
1213SSL_CTX_sess_set_new_cb(SSL_CTX *ctx,
1214    int (*cb)(struct ssl_st *ssl, SSL_SESSION *sess)) {
1215	ctx->new_session_cb = cb;
1216}
1217
1218int
1219(*SSL_CTX_sess_get_new_cb(SSL_CTX *ctx))(SSL *ssl, SSL_SESSION *sess)
1220{
1221	return ctx->new_session_cb;
1222}
1223
1224void
1225SSL_CTX_sess_set_remove_cb(SSL_CTX *ctx,
1226    void (*cb)(SSL_CTX *ctx, SSL_SESSION *sess))
1227{
1228	ctx->remove_session_cb = cb;
1229}
1230
1231void
1232(*SSL_CTX_sess_get_remove_cb(SSL_CTX *ctx))(SSL_CTX * ctx, SSL_SESSION *sess)
1233{
1234	return ctx->remove_session_cb;
1235}
1236
1237void
1238SSL_CTX_sess_set_get_cb(SSL_CTX *ctx, SSL_SESSION *(*cb)(struct ssl_st *ssl,
1239    const unsigned char *data, int len, int *copy))
1240{
1241	ctx->get_session_cb = cb;
1242}
1243
1244SSL_SESSION *
1245(*SSL_CTX_sess_get_get_cb(SSL_CTX *ctx))(SSL *ssl, const unsigned char *data,
1246    int len, int *copy)
1247{
1248	return ctx->get_session_cb;
1249}
1250
1251void
1252SSL_CTX_set_info_callback(SSL_CTX *ctx,
1253    void (*cb)(const SSL *ssl, int type, int val))
1254{
1255	ctx->info_callback = cb;
1256}
1257
1258void
1259(*SSL_CTX_get_info_callback(SSL_CTX *ctx))(const SSL *ssl, int type, int val)
1260{
1261	return ctx->info_callback;
1262}
1263
1264void
1265SSL_CTX_set_client_cert_cb(SSL_CTX *ctx,
1266    int (*cb)(SSL *ssl, X509 **x509, EVP_PKEY **pkey))
1267{
1268	ctx->client_cert_cb = cb;
1269}
1270
1271int
1272(*SSL_CTX_get_client_cert_cb(SSL_CTX *ctx))(SSL * ssl, X509 ** x509,
1273    EVP_PKEY **pkey)
1274{
1275	return ctx->client_cert_cb;
1276}
1277
1278#ifndef OPENSSL_NO_ENGINE
1279int
1280SSL_CTX_set_client_cert_engine(SSL_CTX *ctx, ENGINE *e)
1281{
1282	if (!ENGINE_init(e)) {
1283		SSLerrorx(ERR_R_ENGINE_LIB);
1284		return 0;
1285	}
1286	if (!ENGINE_get_ssl_client_cert_function(e)) {
1287		SSLerrorx(SSL_R_NO_CLIENT_CERT_METHOD);
1288		ENGINE_finish(e);
1289		return 0;
1290	}
1291	ctx->client_cert_engine = e;
1292	return 1;
1293}
1294#endif
1295
1296void
1297SSL_CTX_set_cookie_generate_cb(SSL_CTX *ctx,
1298    int (*cb)(SSL *ssl, unsigned char *cookie, unsigned int *cookie_len))
1299{
1300	ctx->app_gen_cookie_cb = cb;
1301}
1302
1303void
1304SSL_CTX_set_cookie_verify_cb(SSL_CTX *ctx,
1305    int (*cb)(SSL *ssl, const unsigned char *cookie, unsigned int cookie_len))
1306{
1307	ctx->app_verify_cookie_cb = cb;
1308}
1309
1310int
1311PEM_write_SSL_SESSION(FILE *fp, SSL_SESSION *x)
1312{
1313	return PEM_ASN1_write((i2d_of_void *)i2d_SSL_SESSION,
1314	    PEM_STRING_SSL_SESSION, fp, x, NULL, NULL, 0, NULL, NULL);
1315}
1316
1317SSL_SESSION *
1318PEM_read_SSL_SESSION(FILE *fp, SSL_SESSION **x, pem_password_cb *cb, void *u)
1319{
1320	return PEM_ASN1_read((d2i_of_void *)d2i_SSL_SESSION,
1321	    PEM_STRING_SSL_SESSION, fp, (void **)x, cb, u);
1322}
1323
1324SSL_SESSION *
1325PEM_read_bio_SSL_SESSION(BIO *bp, SSL_SESSION **x, pem_password_cb *cb, void *u)
1326{
1327	return PEM_ASN1_read_bio((d2i_of_void *)d2i_SSL_SESSION,
1328	    PEM_STRING_SSL_SESSION, bp, (void **)x, cb, u);
1329}
1330
1331int
1332PEM_write_bio_SSL_SESSION(BIO *bp, SSL_SESSION *x)
1333{
1334	return PEM_ASN1_write_bio((i2d_of_void *)i2d_SSL_SESSION,
1335	    PEM_STRING_SSL_SESSION, bp, x, NULL, NULL, 0, NULL, NULL);
1336}
1337