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