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