ssl_sess.c revision 1.40
1/* $OpenBSD: ssl_sess.c,v 1.40 2014/08/11 01:06:22 jsing Exp $ */
2/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3 * All rights reserved.
4 *
5 * This package is an SSL implementation written
6 * by Eric Young (eay@cryptsoft.com).
7 * The implementation was written so as to conform with Netscapes SSL.
8 *
9 * This library is free for commercial and non-commercial use as long as
10 * the following conditions are aheared to.  The following conditions
11 * apply to all code found in this distribution, be it the RC4, RSA,
12 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13 * included with this distribution is covered by the same copyright terms
14 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15 *
16 * Copyright remains Eric Young's, and as such any Copyright notices in
17 * the code are not to be removed.
18 * If this package is used in a product, Eric Young should be given attribution
19 * as the author of the parts of the library used.
20 * This can be in the form of a textual message at program startup or
21 * in documentation (online or textual) provided with the package.
22 *
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
25 * are met:
26 * 1. Redistributions of source code must retain the copyright
27 *    notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 *    notice, this list of conditions and the following disclaimer in the
30 *    documentation and/or other materials provided with the distribution.
31 * 3. All advertising materials mentioning features or use of this software
32 *    must display the following acknowledgement:
33 *    "This product includes cryptographic software written by
34 *     Eric Young (eay@cryptsoft.com)"
35 *    The word 'cryptographic' can be left out if the rouines from the library
36 *    being used are not cryptographic related :-).
37 * 4. If you include any Windows specific code (or a derivative thereof) from
38 *    the apps directory (application code) you must include an acknowledgement:
39 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40 *
41 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51 * SUCH DAMAGE.
52 *
53 * The licence and distribution terms for any publically available version or
54 * derivative of this code cannot be changed.  i.e. this code cannot simply be
55 * copied and put under another distribution licence
56 * [including the GNU Public Licence.]
57 */
58/* ====================================================================
59 * Copyright (c) 1998-2006 The OpenSSL Project.  All rights reserved.
60 *
61 * Redistribution and use in source and binary forms, with or without
62 * modification, are permitted provided that the following conditions
63 * are met:
64 *
65 * 1. Redistributions of source code must retain the above copyright
66 *    notice, this list of conditions and the following disclaimer.
67 *
68 * 2. Redistributions in binary form must reproduce the above copyright
69 *    notice, this list of conditions and the following disclaimer in
70 *    the documentation and/or other materials provided with the
71 *    distribution.
72 *
73 * 3. All advertising materials mentioning features or use of this
74 *    software must display the following acknowledgment:
75 *    "This product includes software developed by the OpenSSL Project
76 *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77 *
78 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79 *    endorse or promote products derived from this software without
80 *    prior written permission. For written permission, please contact
81 *    openssl-core@openssl.org.
82 *
83 * 5. Products derived from this software may not be called "OpenSSL"
84 *    nor may "OpenSSL" appear in their names without prior written
85 *    permission of the OpenSSL Project.
86 *
87 * 6. Redistributions of any form whatsoever must retain the following
88 *    acknowledgment:
89 *    "This product includes software developed by the OpenSSL Project
90 *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91 *
92 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103 * OF THE POSSIBILITY OF SUCH DAMAGE.
104 * ====================================================================
105 *
106 * This product includes cryptographic software written by Eric Young
107 * (eay@cryptsoft.com).  This product includes software written by Tim
108 * Hudson (tjh@cryptsoft.com).
109 *
110 */
111/* ====================================================================
112 * Copyright 2005 Nokia. All rights reserved.
113 *
114 * The portions of the attached software ("Contribution") is developed by
115 * Nokia Corporation and is licensed pursuant to the OpenSSL open source
116 * license.
117 *
118 * The Contribution, originally written by Mika Kousa and Pasi Eronen of
119 * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
120 * support (see RFC 4279) to OpenSSL.
121 *
122 * No patent licenses or other rights except those expressly stated in
123 * the OpenSSL open source license shall be deemed granted or received
124 * expressly, by implication, estoppel, or otherwise.
125 *
126 * No assurances are provided by Nokia that the Contribution does not
127 * infringe the patent or other intellectual property rights of any third
128 * party or that the license provides you with all the necessary rights
129 * to make use of the Contribution.
130 *
131 * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
132 * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
133 * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
134 * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
135 * OTHERWISE.
136 */
137
138#include <openssl/lhash.h>
139#include <openssl/rand.h>
140
141#ifndef OPENSSL_NO_ENGINE
142#include <openssl/engine.h>
143#endif
144
145#include "ssl_locl.h"
146
147static void SSL_SESSION_list_remove(SSL_CTX *ctx, SSL_SESSION *s);
148static void SSL_SESSION_list_add(SSL_CTX *ctx, SSL_SESSION *s);
149static 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 */
152SSL_SESSION *
153SSL_get_session(const SSL *ssl)
154{
155	return (ssl->session);
156}
157
158/* variant of SSL_get_session: caller really gets something */
159SSL_SESSION *
160SSL_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
178int
179SSL_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
186int
187SSL_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
192void *
193SSL_SESSION_get_ex_data(const SSL_SESSION *s, int idx)
194{
195	return (CRYPTO_get_ex_data(&s->ex_data, idx));
196}
197
198SSL_SESSION *
199SSL_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
227const unsigned char *
228SSL_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
235unsigned int
236SSL_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
255static int
256def_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
281int
282ssl_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
368sess_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 */
438int
439ssl_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		ret->cipher = ssl3_get_cipher_by_id(ret->cipher_id);
562		if (ret->cipher == NULL)
563			goto err;
564	}
565
566	if (ret->timeout < (time(NULL) - ret->time)) {
567		/* timeout */
568		s->session_ctx->stats.sess_timeout++;
569		if (try_session_cache) {
570			/* session was from the cache, so remove it */
571			SSL_CTX_remove_session(s->session_ctx, ret);
572		}
573		goto err;
574	}
575
576	s->session_ctx->stats.sess_hit++;
577
578	if (s->session != NULL)
579		SSL_SESSION_free(s->session);
580	s->session = ret;
581	s->verify_result = s->session->verify_result;
582	return 1;
583
584err:
585	if (ret != NULL) {
586		SSL_SESSION_free(ret);
587		if (!try_session_cache) {
588			/*
589			 * The session was from a ticket, so we should
590			 * issue a ticket for the new session.
591			 */
592			s->tlsext_ticket_expected = 1;
593		}
594	}
595	if (fatal)
596		return -1;
597	else
598		return 0;
599}
600
601int
602SSL_CTX_add_session(SSL_CTX *ctx, SSL_SESSION *c)
603{
604	int ret = 0;
605	SSL_SESSION *s;
606
607	/*
608	 * Add just 1 reference count for the SSL_CTX's session cache
609	 * even though it has two ways of access: each session is in a
610	 * doubly linked list and an lhash.
611	 */
612	CRYPTO_add(&c->references, 1, CRYPTO_LOCK_SSL_SESSION);
613
614	/*
615	 * If session c is in already in cache, we take back the increment
616	 * later.
617	 */
618	CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
619	s = lh_SSL_SESSION_insert(ctx->sessions, c);
620
621	/*
622	 * s != NULL iff we already had a session with the given PID.
623	 * In this case, s == c should hold (then we did not really modify
624	 * ctx->sessions), or we're in trouble.
625	 */
626	if (s != NULL && s != c) {
627		/* We *are* in trouble ... */
628		SSL_SESSION_list_remove(ctx, s);
629		SSL_SESSION_free(s);
630		/*
631		 * ... so pretend the other session did not exist in cache
632		 * (we cannot handle two SSL_SESSION structures with identical
633		 * session ID in the same cache, which could happen e.g. when
634		 * two threads concurrently obtain the same session from an
635		 * external cache).
636		 */
637		s = NULL;
638	}
639
640	/* Put at the head of the queue unless it is already in the cache */
641	if (s == NULL)
642		SSL_SESSION_list_add(ctx, c);
643
644	if (s != NULL) {
645		/*
646		 * existing cache entry -- decrement previously incremented
647		 * reference count because it already takes into account the
648		 * cache.
649		 */
650		SSL_SESSION_free(s); /* s == c */
651		ret = 0;
652	} else {
653		/*
654		 * New cache entry -- remove old ones if cache has become
655		 * too large.
656		 */
657
658		ret = 1;
659
660		if (SSL_CTX_sess_get_cache_size(ctx) > 0) {
661			while (SSL_CTX_sess_number(ctx) >
662			    SSL_CTX_sess_get_cache_size(ctx)) {
663				if (!remove_session_lock(ctx,
664				    ctx->session_cache_tail, 0))
665					break;
666				else
667					ctx->stats.sess_cache_full++;
668			}
669		}
670	}
671	CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
672	return (ret);
673}
674
675int
676SSL_CTX_remove_session(SSL_CTX *ctx, SSL_SESSION *c)
677{
678	return remove_session_lock(ctx, c, 1);
679}
680
681static int
682remove_session_lock(SSL_CTX *ctx, SSL_SESSION *c, int lck)
683{
684	SSL_SESSION *r;
685	int ret = 0;
686
687	if ((c != NULL) && (c->session_id_length != 0)) {
688		if (lck)
689			CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
690		if ((r = lh_SSL_SESSION_retrieve(ctx->sessions, c)) == c) {
691			ret = 1;
692			r = lh_SSL_SESSION_delete(ctx->sessions, c);
693			SSL_SESSION_list_remove(ctx, c);
694		}
695		if (lck)
696			CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
697
698		if (ret) {
699			r->not_resumable = 1;
700			if (ctx->remove_session_cb != NULL)
701				ctx->remove_session_cb(ctx, r);
702			SSL_SESSION_free(r);
703		}
704	} else
705		ret = 0;
706	return (ret);
707}
708
709void
710SSL_SESSION_free(SSL_SESSION *ss)
711{
712	int i;
713
714	if (ss == NULL)
715		return;
716
717	i = CRYPTO_add(&ss->references, -1, CRYPTO_LOCK_SSL_SESSION);
718	if (i > 0)
719		return;
720
721	CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL_SESSION, ss, &ss->ex_data);
722
723	OPENSSL_cleanse(ss->master_key, sizeof ss->master_key);
724	OPENSSL_cleanse(ss->session_id, sizeof ss->session_id);
725	if (ss->sess_cert != NULL)
726		ssl_sess_cert_free(ss->sess_cert);
727	if (ss->peer != NULL)
728		X509_free(ss->peer);
729	if (ss->ciphers != NULL)
730		sk_SSL_CIPHER_free(ss->ciphers);
731	free(ss->tlsext_hostname);
732	free(ss->tlsext_tick);
733	ss->tlsext_ecpointformatlist_length = 0;
734	free(ss->tlsext_ecpointformatlist);
735	ss->tlsext_ellipticcurvelist_length = 0;
736	free(ss->tlsext_ellipticcurvelist);
737	OPENSSL_cleanse(ss, sizeof(*ss));
738	free(ss);
739}
740
741int
742SSL_set_session(SSL *s, SSL_SESSION *session)
743{
744	int ret = 0;
745	const SSL_METHOD *meth;
746
747	if (session != NULL) {
748		meth = s->ctx->method->get_ssl_method(session->ssl_version);
749		if (meth == NULL)
750			meth = s->method->get_ssl_method(session->ssl_version);
751		if (meth == NULL) {
752			SSLerr(SSL_F_SSL_SET_SESSION,
753			    SSL_R_UNABLE_TO_FIND_SSL_METHOD);
754			return (0);
755		}
756
757		if (meth != s->method) {
758			if (!SSL_set_ssl_method(s, meth))
759				return (0);
760		}
761
762
763		/* CRYPTO_w_lock(CRYPTO_LOCK_SSL);*/
764		CRYPTO_add(&session->references, 1, CRYPTO_LOCK_SSL_SESSION);
765		if (s->session != NULL)
766			SSL_SESSION_free(s->session);
767		s->session = session;
768		s->verify_result = s->session->verify_result;
769		/* CRYPTO_w_unlock(CRYPTO_LOCK_SSL);*/
770		ret = 1;
771	} else {
772		if (s->session != NULL) {
773			SSL_SESSION_free(s->session);
774			s->session = NULL;
775		}
776
777		meth = s->ctx->method;
778		if (meth != s->method) {
779			if (!SSL_set_ssl_method(s, meth))
780				return (0);
781		}
782		ret = 1;
783	}
784	return (ret);
785}
786
787long
788SSL_SESSION_set_timeout(SSL_SESSION *s, long t)
789{
790	if (s == NULL)
791		return (0);
792	s->timeout = t;
793	return (1);
794}
795
796long
797SSL_SESSION_get_timeout(const SSL_SESSION *s)
798{
799	if (s == NULL)
800		return (0);
801	return (s->timeout);
802}
803
804/* XXX 2038 */
805long
806SSL_SESSION_get_time(const SSL_SESSION *s)
807{
808	if (s == NULL)
809		return (0);
810	return (s->time);
811}
812
813/* XXX 2038 */
814long
815SSL_SESSION_set_time(SSL_SESSION *s, long t)
816{
817	if (s == NULL)
818		return (0);
819	s->time = t;
820	return (t);
821}
822
823X509 *
824SSL_SESSION_get0_peer(SSL_SESSION *s)
825{
826	return s->peer;
827}
828
829int
830SSL_SESSION_set1_id_context(SSL_SESSION *s, const unsigned char *sid_ctx,
831    unsigned int sid_ctx_len)
832{
833	if (sid_ctx_len > SSL_MAX_SID_CTX_LENGTH) {
834		SSLerr(SSL_F_SSL_SESSION_SET1_ID_CONTEXT,
835		    SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
836		return 0;
837	}
838	s->sid_ctx_length = sid_ctx_len;
839	memcpy(s->sid_ctx, sid_ctx, sid_ctx_len);
840
841	return 1;
842}
843
844long
845SSL_CTX_set_timeout(SSL_CTX *s, long t)
846{
847	long l;
848
849	if (s == NULL)
850		return (0);
851	l = s->session_timeout;
852	s->session_timeout = t;
853
854	return (l);
855}
856
857long
858SSL_CTX_get_timeout(const SSL_CTX *s)
859{
860	if (s == NULL)
861		return (0);
862	return (s->session_timeout);
863}
864
865int
866SSL_set_session_secret_cb(SSL *s, int (*tls_session_secret_cb)(SSL *s,
867    void *secret, int *secret_len, STACK_OF(SSL_CIPHER) *peer_ciphers,
868    SSL_CIPHER **cipher, void *arg), void *arg)
869{
870	if (s == NULL)
871		return (0);
872	s->tls_session_secret_cb = tls_session_secret_cb;
873	s->tls_session_secret_cb_arg = arg;
874	return (1);
875}
876
877int
878SSL_set_session_ticket_ext_cb(SSL *s, tls_session_ticket_ext_cb_fn cb,
879    void *arg)
880{
881	if (s == NULL)
882		return (0);
883	s->tls_session_ticket_ext_cb = cb;
884	s->tls_session_ticket_ext_cb_arg = arg;
885	return (1);
886}
887
888int
889SSL_set_session_ticket_ext(SSL *s, void *ext_data, int ext_len)
890{
891	if (s->version >= TLS1_VERSION) {
892		free(s->tlsext_session_ticket);
893		s->tlsext_session_ticket =
894		    malloc(sizeof(TLS_SESSION_TICKET_EXT) + ext_len);
895		if (!s->tlsext_session_ticket) {
896			SSLerr(SSL_F_SSL_SET_SESSION_TICKET_EXT,
897			    ERR_R_MALLOC_FAILURE);
898			return 0;
899		}
900
901		if (ext_data) {
902			s->tlsext_session_ticket->length = ext_len;
903			s->tlsext_session_ticket->data =
904			    s->tlsext_session_ticket + 1;
905			memcpy(s->tlsext_session_ticket->data,
906			    ext_data, ext_len);
907		} else {
908			s->tlsext_session_ticket->length = 0;
909			s->tlsext_session_ticket->data = NULL;
910		}
911
912		return 1;
913	}
914
915	return 0;
916}
917
918typedef struct timeout_param_st {
919	SSL_CTX *ctx;
920	long time;
921	LHASH_OF(SSL_SESSION) *cache;
922} TIMEOUT_PARAM;
923
924static void
925timeout_doall_arg(SSL_SESSION *s, TIMEOUT_PARAM *p)
926{
927	if ((p->time == 0) || (p->time > (s->time + s->timeout))) {
928		/* timeout */
929		/* The reason we don't call SSL_CTX_remove_session() is to
930		 * save on locking overhead */
931		(void)lh_SSL_SESSION_delete(p->cache, s);
932		SSL_SESSION_list_remove(p->ctx, s);
933		s->not_resumable = 1;
934		if (p->ctx->remove_session_cb != NULL)
935			p->ctx->remove_session_cb(p->ctx, s);
936		SSL_SESSION_free(s);
937	}
938}
939
940static
941IMPLEMENT_LHASH_DOALL_ARG_FN(timeout, SSL_SESSION, TIMEOUT_PARAM)
942
943/* XXX 2038 */
944void
945SSL_CTX_flush_sessions(SSL_CTX *s, long t)
946{
947	unsigned long i;
948	TIMEOUT_PARAM tp;
949
950	tp.ctx = s;
951	tp.cache = s->sessions;
952	if (tp.cache == NULL)
953		return;
954	tp.time = t;
955	CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
956	i = CHECKED_LHASH_OF(SSL_SESSION, tp.cache)->down_load;
957	CHECKED_LHASH_OF(SSL_SESSION, tp.cache)->down_load = 0;
958	lh_SSL_SESSION_doall_arg(tp.cache, LHASH_DOALL_ARG_FN(timeout),
959	TIMEOUT_PARAM, &tp);
960	CHECKED_LHASH_OF(SSL_SESSION, tp.cache)->down_load = i;
961	CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
962}
963
964int
965ssl_clear_bad_session(SSL *s)
966{
967	if ((s->session != NULL) && !(s->shutdown & SSL_SENT_SHUTDOWN) &&
968	    !(SSL_in_init(s) || SSL_in_before(s))) {
969		SSL_CTX_remove_session(s->ctx, s->session);
970		return (1);
971	} else
972		return (0);
973}
974
975/* locked by SSL_CTX in the calling function */
976static void
977SSL_SESSION_list_remove(SSL_CTX *ctx, SSL_SESSION *s)
978{
979	if ((s->next == NULL) || (s->prev == NULL))
980		return;
981
982	if (s->next == (SSL_SESSION *)&(ctx->session_cache_tail)) {
983		/* last element in list */
984		if (s->prev == (SSL_SESSION *)&(ctx->session_cache_head)) {
985			/* only one element in list */
986			ctx->session_cache_head = NULL;
987			ctx->session_cache_tail = NULL;
988		} else {
989			ctx->session_cache_tail = s->prev;
990			s->prev->next =
991			    (SSL_SESSION *)&(ctx->session_cache_tail);
992		}
993	} else {
994		if (s->prev == (SSL_SESSION *)&(ctx->session_cache_head)) {
995			/* first element in list */
996			ctx->session_cache_head = s->next;
997			s->next->prev =
998			    (SSL_SESSION *)&(ctx->session_cache_head);
999		} else {
1000			/* middle of list */
1001			s->next->prev = s->prev;
1002			s->prev->next = s->next;
1003		}
1004	}
1005	s->prev = s->next = NULL;
1006}
1007
1008static void
1009SSL_SESSION_list_add(SSL_CTX *ctx, SSL_SESSION *s)
1010{
1011	if ((s->next != NULL) && (s->prev != NULL))
1012		SSL_SESSION_list_remove(ctx, s);
1013
1014	if (ctx->session_cache_head == NULL) {
1015		ctx->session_cache_head = s;
1016		ctx->session_cache_tail = s;
1017		s->prev = (SSL_SESSION *)&(ctx->session_cache_head);
1018		s->next = (SSL_SESSION *)&(ctx->session_cache_tail);
1019	} else {
1020		s->next = ctx->session_cache_head;
1021		s->next->prev = s;
1022		s->prev = (SSL_SESSION *)&(ctx->session_cache_head);
1023		ctx->session_cache_head = s;
1024	}
1025}
1026
1027void
1028SSL_CTX_sess_set_new_cb(SSL_CTX *ctx,
1029    int (*cb)(struct ssl_st *ssl, SSL_SESSION *sess)) {
1030	ctx->new_session_cb = cb;
1031}
1032
1033int
1034(*SSL_CTX_sess_get_new_cb(SSL_CTX *ctx))(SSL *ssl, SSL_SESSION *sess)
1035{
1036	return ctx->new_session_cb;
1037}
1038
1039void
1040SSL_CTX_sess_set_remove_cb(SSL_CTX *ctx,
1041    void (*cb)(SSL_CTX *ctx, SSL_SESSION *sess))
1042{
1043	ctx->remove_session_cb = cb;
1044}
1045
1046void
1047(*SSL_CTX_sess_get_remove_cb(SSL_CTX *ctx))(SSL_CTX * ctx, SSL_SESSION *sess)
1048{
1049	return ctx->remove_session_cb;
1050}
1051
1052void
1053SSL_CTX_sess_set_get_cb(SSL_CTX *ctx, SSL_SESSION *(*cb)(struct ssl_st *ssl,
1054    unsigned char *data, int len, int *copy))
1055{
1056	ctx->get_session_cb = cb;
1057}
1058
1059SSL_SESSION *
1060(*SSL_CTX_sess_get_get_cb(SSL_CTX *ctx))(SSL *ssl, unsigned char *data,
1061    int len, int *copy)
1062{
1063	return ctx->get_session_cb;
1064}
1065
1066void
1067SSL_CTX_set_info_callback(SSL_CTX *ctx,
1068    void (*cb)(const SSL *ssl, int type, int val))
1069{
1070	ctx->info_callback = cb;
1071}
1072
1073void
1074(*SSL_CTX_get_info_callback(SSL_CTX *ctx))(const SSL *ssl, int type, int val)
1075{
1076	return ctx->info_callback;
1077}
1078
1079void
1080SSL_CTX_set_client_cert_cb(SSL_CTX *ctx,
1081    int (*cb)(SSL *ssl, X509 **x509, EVP_PKEY **pkey))
1082{
1083	ctx->client_cert_cb = cb;
1084}
1085
1086int
1087(*SSL_CTX_get_client_cert_cb(SSL_CTX *ctx))(SSL * ssl, X509 ** x509,
1088    EVP_PKEY **pkey)
1089{
1090	return ctx->client_cert_cb;
1091}
1092
1093#ifndef OPENSSL_NO_ENGINE
1094int
1095SSL_CTX_set_client_cert_engine(SSL_CTX *ctx, ENGINE *e)
1096{
1097	if (!ENGINE_init(e)) {
1098		SSLerr(SSL_F_SSL_CTX_SET_CLIENT_CERT_ENGINE,
1099		    ERR_R_ENGINE_LIB);
1100		return 0;
1101	}
1102	if (!ENGINE_get_ssl_client_cert_function(e)) {
1103		SSLerr(SSL_F_SSL_CTX_SET_CLIENT_CERT_ENGINE,
1104		    SSL_R_NO_CLIENT_CERT_METHOD);
1105		ENGINE_finish(e);
1106		return 0;
1107	}
1108	ctx->client_cert_engine = e;
1109	return 1;
1110}
1111#endif
1112
1113void
1114SSL_CTX_set_cookie_generate_cb(SSL_CTX *ctx,
1115    int (*cb)(SSL *ssl, unsigned char *cookie, unsigned int *cookie_len))
1116{
1117	ctx->app_gen_cookie_cb = cb;
1118}
1119
1120void
1121SSL_CTX_set_cookie_verify_cb(SSL_CTX *ctx,
1122    int (*cb)(SSL *ssl, unsigned char *cookie, unsigned int cookie_len))
1123{
1124	ctx->app_verify_cookie_cb = cb;
1125}
1126
1127IMPLEMENT_PEM_rw(SSL_SESSION, SSL_SESSION, PEM_STRING_SSL_SESSION, SSL_SESSION)
1128