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