ssl_sess.c revision 1.119
1/* $OpenBSD: ssl_sess.c,v 1.119 2022/10/20 15:21:22 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
245const unsigned char *
246SSL_SESSION_get_id(const SSL_SESSION *ss, unsigned int *len)
247{
248	if (len != NULL)
249		*len = (unsigned int)ss->session_id_length;
250	return ss->session_id;
251}
252
253const unsigned char *
254SSL_SESSION_get0_id_context(const SSL_SESSION *ss, unsigned int *len)
255{
256	if (len != NULL)
257		*len = (unsigned int)ss->sid_ctx_length;
258	return ss->sid_ctx;
259}
260
261unsigned int
262SSL_SESSION_get_compress_id(const SSL_SESSION *ss)
263{
264	return 0;
265}
266
267unsigned long
268SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
269{
270	return s->tlsext_tick_lifetime_hint;
271}
272
273int
274SSL_SESSION_has_ticket(const SSL_SESSION *s)
275{
276	return (s->tlsext_ticklen > 0) ? 1 : 0;
277}
278
279/*
280 * SSLv3/TLSv1 has 32 bytes (256 bits) of session ID space. As such, filling
281 * the ID with random gunk repeatedly until we have no conflict is going to
282 * complete in one iteration pretty much "most" of the time (btw:
283 * understatement). So, if it takes us 10 iterations and we still can't avoid
284 * a conflict - well that's a reasonable point to call it quits. Either the
285 * arc4random code is broken or someone is trying to open roughly very close to
286 * 2^128 (or 2^256) SSL sessions to our server. How you might store that many
287 * sessions is perhaps a more interesting question...
288 */
289
290#define MAX_SESS_ID_ATTEMPTS 10
291
292static int
293def_generate_session_id(const SSL *ssl, unsigned char *id, unsigned int *id_len)
294{
295	unsigned int retry = 0;
296
297	do {
298		arc4random_buf(id, *id_len);
299	} while (SSL_has_matching_session_id(ssl, id, *id_len) &&
300	    (++retry < MAX_SESS_ID_ATTEMPTS));
301
302	if (retry < MAX_SESS_ID_ATTEMPTS)
303		return 1;
304
305	/* else - woops a session_id match */
306	/* XXX We should also check the external cache --
307	 * but the probability of a collision is negligible, and
308	 * we could not prevent the concurrent creation of sessions
309	 * with identical IDs since we currently don't have means
310	 * to atomically check whether a session ID already exists
311	 * and make a reservation for it if it does not
312	 * (this problem applies to the internal cache as well).
313	 */
314	return 0;
315}
316
317int
318ssl_get_new_session(SSL *s, int session)
319{
320	unsigned int tmp;
321	SSL_SESSION *ss = NULL;
322	GEN_SESSION_CB cb = def_generate_session_id;
323
324	/* This gets used by clients and servers. */
325
326	if ((ss = SSL_SESSION_new()) == NULL)
327		return (0);
328
329	/* If the context has a default timeout, use it */
330	if (s->session_ctx->session_timeout == 0)
331		ss->timeout = SSL_get_default_timeout(s);
332	else
333		ss->timeout = s->session_ctx->session_timeout;
334
335	if (s->session != NULL) {
336		SSL_SESSION_free(s->session);
337		s->session = NULL;
338	}
339
340	if (session) {
341		switch (s->version) {
342		case TLS1_VERSION:
343		case TLS1_1_VERSION:
344		case TLS1_2_VERSION:
345		case DTLS1_VERSION:
346		case DTLS1_2_VERSION:
347			ss->ssl_version = s->version;
348			ss->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
349			break;
350		default:
351			SSLerror(s, SSL_R_UNSUPPORTED_SSL_VERSION);
352			SSL_SESSION_free(ss);
353			return (0);
354		}
355
356		/* If RFC4507 ticket use empty session ID. */
357		if (s->tlsext_ticket_expected) {
358			ss->session_id_length = 0;
359			goto sess_id_done;
360		}
361
362		/* Choose which callback will set the session ID. */
363		CRYPTO_r_lock(CRYPTO_LOCK_SSL_CTX);
364		if (s->generate_session_id)
365			cb = s->generate_session_id;
366		else if (s->session_ctx->generate_session_id)
367			cb = s->session_ctx->generate_session_id;
368		CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX);
369
370		/* Choose a session ID. */
371		tmp = ss->session_id_length;
372		if (!cb(s, ss->session_id, &tmp)) {
373			/* The callback failed */
374			SSLerror(s, SSL_R_SSL_SESSION_ID_CALLBACK_FAILED);
375			SSL_SESSION_free(ss);
376			return (0);
377		}
378
379		/*
380		 * Don't allow the callback to set the session length to zero.
381		 * nor set it higher than it was.
382		 */
383		if (tmp == 0 || tmp > ss->session_id_length) {
384			/* The callback set an illegal length */
385			SSLerror(s, SSL_R_SSL_SESSION_ID_HAS_BAD_LENGTH);
386			SSL_SESSION_free(ss);
387			return (0);
388		}
389		ss->session_id_length = tmp;
390
391		/* Finally, check for a conflict. */
392		if (SSL_has_matching_session_id(s, ss->session_id,
393		    ss->session_id_length)) {
394			SSLerror(s, SSL_R_SSL_SESSION_ID_CONFLICT);
395			SSL_SESSION_free(ss);
396			return (0);
397		}
398
399 sess_id_done:
400		if (s->tlsext_hostname) {
401			ss->tlsext_hostname = strdup(s->tlsext_hostname);
402			if (ss->tlsext_hostname == NULL) {
403				SSLerror(s, ERR_R_INTERNAL_ERROR);
404				SSL_SESSION_free(ss);
405				return 0;
406			}
407		}
408	} else {
409		ss->session_id_length = 0;
410	}
411
412	if (s->sid_ctx_length > sizeof ss->sid_ctx) {
413		SSLerror(s, ERR_R_INTERNAL_ERROR);
414		SSL_SESSION_free(ss);
415		return 0;
416	}
417
418	memcpy(ss->sid_ctx, s->sid_ctx, s->sid_ctx_length);
419	ss->sid_ctx_length = s->sid_ctx_length;
420	s->session = ss;
421	ss->ssl_version = s->version;
422	ss->verify_result = X509_V_OK;
423
424	return (1);
425}
426
427static SSL_SESSION *
428ssl_session_from_cache(SSL *s, CBS *session_id)
429{
430	SSL_SESSION *sess;
431	SSL_SESSION data;
432
433	if ((s->session_ctx->session_cache_mode &
434	     SSL_SESS_CACHE_NO_INTERNAL_LOOKUP))
435		return NULL;
436
437	memset(&data, 0, sizeof(data));
438
439	data.ssl_version = s->version;
440
441	if (!CBS_write_bytes(session_id, data.session_id,
442	    sizeof(data.session_id), &data.session_id_length))
443		return NULL;
444
445	CRYPTO_r_lock(CRYPTO_LOCK_SSL_CTX);
446	sess = lh_SSL_SESSION_retrieve(s->session_ctx->sessions, &data);
447	if (sess != NULL)
448		CRYPTO_add(&sess->references, 1, CRYPTO_LOCK_SSL_SESSION);
449	CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX);
450
451	if (sess == NULL)
452		s->session_ctx->stats.sess_miss++;
453
454	return sess;
455}
456
457static SSL_SESSION *
458ssl_session_from_callback(SSL *s, CBS *session_id)
459{
460	SSL_SESSION *sess;
461	int copy;
462
463	if (s->session_ctx->get_session_cb == NULL)
464		return NULL;
465
466	copy = 1;
467	if ((sess = s->session_ctx->get_session_cb(s,
468	    CBS_data(session_id), CBS_len(session_id), &copy)) == NULL)
469		return NULL;
470	/*
471	 * The copy handler may have set copy == 0 to indicate that the session
472	 * structures are shared between threads and that it handles the
473	 * reference count itself. If it didn't set copy to zero, we must
474	 * increment the reference count.
475	 */
476	if (copy)
477		CRYPTO_add(&sess->references, 1, CRYPTO_LOCK_SSL_SESSION);
478
479	s->session_ctx->stats.sess_cb_hit++;
480
481	/* Add the externally cached session to the internal cache as well. */
482	if (!(s->session_ctx->session_cache_mode &
483	    SSL_SESS_CACHE_NO_INTERNAL_STORE)) {
484		/*
485		 * The following should not return 1,
486		 * otherwise, things are very strange.
487		 */
488		SSL_CTX_add_session(s->session_ctx, sess);
489	}
490
491	return sess;
492}
493
494static SSL_SESSION *
495ssl_session_by_id(SSL *s, CBS *session_id)
496{
497	SSL_SESSION *sess;
498
499	if (CBS_len(session_id) == 0)
500		return NULL;
501
502	if ((sess = ssl_session_from_cache(s, session_id)) == NULL)
503		sess = ssl_session_from_callback(s, session_id);
504
505	return sess;
506}
507
508/*
509 * ssl_get_prev_session attempts to find an SSL_SESSION to be used to resume
510 * this connection. It is only called by servers.
511 *
512 *   session_id: points at the session ID in the ClientHello. This code will
513 *       read past the end of this in order to parse out the session ticket
514 *       extension, if any.
515 *   ext_block: a CBS for the ClientHello extensions block.
516 *   alert: alert that the caller should send in case of failure.
517 *
518 * Returns:
519 *   -1: error
520 *    0: a session may have been found.
521 *
522 * Side effects:
523 *   - If a session is found then s->session is pointed at it (after freeing
524 *     an existing session if need be) and s->verify_result is set from the
525 *     session.
526 *   - For both new and resumed sessions, s->tlsext_ticket_expected
527 *     indicates whether the server should issue a new session ticket or not.
528 */
529int
530ssl_get_prev_session(SSL *s, CBS *session_id, CBS *ext_block, int *alert)
531{
532	SSL_SESSION *sess = NULL;
533	int alert_desc = SSL_AD_INTERNAL_ERROR, fatal = 0;
534	int ticket_decrypted = 0;
535
536	/* This is used only by servers. */
537
538	if (CBS_len(session_id) > SSL_MAX_SSL_SESSION_ID_LENGTH)
539		goto err;
540
541	/* Sets s->tlsext_ticket_expected. */
542	switch (tls1_process_ticket(s, ext_block, &alert_desc, &sess)) {
543	case TLS1_TICKET_FATAL_ERROR:
544		fatal = 1;
545		goto err;
546	case TLS1_TICKET_NONE:
547	case TLS1_TICKET_EMPTY:
548		if ((sess = ssl_session_by_id(s, session_id)) == NULL)
549			goto err;
550		break;
551	case TLS1_TICKET_NOT_DECRYPTED:
552		goto err;
553	case TLS1_TICKET_DECRYPTED:
554		ticket_decrypted = 1;
555
556		/*
557		 * The session ID is used by some clients to detect that the
558		 * ticket has been accepted so we copy it into sess.
559		 */
560		if (!CBS_write_bytes(session_id, sess->session_id,
561		    sizeof(sess->session_id), &sess->session_id_length)) {
562			fatal = 1;
563			goto err;
564		}
565		break;
566	default:
567		SSLerror(s, ERR_R_INTERNAL_ERROR);
568		fatal = 1;
569		goto err;
570	}
571
572	/* Now sess is non-NULL and we own one of its reference counts. */
573
574	if (sess->sid_ctx_length != s->sid_ctx_length ||
575	    timingsafe_memcmp(sess->sid_ctx, s->sid_ctx,
576	    sess->sid_ctx_length) != 0) {
577		/*
578		 * We have the session requested by the client, but we don't
579		 * want to use it in this context. Treat it like a cache miss.
580		 */
581		goto err;
582	}
583
584	if ((s->verify_mode & SSL_VERIFY_PEER) && s->sid_ctx_length == 0) {
585		/*
586		 * We can't be sure if this session is being used out of
587		 * context, which is especially important for SSL_VERIFY_PEER.
588		 * The application should have used
589		 * SSL[_CTX]_set_session_id_context.
590		 *
591		 * For this error case, we generate an error instead of treating
592		 * the event like a cache miss (otherwise it would be easy for
593		 * applications to effectively disable the session cache by
594		 * accident without anyone noticing).
595		 */
596		SSLerror(s, SSL_R_SESSION_ID_CONTEXT_UNINITIALIZED);
597		fatal = 1;
598		goto err;
599	}
600
601	if (sess->cipher == NULL) {
602		sess->cipher = ssl3_get_cipher_by_id(sess->cipher_id);
603		if (sess->cipher == NULL)
604			goto err;
605	}
606
607	if (sess->timeout < (time(NULL) - sess->time)) {
608		s->session_ctx->stats.sess_timeout++;
609		if (!ticket_decrypted) {
610			/* The session was from the cache, so remove it. */
611			SSL_CTX_remove_session(s->session_ctx, sess);
612		}
613		goto err;
614	}
615
616	s->session_ctx->stats.sess_hit++;
617
618	SSL_SESSION_free(s->session);
619	s->session = sess;
620	s->verify_result = s->session->verify_result;
621
622	return 1;
623
624 err:
625	SSL_SESSION_free(sess);
626	if (ticket_decrypted) {
627		/*
628		 * The session was from a ticket. Issue a ticket for the new
629		 * session.
630		 */
631		s->tlsext_ticket_expected = 1;
632	}
633	if (fatal) {
634		*alert = alert_desc;
635		return -1;
636	}
637	return 0;
638}
639
640int
641SSL_CTX_add_session(SSL_CTX *ctx, SSL_SESSION *c)
642{
643	int ret = 0;
644	SSL_SESSION *s;
645
646	/*
647	 * Add just 1 reference count for the SSL_CTX's session cache
648	 * even though it has two ways of access: each session is in a
649	 * doubly linked list and an lhash.
650	 */
651	CRYPTO_add(&c->references, 1, CRYPTO_LOCK_SSL_SESSION);
652
653	/*
654	 * If session c is in already in cache, we take back the increment
655	 * later.
656	 */
657	CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
658	s = lh_SSL_SESSION_insert(ctx->sessions, c);
659
660	/*
661	 * s != NULL iff we already had a session with the given PID.
662	 * In this case, s == c should hold (then we did not really modify
663	 * ctx->sessions), or we're in trouble.
664	 */
665	if (s != NULL && s != c) {
666		/* We *are* in trouble ... */
667		SSL_SESSION_list_remove(ctx, s);
668		SSL_SESSION_free(s);
669		/*
670		 * ... so pretend the other session did not exist in cache
671		 * (we cannot handle two SSL_SESSION structures with identical
672		 * session ID in the same cache, which could happen e.g. when
673		 * two threads concurrently obtain the same session from an
674		 * external cache).
675		 */
676		s = NULL;
677	}
678
679	/* Put at the head of the queue unless it is already in the cache */
680	if (s == NULL)
681		SSL_SESSION_list_add(ctx, c);
682
683	if (s != NULL) {
684		/*
685		 * existing cache entry -- decrement previously incremented
686		 * reference count because it already takes into account the
687		 * cache.
688		 */
689		SSL_SESSION_free(s); /* s == c */
690		ret = 0;
691	} else {
692		/*
693		 * New cache entry -- remove old ones if cache has become
694		 * too large.
695		 */
696
697		ret = 1;
698
699		if (SSL_CTX_sess_get_cache_size(ctx) > 0) {
700			while (SSL_CTX_sess_number(ctx) >
701			    SSL_CTX_sess_get_cache_size(ctx)) {
702				if (!remove_session_lock(ctx,
703				    ctx->session_cache_tail, 0))
704					break;
705				else
706					ctx->stats.sess_cache_full++;
707			}
708		}
709	}
710	CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
711	return (ret);
712}
713
714int
715SSL_CTX_remove_session(SSL_CTX *ctx, SSL_SESSION *c)
716{
717	return remove_session_lock(ctx, c, 1);
718}
719
720static int
721remove_session_lock(SSL_CTX *ctx, SSL_SESSION *c, int lck)
722{
723	SSL_SESSION *r;
724	int ret = 0;
725
726	if (c == NULL || c->session_id_length == 0)
727		return 0;
728
729	if (lck)
730		CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
731	if ((r = lh_SSL_SESSION_retrieve(ctx->sessions, c)) == c) {
732		ret = 1;
733		r = lh_SSL_SESSION_delete(ctx->sessions, c);
734		SSL_SESSION_list_remove(ctx, c);
735	}
736	if (lck)
737		CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
738
739	if (ret) {
740		r->not_resumable = 1;
741		if (ctx->remove_session_cb != NULL)
742			ctx->remove_session_cb(ctx, r);
743		SSL_SESSION_free(r);
744	}
745
746	return ret;
747}
748
749void
750SSL_SESSION_free(SSL_SESSION *ss)
751{
752	int i;
753
754	if (ss == NULL)
755		return;
756
757	i = CRYPTO_add(&ss->references, -1, CRYPTO_LOCK_SSL_SESSION);
758	if (i > 0)
759		return;
760
761	CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL_SESSION, ss, &ss->ex_data);
762
763	explicit_bzero(ss->master_key, sizeof ss->master_key);
764	explicit_bzero(ss->session_id, sizeof ss->session_id);
765
766	X509_free(ss->peer_cert);
767
768	sk_SSL_CIPHER_free(ss->ciphers);
769
770	free(ss->tlsext_hostname);
771	free(ss->tlsext_tick);
772	free(ss->tlsext_ecpointformatlist);
773	free(ss->tlsext_supportedgroups);
774
775	tls13_secret_cleanup(&ss->resumption_master_secret);
776
777	freezero(ss, sizeof(*ss));
778}
779
780int
781SSL_SESSION_up_ref(SSL_SESSION *ss)
782{
783	int refs = CRYPTO_add(&ss->references, 1, CRYPTO_LOCK_SSL_SESSION);
784	return (refs > 1) ? 1 : 0;
785}
786
787int
788SSL_set_session(SSL *s, SSL_SESSION *session)
789{
790	const SSL_METHOD *method;
791
792	if (session == NULL) {
793		SSL_SESSION_free(s->session);
794		s->session = NULL;
795
796		return SSL_set_ssl_method(s, s->ctx->method);
797	}
798
799	if ((method = ssl_get_method(session->ssl_version)) == NULL) {
800		SSLerror(s, SSL_R_UNABLE_TO_FIND_SSL_METHOD);
801		return (0);
802	}
803
804	if (!SSL_set_ssl_method(s, method))
805		return (0);
806
807	CRYPTO_add(&session->references, 1, CRYPTO_LOCK_SSL_SESSION);
808	SSL_SESSION_free(s->session);
809	s->session = session;
810	s->verify_result = s->session->verify_result;
811
812	return (1);
813}
814
815size_t
816SSL_SESSION_get_master_key(const SSL_SESSION *ss, unsigned char *out,
817    size_t max_out)
818{
819	size_t len = ss->master_key_length;
820
821	if (out == NULL)
822		return len;
823
824	if (len > max_out)
825		len = max_out;
826
827	memcpy(out, ss->master_key, len);
828
829	return len;
830}
831
832long
833SSL_SESSION_set_timeout(SSL_SESSION *s, long t)
834{
835	if (s == NULL)
836		return (0);
837	s->timeout = t;
838	return (1);
839}
840
841long
842SSL_SESSION_get_timeout(const SSL_SESSION *s)
843{
844	if (s == NULL)
845		return (0);
846	return (s->timeout);
847}
848
849/* XXX 2038 */
850long
851SSL_SESSION_get_time(const SSL_SESSION *s)
852{
853	if (s == NULL)
854		return (0);
855	return (s->time);
856}
857
858/* XXX 2038 */
859long
860SSL_SESSION_set_time(SSL_SESSION *s, long t)
861{
862	if (s == NULL)
863		return (0);
864	s->time = t;
865	return (t);
866}
867
868int
869SSL_SESSION_get_protocol_version(const SSL_SESSION *s)
870{
871	return s->ssl_version;
872}
873
874const SSL_CIPHER *
875SSL_SESSION_get0_cipher(const SSL_SESSION *s)
876{
877	return s->cipher;
878}
879
880X509 *
881SSL_SESSION_get0_peer(SSL_SESSION *s)
882{
883	return s->peer_cert;
884}
885
886int
887SSL_SESSION_set1_id(SSL_SESSION *s, const unsigned char *sid,
888    unsigned int sid_len)
889{
890	if (sid_len > SSL_MAX_SSL_SESSION_ID_LENGTH) {
891		SSLerrorx(SSL_R_SSL_SESSION_ID_TOO_LONG);
892		return 0;
893	}
894	s->session_id_length = sid_len;
895	memmove(s->session_id, sid, sid_len);
896	return 1;
897}
898
899int
900SSL_SESSION_set1_id_context(SSL_SESSION *s, const unsigned char *sid_ctx,
901    unsigned int sid_ctx_len)
902{
903	if (sid_ctx_len > SSL_MAX_SID_CTX_LENGTH) {
904		SSLerrorx(SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
905		return 0;
906	}
907	s->sid_ctx_length = sid_ctx_len;
908	memcpy(s->sid_ctx, sid_ctx, sid_ctx_len);
909
910	return 1;
911}
912
913int
914SSL_SESSION_is_resumable(const SSL_SESSION *s)
915{
916	return 0;
917}
918
919long
920SSL_CTX_set_timeout(SSL_CTX *s, long t)
921{
922	long l;
923
924	if (s == NULL)
925		return (0);
926	l = s->session_timeout;
927	s->session_timeout = t;
928
929	return (l);
930}
931
932long
933SSL_CTX_get_timeout(const SSL_CTX *s)
934{
935	if (s == NULL)
936		return (0);
937	return (s->session_timeout);
938}
939
940int
941SSL_set_session_secret_cb(SSL *s, int (*tls_session_secret_cb)(SSL *s,
942    void *secret, int *secret_len, STACK_OF(SSL_CIPHER) *peer_ciphers,
943    SSL_CIPHER **cipher, void *arg), void *arg)
944{
945	if (s == NULL)
946		return (0);
947	s->tls_session_secret_cb = tls_session_secret_cb;
948	s->tls_session_secret_cb_arg = arg;
949	return (1);
950}
951
952int
953SSL_set_session_ticket_ext_cb(SSL *s, tls_session_ticket_ext_cb_fn cb,
954    void *arg)
955{
956	if (s == NULL)
957		return (0);
958	s->tls_session_ticket_ext_cb = cb;
959	s->tls_session_ticket_ext_cb_arg = arg;
960	return (1);
961}
962
963int
964SSL_set_session_ticket_ext(SSL *s, void *ext_data, int ext_len)
965{
966	if (s->version >= TLS1_VERSION) {
967		free(s->tlsext_session_ticket);
968		s->tlsext_session_ticket =
969		    malloc(sizeof(TLS_SESSION_TICKET_EXT) + ext_len);
970		if (!s->tlsext_session_ticket) {
971			SSLerror(s, ERR_R_MALLOC_FAILURE);
972			return 0;
973		}
974
975		if (ext_data) {
976			s->tlsext_session_ticket->length = ext_len;
977			s->tlsext_session_ticket->data =
978			    s->tlsext_session_ticket + 1;
979			memcpy(s->tlsext_session_ticket->data,
980			    ext_data, ext_len);
981		} else {
982			s->tlsext_session_ticket->length = 0;
983			s->tlsext_session_ticket->data = NULL;
984		}
985
986		return 1;
987	}
988
989	return 0;
990}
991
992typedef struct timeout_param_st {
993	SSL_CTX *ctx;
994	long time;
995	struct lhash_st_SSL_SESSION *cache;
996} TIMEOUT_PARAM;
997
998static void
999timeout_doall_arg(SSL_SESSION *s, TIMEOUT_PARAM *p)
1000{
1001	if ((p->time == 0) || (p->time > (s->time + s->timeout))) {
1002		/* timeout */
1003		/* The reason we don't call SSL_CTX_remove_session() is to
1004		 * save on locking overhead */
1005		(void)lh_SSL_SESSION_delete(p->cache, s);
1006		SSL_SESSION_list_remove(p->ctx, s);
1007		s->not_resumable = 1;
1008		if (p->ctx->remove_session_cb != NULL)
1009			p->ctx->remove_session_cb(p->ctx, s);
1010		SSL_SESSION_free(s);
1011	}
1012}
1013
1014static void
1015timeout_LHASH_DOALL_ARG(void *arg1, void *arg2)
1016{
1017	SSL_SESSION *a = arg1;
1018	TIMEOUT_PARAM *b = arg2;
1019
1020	timeout_doall_arg(a, b);
1021}
1022
1023/* XXX 2038 */
1024void
1025SSL_CTX_flush_sessions(SSL_CTX *s, long t)
1026{
1027	unsigned long i;
1028	TIMEOUT_PARAM tp;
1029
1030	tp.ctx = s;
1031	tp.cache = s->sessions;
1032	if (tp.cache == NULL)
1033		return;
1034	tp.time = t;
1035	CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
1036	i = CHECKED_LHASH_OF(SSL_SESSION, tp.cache)->down_load;
1037	CHECKED_LHASH_OF(SSL_SESSION, tp.cache)->down_load = 0;
1038	lh_SSL_SESSION_doall_arg(tp.cache, timeout_LHASH_DOALL_ARG,
1039	TIMEOUT_PARAM, &tp);
1040	CHECKED_LHASH_OF(SSL_SESSION, tp.cache)->down_load = i;
1041	CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
1042}
1043
1044int
1045ssl_clear_bad_session(SSL *s)
1046{
1047	if ((s->session != NULL) && !(s->shutdown & SSL_SENT_SHUTDOWN) &&
1048	    !(SSL_in_init(s) || SSL_in_before(s))) {
1049		SSL_CTX_remove_session(s->ctx, s->session);
1050		return (1);
1051	} else
1052		return (0);
1053}
1054
1055/* locked by SSL_CTX in the calling function */
1056static void
1057SSL_SESSION_list_remove(SSL_CTX *ctx, SSL_SESSION *s)
1058{
1059	if (s->next == NULL || s->prev == NULL)
1060		return;
1061
1062	if (s->next == (SSL_SESSION *)&(ctx->session_cache_tail)) {
1063		/* last element in list */
1064		if (s->prev == (SSL_SESSION *)&(ctx->session_cache_head)) {
1065			/* only one element in list */
1066			ctx->session_cache_head = NULL;
1067			ctx->session_cache_tail = NULL;
1068		} else {
1069			ctx->session_cache_tail = s->prev;
1070			s->prev->next =
1071			    (SSL_SESSION *)&(ctx->session_cache_tail);
1072		}
1073	} else {
1074		if (s->prev == (SSL_SESSION *)&(ctx->session_cache_head)) {
1075			/* first element in list */
1076			ctx->session_cache_head = s->next;
1077			s->next->prev =
1078			    (SSL_SESSION *)&(ctx->session_cache_head);
1079		} else {
1080			/* middle of list */
1081			s->next->prev = s->prev;
1082			s->prev->next = s->next;
1083		}
1084	}
1085	s->prev = s->next = NULL;
1086}
1087
1088static void
1089SSL_SESSION_list_add(SSL_CTX *ctx, SSL_SESSION *s)
1090{
1091	if (s->next != NULL && s->prev != NULL)
1092		SSL_SESSION_list_remove(ctx, s);
1093
1094	if (ctx->session_cache_head == NULL) {
1095		ctx->session_cache_head = s;
1096		ctx->session_cache_tail = s;
1097		s->prev = (SSL_SESSION *)&(ctx->session_cache_head);
1098		s->next = (SSL_SESSION *)&(ctx->session_cache_tail);
1099	} else {
1100		s->next = ctx->session_cache_head;
1101		s->next->prev = s;
1102		s->prev = (SSL_SESSION *)&(ctx->session_cache_head);
1103		ctx->session_cache_head = s;
1104	}
1105}
1106
1107void
1108SSL_CTX_sess_set_new_cb(SSL_CTX *ctx,
1109    int (*cb)(struct ssl_st *ssl, SSL_SESSION *sess)) {
1110	ctx->new_session_cb = cb;
1111}
1112
1113int
1114(*SSL_CTX_sess_get_new_cb(SSL_CTX *ctx))(SSL *ssl, SSL_SESSION *sess)
1115{
1116	return ctx->new_session_cb;
1117}
1118
1119void
1120SSL_CTX_sess_set_remove_cb(SSL_CTX *ctx,
1121    void (*cb)(SSL_CTX *ctx, SSL_SESSION *sess))
1122{
1123	ctx->remove_session_cb = cb;
1124}
1125
1126void
1127(*SSL_CTX_sess_get_remove_cb(SSL_CTX *ctx))(SSL_CTX * ctx, SSL_SESSION *sess)
1128{
1129	return ctx->remove_session_cb;
1130}
1131
1132void
1133SSL_CTX_sess_set_get_cb(SSL_CTX *ctx, SSL_SESSION *(*cb)(struct ssl_st *ssl,
1134    const unsigned char *data, int len, int *copy))
1135{
1136	ctx->get_session_cb = cb;
1137}
1138
1139SSL_SESSION *
1140(*SSL_CTX_sess_get_get_cb(SSL_CTX *ctx))(SSL *ssl, const unsigned char *data,
1141    int len, int *copy)
1142{
1143	return ctx->get_session_cb;
1144}
1145
1146void
1147SSL_CTX_set_info_callback(SSL_CTX *ctx,
1148    void (*cb)(const SSL *ssl, int type, int val))
1149{
1150	ctx->info_callback = cb;
1151}
1152
1153void
1154(*SSL_CTX_get_info_callback(SSL_CTX *ctx))(const SSL *ssl, int type, int val)
1155{
1156	return ctx->info_callback;
1157}
1158
1159void
1160SSL_CTX_set_client_cert_cb(SSL_CTX *ctx,
1161    int (*cb)(SSL *ssl, X509 **x509, EVP_PKEY **pkey))
1162{
1163	ctx->client_cert_cb = cb;
1164}
1165
1166int
1167(*SSL_CTX_get_client_cert_cb(SSL_CTX *ctx))(SSL * ssl, X509 ** x509,
1168    EVP_PKEY **pkey)
1169{
1170	return ctx->client_cert_cb;
1171}
1172
1173#ifndef OPENSSL_NO_ENGINE
1174int
1175SSL_CTX_set_client_cert_engine(SSL_CTX *ctx, ENGINE *e)
1176{
1177	if (!ENGINE_init(e)) {
1178		SSLerrorx(ERR_R_ENGINE_LIB);
1179		return 0;
1180	}
1181	if (!ENGINE_get_ssl_client_cert_function(e)) {
1182		SSLerrorx(SSL_R_NO_CLIENT_CERT_METHOD);
1183		ENGINE_finish(e);
1184		return 0;
1185	}
1186	ctx->client_cert_engine = e;
1187	return 1;
1188}
1189#endif
1190
1191void
1192SSL_CTX_set_cookie_generate_cb(SSL_CTX *ctx,
1193    int (*cb)(SSL *ssl, unsigned char *cookie, unsigned int *cookie_len))
1194{
1195	ctx->app_gen_cookie_cb = cb;
1196}
1197
1198void
1199SSL_CTX_set_cookie_verify_cb(SSL_CTX *ctx,
1200    int (*cb)(SSL *ssl, const unsigned char *cookie, unsigned int cookie_len))
1201{
1202	ctx->app_verify_cookie_cb = cb;
1203}
1204
1205int
1206PEM_write_SSL_SESSION(FILE *fp, SSL_SESSION *x)
1207{
1208	return PEM_ASN1_write((i2d_of_void *)i2d_SSL_SESSION,
1209	    PEM_STRING_SSL_SESSION, fp, x, NULL, NULL, 0, NULL, NULL);
1210}
1211
1212SSL_SESSION *
1213PEM_read_SSL_SESSION(FILE *fp, SSL_SESSION **x, pem_password_cb *cb, void *u)
1214{
1215	return PEM_ASN1_read((d2i_of_void *)d2i_SSL_SESSION,
1216	    PEM_STRING_SSL_SESSION, fp, (void **)x, cb, u);
1217}
1218
1219SSL_SESSION *
1220PEM_read_bio_SSL_SESSION(BIO *bp, SSL_SESSION **x, pem_password_cb *cb, void *u)
1221{
1222	return PEM_ASN1_read_bio((d2i_of_void *)d2i_SSL_SESSION,
1223	    PEM_STRING_SSL_SESSION, bp, (void **)x, cb, u);
1224}
1225
1226int
1227PEM_write_bio_SSL_SESSION(BIO *bp, SSL_SESSION *x)
1228{
1229	return PEM_ASN1_write_bio((i2d_of_void *)i2d_SSL_SESSION,
1230	    PEM_STRING_SSL_SESSION, bp, x, NULL, NULL, 0, NULL, NULL);
1231}
1232