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