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