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