xref: /dragonfly/crypto/libressl/ssl/ssl_sess.c (revision f9993810)
1 /* $OpenBSD: ssl_sess.c,v 1.117 2022/08/17 07:39:19 jsing 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 
147 static void SSL_SESSION_list_remove(SSL_CTX *ctx, SSL_SESSION *s);
148 static void SSL_SESSION_list_add(SSL_CTX *ctx, SSL_SESSION *s);
149 static 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 */
152 SSL_SESSION *
153 SSL_get_session(const SSL *ssl)
154 {
155 	return (ssl->session);
156 }
157 
158 /* variant of SSL_get_session: caller really gets something */
159 SSL_SESSION *
160 SSL_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 
178 int
179 SSL_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 
186 int
187 SSL_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 
192 void *
193 SSL_SESSION_get_ex_data(const SSL_SESSION *s, int idx)
194 {
195 	return (CRYPTO_get_ex_data(&s->ex_data, idx));
196 }
197 
198 uint32_t
199 SSL_SESSION_get_max_early_data(const SSL_SESSION *s)
200 {
201 	return 0;
202 }
203 
204 int
205 SSL_SESSION_set_max_early_data(SSL_SESSION *s, uint32_t max_early_data)
206 {
207 	return 1;
208 }
209 
210 SSL_SESSION *
211 SSL_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 
245 const unsigned char *
246 SSL_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 
253 const unsigned char *
254 SSL_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 
261 unsigned int
262 SSL_SESSION_get_compress_id(const SSL_SESSION *ss)
263 {
264 	return 0;
265 }
266 
267 unsigned long
268 SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
269 {
270 	return s->tlsext_tick_lifetime_hint;
271 }
272 
273 int
274 SSL_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 
292 static int
293 def_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 
317 int
318 ssl_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->internal->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->internal->generate_session_id)
365 			cb = s->internal->generate_session_id;
366 		else if (s->session_ctx->internal->generate_session_id)
367 			cb = s->session_ctx->internal->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 
427 static SSL_SESSION *
428 ssl_session_from_cache(SSL *s, CBS *session_id)
429 {
430 	SSL_SESSION *sess;
431 	SSL_SESSION data;
432 
433 	if ((s->session_ctx->internal->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->internal->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->internal->stats.sess_miss++;
453 
454 	return sess;
455 }
456 
457 static SSL_SESSION *
458 ssl_session_from_callback(SSL *s, CBS *session_id)
459 {
460 	SSL_SESSION *sess;
461 	int copy;
462 
463 	if (s->session_ctx->internal->get_session_cb == NULL)
464 		return NULL;
465 
466 	copy = 1;
467 	if ((sess = s->session_ctx->internal->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->internal->stats.sess_cb_hit++;
480 
481 	/* Add the externally cached session to the internal cache as well. */
482 	if (!(s->session_ctx->internal->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 
494 static SSL_SESSION *
495 ssl_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->internal->tlsext_ticket_expected
527  *     indicates whether the server should issue a new session ticket or not.
528  */
529 int
530 ssl_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->internal->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->internal->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->internal->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->internal->tlsext_ticket_expected = 1;
632 	}
633 	if (fatal) {
634 		*alert = alert_desc;
635 		return -1;
636 	}
637 	return 0;
638 }
639 
640 int
641 SSL_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->internal->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->internal->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->internal->session_cache_tail, 0))
704 					break;
705 				else
706 					ctx->internal->stats.sess_cache_full++;
707 			}
708 		}
709 	}
710 	CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
711 	return (ret);
712 }
713 
714 int
715 SSL_CTX_remove_session(SSL_CTX *ctx, SSL_SESSION *c)
716 {
717 	return remove_session_lock(ctx, c, 1);
718 }
719 
720 static int
721 remove_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->internal->sessions, c)) == c) {
732 		ret = 1;
733 		r = lh_SSL_SESSION_delete(ctx->internal->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->internal->remove_session_cb != NULL)
742 			ctx->internal->remove_session_cb(ctx, r);
743 		SSL_SESSION_free(r);
744 	}
745 
746 	return ret;
747 }
748 
749 void
750 SSL_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 	freezero(ss, sizeof(*ss));
776 }
777 
778 int
779 SSL_SESSION_up_ref(SSL_SESSION *ss)
780 {
781 	int refs = CRYPTO_add(&ss->references, 1, CRYPTO_LOCK_SSL_SESSION);
782 	return (refs > 1) ? 1 : 0;
783 }
784 
785 int
786 SSL_set_session(SSL *s, SSL_SESSION *session)
787 {
788 	const SSL_METHOD *method;
789 
790 	if (session == NULL) {
791 		SSL_SESSION_free(s->session);
792 		s->session = NULL;
793 
794 		return SSL_set_ssl_method(s, s->ctx->method);
795 	}
796 
797 	if ((method = ssl_get_method(session->ssl_version)) == NULL) {
798 		SSLerror(s, SSL_R_UNABLE_TO_FIND_SSL_METHOD);
799 		return (0);
800 	}
801 
802 	if (!SSL_set_ssl_method(s, method))
803 		return (0);
804 
805 	CRYPTO_add(&session->references, 1, CRYPTO_LOCK_SSL_SESSION);
806 	SSL_SESSION_free(s->session);
807 	s->session = session;
808 	s->verify_result = s->session->verify_result;
809 
810 	return (1);
811 }
812 
813 size_t
814 SSL_SESSION_get_master_key(const SSL_SESSION *ss, unsigned char *out,
815     size_t max_out)
816 {
817 	size_t len = ss->master_key_length;
818 
819 	if (out == NULL)
820 		return len;
821 
822 	if (len > max_out)
823 		len = max_out;
824 
825 	memcpy(out, ss->master_key, len);
826 
827 	return len;
828 }
829 
830 long
831 SSL_SESSION_set_timeout(SSL_SESSION *s, long t)
832 {
833 	if (s == NULL)
834 		return (0);
835 	s->timeout = t;
836 	return (1);
837 }
838 
839 long
840 SSL_SESSION_get_timeout(const SSL_SESSION *s)
841 {
842 	if (s == NULL)
843 		return (0);
844 	return (s->timeout);
845 }
846 
847 /* XXX 2038 */
848 long
849 SSL_SESSION_get_time(const SSL_SESSION *s)
850 {
851 	if (s == NULL)
852 		return (0);
853 	return (s->time);
854 }
855 
856 /* XXX 2038 */
857 long
858 SSL_SESSION_set_time(SSL_SESSION *s, long t)
859 {
860 	if (s == NULL)
861 		return (0);
862 	s->time = t;
863 	return (t);
864 }
865 
866 int
867 SSL_SESSION_get_protocol_version(const SSL_SESSION *s)
868 {
869 	return s->ssl_version;
870 }
871 
872 const SSL_CIPHER *
873 SSL_SESSION_get0_cipher(const SSL_SESSION *s)
874 {
875 	return s->cipher;
876 }
877 
878 X509 *
879 SSL_SESSION_get0_peer(SSL_SESSION *s)
880 {
881 	return s->peer_cert;
882 }
883 
884 int
885 SSL_SESSION_set1_id(SSL_SESSION *s, const unsigned char *sid,
886     unsigned int sid_len)
887 {
888 	if (sid_len > SSL_MAX_SSL_SESSION_ID_LENGTH) {
889 		SSLerrorx(SSL_R_SSL_SESSION_ID_TOO_LONG);
890 		return 0;
891 	}
892 	s->session_id_length = sid_len;
893 	memmove(s->session_id, sid, sid_len);
894 	return 1;
895 }
896 
897 int
898 SSL_SESSION_set1_id_context(SSL_SESSION *s, const unsigned char *sid_ctx,
899     unsigned int sid_ctx_len)
900 {
901 	if (sid_ctx_len > SSL_MAX_SID_CTX_LENGTH) {
902 		SSLerrorx(SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
903 		return 0;
904 	}
905 	s->sid_ctx_length = sid_ctx_len;
906 	memcpy(s->sid_ctx, sid_ctx, sid_ctx_len);
907 
908 	return 1;
909 }
910 
911 int
912 SSL_SESSION_is_resumable(const SSL_SESSION *s)
913 {
914 	return 0;
915 }
916 
917 long
918 SSL_CTX_set_timeout(SSL_CTX *s, long t)
919 {
920 	long l;
921 
922 	if (s == NULL)
923 		return (0);
924 	l = s->session_timeout;
925 	s->session_timeout = t;
926 
927 	return (l);
928 }
929 
930 long
931 SSL_CTX_get_timeout(const SSL_CTX *s)
932 {
933 	if (s == NULL)
934 		return (0);
935 	return (s->session_timeout);
936 }
937 
938 int
939 SSL_set_session_secret_cb(SSL *s, int (*tls_session_secret_cb)(SSL *s,
940     void *secret, int *secret_len, STACK_OF(SSL_CIPHER) *peer_ciphers,
941     SSL_CIPHER **cipher, void *arg), void *arg)
942 {
943 	if (s == NULL)
944 		return (0);
945 	s->internal->tls_session_secret_cb = tls_session_secret_cb;
946 	s->internal->tls_session_secret_cb_arg = arg;
947 	return (1);
948 }
949 
950 int
951 SSL_set_session_ticket_ext_cb(SSL *s, tls_session_ticket_ext_cb_fn cb,
952     void *arg)
953 {
954 	if (s == NULL)
955 		return (0);
956 	s->internal->tls_session_ticket_ext_cb = cb;
957 	s->internal->tls_session_ticket_ext_cb_arg = arg;
958 	return (1);
959 }
960 
961 int
962 SSL_set_session_ticket_ext(SSL *s, void *ext_data, int ext_len)
963 {
964 	if (s->version >= TLS1_VERSION) {
965 		free(s->internal->tlsext_session_ticket);
966 		s->internal->tlsext_session_ticket =
967 		    malloc(sizeof(TLS_SESSION_TICKET_EXT) + ext_len);
968 		if (!s->internal->tlsext_session_ticket) {
969 			SSLerror(s, ERR_R_MALLOC_FAILURE);
970 			return 0;
971 		}
972 
973 		if (ext_data) {
974 			s->internal->tlsext_session_ticket->length = ext_len;
975 			s->internal->tlsext_session_ticket->data =
976 			    s->internal->tlsext_session_ticket + 1;
977 			memcpy(s->internal->tlsext_session_ticket->data,
978 			    ext_data, ext_len);
979 		} else {
980 			s->internal->tlsext_session_ticket->length = 0;
981 			s->internal->tlsext_session_ticket->data = NULL;
982 		}
983 
984 		return 1;
985 	}
986 
987 	return 0;
988 }
989 
990 typedef struct timeout_param_st {
991 	SSL_CTX *ctx;
992 	long time;
993 	struct lhash_st_SSL_SESSION *cache;
994 } TIMEOUT_PARAM;
995 
996 static void
997 timeout_doall_arg(SSL_SESSION *s, TIMEOUT_PARAM *p)
998 {
999 	if ((p->time == 0) || (p->time > (s->time + s->timeout))) {
1000 		/* timeout */
1001 		/* The reason we don't call SSL_CTX_remove_session() is to
1002 		 * save on locking overhead */
1003 		(void)lh_SSL_SESSION_delete(p->cache, s);
1004 		SSL_SESSION_list_remove(p->ctx, s);
1005 		s->not_resumable = 1;
1006 		if (p->ctx->internal->remove_session_cb != NULL)
1007 			p->ctx->internal->remove_session_cb(p->ctx, s);
1008 		SSL_SESSION_free(s);
1009 	}
1010 }
1011 
1012 static void
1013 timeout_LHASH_DOALL_ARG(void *arg1, void *arg2)
1014 {
1015 	SSL_SESSION *a = arg1;
1016 	TIMEOUT_PARAM *b = arg2;
1017 
1018 	timeout_doall_arg(a, b);
1019 }
1020 
1021 /* XXX 2038 */
1022 void
1023 SSL_CTX_flush_sessions(SSL_CTX *s, long t)
1024 {
1025 	unsigned long i;
1026 	TIMEOUT_PARAM tp;
1027 
1028 	tp.ctx = s;
1029 	tp.cache = s->internal->sessions;
1030 	if (tp.cache == NULL)
1031 		return;
1032 	tp.time = t;
1033 	CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
1034 	i = CHECKED_LHASH_OF(SSL_SESSION, tp.cache)->down_load;
1035 	CHECKED_LHASH_OF(SSL_SESSION, tp.cache)->down_load = 0;
1036 	lh_SSL_SESSION_doall_arg(tp.cache, timeout_LHASH_DOALL_ARG,
1037 	TIMEOUT_PARAM, &tp);
1038 	CHECKED_LHASH_OF(SSL_SESSION, tp.cache)->down_load = i;
1039 	CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
1040 }
1041 
1042 int
1043 ssl_clear_bad_session(SSL *s)
1044 {
1045 	if ((s->session != NULL) && !(s->internal->shutdown & SSL_SENT_SHUTDOWN) &&
1046 	    !(SSL_in_init(s) || SSL_in_before(s))) {
1047 		SSL_CTX_remove_session(s->ctx, s->session);
1048 		return (1);
1049 	} else
1050 		return (0);
1051 }
1052 
1053 /* locked by SSL_CTX in the calling function */
1054 static void
1055 SSL_SESSION_list_remove(SSL_CTX *ctx, SSL_SESSION *s)
1056 {
1057 	if (s->next == NULL || s->prev == NULL)
1058 		return;
1059 
1060 	if (s->next == (SSL_SESSION *)&(ctx->internal->session_cache_tail)) {
1061 		/* last element in list */
1062 		if (s->prev == (SSL_SESSION *)&(ctx->internal->session_cache_head)) {
1063 			/* only one element in list */
1064 			ctx->internal->session_cache_head = NULL;
1065 			ctx->internal->session_cache_tail = NULL;
1066 		} else {
1067 			ctx->internal->session_cache_tail = s->prev;
1068 			s->prev->next =
1069 			    (SSL_SESSION *)&(ctx->internal->session_cache_tail);
1070 		}
1071 	} else {
1072 		if (s->prev == (SSL_SESSION *)&(ctx->internal->session_cache_head)) {
1073 			/* first element in list */
1074 			ctx->internal->session_cache_head = s->next;
1075 			s->next->prev =
1076 			    (SSL_SESSION *)&(ctx->internal->session_cache_head);
1077 		} else {
1078 			/* middle of list */
1079 			s->next->prev = s->prev;
1080 			s->prev->next = s->next;
1081 		}
1082 	}
1083 	s->prev = s->next = NULL;
1084 }
1085 
1086 static void
1087 SSL_SESSION_list_add(SSL_CTX *ctx, SSL_SESSION *s)
1088 {
1089 	if (s->next != NULL && s->prev != NULL)
1090 		SSL_SESSION_list_remove(ctx, s);
1091 
1092 	if (ctx->internal->session_cache_head == NULL) {
1093 		ctx->internal->session_cache_head = s;
1094 		ctx->internal->session_cache_tail = s;
1095 		s->prev = (SSL_SESSION *)&(ctx->internal->session_cache_head);
1096 		s->next = (SSL_SESSION *)&(ctx->internal->session_cache_tail);
1097 	} else {
1098 		s->next = ctx->internal->session_cache_head;
1099 		s->next->prev = s;
1100 		s->prev = (SSL_SESSION *)&(ctx->internal->session_cache_head);
1101 		ctx->internal->session_cache_head = s;
1102 	}
1103 }
1104 
1105 void
1106 SSL_CTX_sess_set_new_cb(SSL_CTX *ctx,
1107     int (*cb)(struct ssl_st *ssl, SSL_SESSION *sess)) {
1108 	ctx->internal->new_session_cb = cb;
1109 }
1110 
1111 int
1112 (*SSL_CTX_sess_get_new_cb(SSL_CTX *ctx))(SSL *ssl, SSL_SESSION *sess)
1113 {
1114 	return ctx->internal->new_session_cb;
1115 }
1116 
1117 void
1118 SSL_CTX_sess_set_remove_cb(SSL_CTX *ctx,
1119     void (*cb)(SSL_CTX *ctx, SSL_SESSION *sess))
1120 {
1121 	ctx->internal->remove_session_cb = cb;
1122 }
1123 
1124 void
1125 (*SSL_CTX_sess_get_remove_cb(SSL_CTX *ctx))(SSL_CTX * ctx, SSL_SESSION *sess)
1126 {
1127 	return ctx->internal->remove_session_cb;
1128 }
1129 
1130 void
1131 SSL_CTX_sess_set_get_cb(SSL_CTX *ctx, SSL_SESSION *(*cb)(struct ssl_st *ssl,
1132     const unsigned char *data, int len, int *copy))
1133 {
1134 	ctx->internal->get_session_cb = cb;
1135 }
1136 
1137 SSL_SESSION *
1138 (*SSL_CTX_sess_get_get_cb(SSL_CTX *ctx))(SSL *ssl, const unsigned char *data,
1139     int len, int *copy)
1140 {
1141 	return ctx->internal->get_session_cb;
1142 }
1143 
1144 void
1145 SSL_CTX_set_info_callback(SSL_CTX *ctx,
1146     void (*cb)(const SSL *ssl, int type, int val))
1147 {
1148 	ctx->internal->info_callback = cb;
1149 }
1150 
1151 void
1152 (*SSL_CTX_get_info_callback(SSL_CTX *ctx))(const SSL *ssl, int type, int val)
1153 {
1154 	return ctx->internal->info_callback;
1155 }
1156 
1157 void
1158 SSL_CTX_set_client_cert_cb(SSL_CTX *ctx,
1159     int (*cb)(SSL *ssl, X509 **x509, EVP_PKEY **pkey))
1160 {
1161 	ctx->internal->client_cert_cb = cb;
1162 }
1163 
1164 int
1165 (*SSL_CTX_get_client_cert_cb(SSL_CTX *ctx))(SSL * ssl, X509 ** x509,
1166     EVP_PKEY **pkey)
1167 {
1168 	return ctx->internal->client_cert_cb;
1169 }
1170 
1171 #ifndef OPENSSL_NO_ENGINE
1172 int
1173 SSL_CTX_set_client_cert_engine(SSL_CTX *ctx, ENGINE *e)
1174 {
1175 	if (!ENGINE_init(e)) {
1176 		SSLerrorx(ERR_R_ENGINE_LIB);
1177 		return 0;
1178 	}
1179 	if (!ENGINE_get_ssl_client_cert_function(e)) {
1180 		SSLerrorx(SSL_R_NO_CLIENT_CERT_METHOD);
1181 		ENGINE_finish(e);
1182 		return 0;
1183 	}
1184 	ctx->internal->client_cert_engine = e;
1185 	return 1;
1186 }
1187 #endif
1188 
1189 void
1190 SSL_CTX_set_cookie_generate_cb(SSL_CTX *ctx,
1191     int (*cb)(SSL *ssl, unsigned char *cookie, unsigned int *cookie_len))
1192 {
1193 	ctx->internal->app_gen_cookie_cb = cb;
1194 }
1195 
1196 void
1197 SSL_CTX_set_cookie_verify_cb(SSL_CTX *ctx,
1198     int (*cb)(SSL *ssl, const unsigned char *cookie, unsigned int cookie_len))
1199 {
1200 	ctx->internal->app_verify_cookie_cb = cb;
1201 }
1202 
1203 int
1204 PEM_write_SSL_SESSION(FILE *fp, SSL_SESSION *x)
1205 {
1206 	return PEM_ASN1_write((i2d_of_void *)i2d_SSL_SESSION,
1207 	    PEM_STRING_SSL_SESSION, fp, x, NULL, NULL, 0, NULL, NULL);
1208 }
1209 
1210 SSL_SESSION *
1211 PEM_read_SSL_SESSION(FILE *fp, SSL_SESSION **x, pem_password_cb *cb, void *u)
1212 {
1213 	return PEM_ASN1_read((d2i_of_void *)d2i_SSL_SESSION,
1214 	    PEM_STRING_SSL_SESSION, fp, (void **)x, cb, u);
1215 }
1216 
1217 SSL_SESSION *
1218 PEM_read_bio_SSL_SESSION(BIO *bp, SSL_SESSION **x, pem_password_cb *cb, void *u)
1219 {
1220 	return PEM_ASN1_read_bio((d2i_of_void *)d2i_SSL_SESSION,
1221 	    PEM_STRING_SSL_SESSION, bp, (void **)x, cb, u);
1222 }
1223 
1224 int
1225 PEM_write_bio_SSL_SESSION(BIO *bp, SSL_SESSION *x)
1226 {
1227 	return PEM_ASN1_write_bio((i2d_of_void *)i2d_SSL_SESSION,
1228 	    PEM_STRING_SSL_SESSION, bp, x, NULL, NULL, 0, NULL, NULL);
1229 }
1230