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