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