926b55c7ba2b1ad341065a8026425a77e402c179
[oweals/openssl.git] / ssl / ssl_sess.c
1 /*
2  * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 /* ====================================================================
11  * Copyright 2005 Nokia. All rights reserved.
12  *
13  * The portions of the attached software ("Contribution") is developed by
14  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
15  * license.
16  *
17  * The Contribution, originally written by Mika Kousa and Pasi Eronen of
18  * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
19  * support (see RFC 4279) to OpenSSL.
20  *
21  * No patent licenses or other rights except those expressly stated in
22  * the OpenSSL open source license shall be deemed granted or received
23  * expressly, by implication, estoppel, or otherwise.
24  *
25  * No assurances are provided by Nokia that the Contribution does not
26  * infringe the patent or other intellectual property rights of any third
27  * party or that the license provides you with all the necessary rights
28  * to make use of the Contribution.
29  *
30  * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
31  * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
32  * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
33  * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
34  * OTHERWISE.
35  */
36
37 #include <stdio.h>
38 #include <openssl/lhash.h>
39 #include <openssl/rand.h>
40 #include <openssl/engine.h>
41 #include "ssl_locl.h"
42
43 static void SSL_SESSION_list_remove(SSL_CTX *ctx, SSL_SESSION *s);
44 static void SSL_SESSION_list_add(SSL_CTX *ctx, SSL_SESSION *s);
45 static int remove_session_lock(SSL_CTX *ctx, SSL_SESSION *c, int lck);
46
47 SSL_SESSION *SSL_get_session(const SSL *ssl)
48 /* aka SSL_get0_session; gets 0 objects, just returns a copy of the pointer */
49 {
50     return (ssl->session);
51 }
52
53 SSL_SESSION *SSL_get1_session(SSL *ssl)
54 /* variant of SSL_get_session: caller really gets something */
55 {
56     SSL_SESSION *sess;
57     /*
58      * Need to lock this all up rather than just use CRYPTO_add so that
59      * somebody doesn't free ssl->session between when we check it's non-null
60      * and when we up the reference count.
61      */
62     CRYPTO_THREAD_read_lock(ssl->lock);
63     sess = ssl->session;
64     if (sess)
65         SSL_SESSION_up_ref(sess);
66     CRYPTO_THREAD_unlock(ssl->lock);
67     return sess;
68 }
69
70 int SSL_SESSION_set_ex_data(SSL_SESSION *s, int idx, void *arg)
71 {
72     return (CRYPTO_set_ex_data(&s->ex_data, idx, arg));
73 }
74
75 void *SSL_SESSION_get_ex_data(const SSL_SESSION *s, int idx)
76 {
77     return (CRYPTO_get_ex_data(&s->ex_data, idx));
78 }
79
80 SSL_SESSION *SSL_SESSION_new(void)
81 {
82     SSL_SESSION *ss;
83
84     ss = OPENSSL_zalloc(sizeof(*ss));
85     if (ss == NULL) {
86         SSLerr(SSL_F_SSL_SESSION_NEW, ERR_R_MALLOC_FAILURE);
87         return NULL;
88     }
89
90     ss->verify_result = 1;      /* avoid 0 (= X509_V_OK) just in case */
91     ss->references = 1;
92     ss->timeout = 60 * 5 + 4;   /* 5 minute timeout by default */
93     ss->time = (unsigned long)time(NULL);
94     ss->lock = CRYPTO_THREAD_lock_new();
95     if (ss->lock == NULL) {
96         SSLerr(SSL_F_SSL_SESSION_NEW, ERR_R_MALLOC_FAILURE);
97         OPENSSL_free(ss);
98         return NULL;
99     }
100
101     if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL_SESSION, ss, &ss->ex_data)) {
102         CRYPTO_THREAD_lock_free(ss->lock);
103         OPENSSL_free(ss);
104         return NULL;
105     }
106     return ss;
107 }
108
109 /*
110  * Create a new SSL_SESSION and duplicate the contents of |src| into it. If
111  * ticket == 0 then no ticket information is duplicated, otherwise it is.
112  */
113 SSL_SESSION *ssl_session_dup(SSL_SESSION *src, int ticket)
114 {
115     SSL_SESSION *dest;
116
117     dest = OPENSSL_malloc(sizeof(*src));
118     if (dest == NULL) {
119         goto err;
120     }
121     memcpy(dest, src, sizeof(*dest));
122
123     /*
124      * Set the various pointers to NULL so that we can call SSL_SESSION_free in
125      * the case of an error whilst halfway through constructing dest
126      */
127 #ifndef OPENSSL_NO_PSK
128     dest->psk_identity_hint = NULL;
129     dest->psk_identity = NULL;
130 #endif
131     dest->ciphers = NULL;
132     dest->tlsext_hostname = NULL;
133 #ifndef OPENSSL_NO_EC
134     dest->tlsext_ecpointformatlist = NULL;
135     dest->tlsext_ellipticcurvelist = NULL;
136 #endif
137     dest->tlsext_tick = NULL;
138 #ifndef OPENSSL_NO_SRP
139     dest->srp_username = NULL;
140 #endif
141     dest->peer_chain = NULL;
142     dest->peer = NULL;
143     memset(&dest->ex_data, 0, sizeof(dest->ex_data));
144
145     /* We deliberately don't copy the prev and next pointers */
146     dest->prev = NULL;
147     dest->next = NULL;
148
149     dest->references = 1;
150
151     dest->lock = CRYPTO_THREAD_lock_new();
152     if (dest->lock == NULL)
153         goto err;
154
155     if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL_SESSION, dest, &dest->ex_data))
156         goto err;
157
158     if (src->peer != NULL) {
159         if (!X509_up_ref(src->peer))
160             goto err;
161         dest->peer = src->peer;
162     }
163
164     if (src->peer_chain != NULL) {
165         dest->peer_chain = X509_chain_up_ref(src->peer_chain);
166         if (dest->peer_chain == NULL)
167             goto err;
168     }
169 #ifndef OPENSSL_NO_PSK
170     if (src->psk_identity_hint) {
171         dest->psk_identity_hint = OPENSSL_strdup(src->psk_identity_hint);
172         if (dest->psk_identity_hint == NULL) {
173             goto err;
174         }
175     }
176     if (src->psk_identity) {
177         dest->psk_identity = OPENSSL_strdup(src->psk_identity);
178         if (dest->psk_identity == NULL) {
179             goto err;
180         }
181     }
182 #endif
183
184     if (src->ciphers != NULL) {
185         dest->ciphers = sk_SSL_CIPHER_dup(src->ciphers);
186         if (dest->ciphers == NULL)
187             goto err;
188     }
189
190     if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_SSL_SESSION,
191                             &dest->ex_data, &src->ex_data)) {
192         goto err;
193     }
194
195     if (src->tlsext_hostname) {
196         dest->tlsext_hostname = OPENSSL_strdup(src->tlsext_hostname);
197         if (dest->tlsext_hostname == NULL) {
198             goto err;
199         }
200     }
201 #ifndef OPENSSL_NO_EC
202     if (src->tlsext_ecpointformatlist) {
203         dest->tlsext_ecpointformatlist =
204             OPENSSL_memdup(src->tlsext_ecpointformatlist,
205                            src->tlsext_ecpointformatlist_length);
206         if (dest->tlsext_ecpointformatlist == NULL)
207             goto err;
208     }
209     if (src->tlsext_ellipticcurvelist) {
210         dest->tlsext_ellipticcurvelist =
211             OPENSSL_memdup(src->tlsext_ellipticcurvelist,
212                            src->tlsext_ellipticcurvelist_length);
213         if (dest->tlsext_ellipticcurvelist == NULL)
214             goto err;
215     }
216 #endif
217
218     if (ticket != 0 && src->tlsext_tick != NULL) {
219         dest->tlsext_tick =
220             OPENSSL_memdup(src->tlsext_tick, src->tlsext_ticklen);
221         if (dest->tlsext_tick == NULL)
222             goto err;
223     } else {
224         dest->tlsext_tick_lifetime_hint = 0;
225         dest->tlsext_ticklen = 0;
226     }
227
228 #ifndef OPENSSL_NO_SRP
229     if (src->srp_username) {
230         dest->srp_username = OPENSSL_strdup(src->srp_username);
231         if (dest->srp_username == NULL) {
232             goto err;
233         }
234     }
235 #endif
236
237     return dest;
238  err:
239     SSLerr(SSL_F_SSL_SESSION_DUP, ERR_R_MALLOC_FAILURE);
240     SSL_SESSION_free(dest);
241     return NULL;
242 }
243
244 const unsigned char *SSL_SESSION_get_id(const SSL_SESSION *s, unsigned int *len)
245 {
246     if (len)
247         *len = s->session_id_length;
248     return s->session_id;
249 }
250 const unsigned char *SSL_SESSION_get0_id_context(const SSL_SESSION *s,
251                                                 unsigned int *len)
252 {
253     if (len != NULL)
254         *len = s->sid_ctx_length;
255     return s->sid_ctx;
256 }
257
258 unsigned int SSL_SESSION_get_compress_id(const SSL_SESSION *s)
259 {
260     return s->compress_meth;
261 }
262
263 /*
264  * SSLv3/TLSv1 has 32 bytes (256 bits) of session ID space. As such, filling
265  * the ID with random junk repeatedly until we have no conflict is going to
266  * complete in one iteration pretty much "most" of the time (btw:
267  * understatement). So, if it takes us 10 iterations and we still can't avoid
268  * a conflict - well that's a reasonable point to call it quits. Either the
269  * RAND code is broken or someone is trying to open roughly very close to
270  * 2^256 SSL sessions to our server. How you might store that many sessions
271  * is perhaps a more interesting question ...
272  */
273
274 #define MAX_SESS_ID_ATTEMPTS 10
275 static int def_generate_session_id(const SSL *ssl, unsigned char *id,
276                                    unsigned int *id_len)
277 {
278     unsigned int retry = 0;
279     do
280         if (RAND_bytes(id, *id_len) <= 0)
281             return 0;
282     while (SSL_has_matching_session_id(ssl, id, *id_len) &&
283            (++retry < MAX_SESS_ID_ATTEMPTS)) ;
284     if (retry < MAX_SESS_ID_ATTEMPTS)
285         return 1;
286     /* else - woops a session_id match */
287     /*
288      * XXX We should also check the external cache -- but the probability of
289      * a collision is negligible, and we could not prevent the concurrent
290      * creation of sessions with identical IDs since we currently don't have
291      * means to atomically check whether a session ID already exists and make
292      * a reservation for it if it does not (this problem applies to the
293      * internal cache as well).
294      */
295     return 0;
296 }
297
298 int ssl_get_new_session(SSL *s, int session)
299 {
300     /* This gets used by clients and servers. */
301
302     unsigned int tmp;
303     SSL_SESSION *ss = NULL;
304     GEN_SESSION_CB cb = def_generate_session_id;
305
306     if ((ss = SSL_SESSION_new()) == NULL)
307         return (0);
308
309     /* If the context has a default timeout, use it */
310     if (s->session_ctx->session_timeout == 0)
311         ss->timeout = SSL_get_default_timeout(s);
312     else
313         ss->timeout = s->session_ctx->session_timeout;
314
315     SSL_SESSION_free(s->session);
316     s->session = NULL;
317
318     if (session) {
319         if (s->version == SSL3_VERSION) {
320             ss->ssl_version = SSL3_VERSION;
321             ss->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
322         } else if (s->version == TLS1_VERSION) {
323             ss->ssl_version = TLS1_VERSION;
324             ss->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
325         } else if (s->version == TLS1_1_VERSION) {
326             ss->ssl_version = TLS1_1_VERSION;
327             ss->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
328         } else if (s->version == TLS1_2_VERSION) {
329             ss->ssl_version = TLS1_2_VERSION;
330             ss->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
331         } else if (s->version == DTLS1_BAD_VER) {
332             ss->ssl_version = DTLS1_BAD_VER;
333             ss->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
334         } else if (s->version == DTLS1_VERSION) {
335             ss->ssl_version = DTLS1_VERSION;
336             ss->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
337         } else if (s->version == DTLS1_2_VERSION) {
338             ss->ssl_version = DTLS1_2_VERSION;
339             ss->session_id_length = SSL3_SSL_SESSION_ID_LENGTH;
340         } else {
341             SSLerr(SSL_F_SSL_GET_NEW_SESSION, SSL_R_UNSUPPORTED_SSL_VERSION);
342             SSL_SESSION_free(ss);
343             return (0);
344         }
345
346         /*-
347          * If RFC5077 ticket, use empty session ID (as server).
348          * Note that:
349          * (a) ssl_get_prev_session() does lookahead into the
350          *     ClientHello extensions to find the session ticket.
351          *     When ssl_get_prev_session() fails, statem_srvr.c calls
352          *     ssl_get_new_session() in tls_process_client_hello().
353          *     At that point, it has not yet parsed the extensions,
354          *     however, because of the lookahead, it already knows
355          *     whether a ticket is expected or not.
356          *
357          * (b) statem_clnt.c calls ssl_get_new_session() before parsing
358          *     ServerHello extensions, and before recording the session
359          *     ID received from the server, so this block is a noop.
360          */
361         if (s->tlsext_ticket_expected) {
362             ss->session_id_length = 0;
363             goto sess_id_done;
364         }
365
366         /* Choose which callback will set the session ID */
367         CRYPTO_THREAD_read_lock(s->lock);
368         CRYPTO_THREAD_read_lock(s->session_ctx->lock);
369         if (s->generate_session_id)
370             cb = s->generate_session_id;
371         else if (s->session_ctx->generate_session_id)
372             cb = s->session_ctx->generate_session_id;
373         CRYPTO_THREAD_unlock(s->session_ctx->lock);
374         CRYPTO_THREAD_unlock(s->lock);
375         /* Choose a session ID */
376         memset(ss->session_id, 0, ss->session_id_length);
377         tmp = ss->session_id_length;
378         if (!cb(s, ss->session_id, &tmp)) {
379             /* The callback failed */
380             SSLerr(SSL_F_SSL_GET_NEW_SESSION,
381                    SSL_R_SSL_SESSION_ID_CALLBACK_FAILED);
382             SSL_SESSION_free(ss);
383             return (0);
384         }
385         /*
386          * Don't allow the callback to set the session length to zero. nor
387          * set it higher than it was.
388          */
389         if (tmp == 0 || tmp > ss->session_id_length) {
390             /* The callback set an illegal length */
391             SSLerr(SSL_F_SSL_GET_NEW_SESSION,
392                    SSL_R_SSL_SESSION_ID_HAS_BAD_LENGTH);
393             SSL_SESSION_free(ss);
394             return (0);
395         }
396         ss->session_id_length = tmp;
397         /* Finally, check for a conflict */
398         if (SSL_has_matching_session_id(s, ss->session_id,
399                                         ss->session_id_length)) {
400             SSLerr(SSL_F_SSL_GET_NEW_SESSION, SSL_R_SSL_SESSION_ID_CONFLICT);
401             SSL_SESSION_free(ss);
402             return (0);
403         }
404
405  sess_id_done:
406         if (s->tlsext_hostname) {
407             ss->tlsext_hostname = OPENSSL_strdup(s->tlsext_hostname);
408             if (ss->tlsext_hostname == NULL) {
409                 SSLerr(SSL_F_SSL_GET_NEW_SESSION, ERR_R_INTERNAL_ERROR);
410                 SSL_SESSION_free(ss);
411                 return 0;
412             }
413         }
414     } else {
415         ss->session_id_length = 0;
416     }
417
418     if (s->sid_ctx_length > sizeof(ss->sid_ctx)) {
419         SSLerr(SSL_F_SSL_GET_NEW_SESSION, ERR_R_INTERNAL_ERROR);
420         SSL_SESSION_free(ss);
421         return 0;
422     }
423     memcpy(ss->sid_ctx, s->sid_ctx, s->sid_ctx_length);
424     ss->sid_ctx_length = s->sid_ctx_length;
425     s->session = ss;
426     ss->ssl_version = s->version;
427     ss->verify_result = X509_V_OK;
428
429     /* If client supports extended master secret set it in session */
430     if (s->s3->flags & TLS1_FLAGS_RECEIVED_EXTMS)
431         ss->flags |= SSL_SESS_FLAG_EXTMS;
432
433     return (1);
434 }
435
436 /*-
437  * ssl_get_prev attempts to find an SSL_SESSION to be used to resume this
438  * connection. It is only called by servers.
439  *
440  *   ext: ClientHello extensions (including length prefix)
441  *   session_id: ClientHello session ID.
442  *
443  * Returns:
444  *   -1: error
445  *    0: a session may have been found.
446  *
447  * Side effects:
448  *   - If a session is found then s->session is pointed at it (after freeing an
449  *     existing session if need be) and s->verify_result is set from the session.
450  *   - Both for new and resumed sessions, s->tlsext_ticket_expected is set to 1
451  *     if the server should issue a new session ticket (to 0 otherwise).
452  */
453 int ssl_get_prev_session(SSL *s, const PACKET *ext, const PACKET *session_id)
454 {
455     /* This is used only by servers. */
456
457     SSL_SESSION *ret = NULL;
458     int fatal = 0;
459     int try_session_cache = 1;
460     int r;
461
462     if (PACKET_remaining(session_id) == 0)
463         try_session_cache = 0;
464
465     /* sets s->tlsext_ticket_expected and extended master secret flag */
466     r = tls_check_serverhello_tlsext_early(s, ext, session_id, &ret);
467     switch (r) {
468     case -1:                   /* Error during processing */
469         fatal = 1;
470         goto err;
471     case 0:                    /* No ticket found */
472     case 1:                    /* Zero length ticket found */
473         break;                  /* Ok to carry on processing session id. */
474     case 2:                    /* Ticket found but not decrypted. */
475     case 3:                    /* Ticket decrypted, *ret has been set. */
476         try_session_cache = 0;
477         break;
478     default:
479         abort();
480     }
481
482     if (try_session_cache &&
483         ret == NULL &&
484         !(s->session_ctx->session_cache_mode &
485           SSL_SESS_CACHE_NO_INTERNAL_LOOKUP)) {
486         SSL_SESSION data;
487         size_t local_len;
488         data.ssl_version = s->version;
489         memset(data.session_id, 0, sizeof(data.session_id));
490         if (!PACKET_copy_all(session_id, data.session_id,
491                              sizeof(data.session_id), &local_len)) {
492             goto err;
493         }
494         data.session_id_length = local_len;
495         CRYPTO_THREAD_read_lock(s->session_ctx->lock);
496         ret = lh_SSL_SESSION_retrieve(s->session_ctx->sessions, &data);
497         if (ret != NULL) {
498             /* don't allow other threads to steal it: */
499             SSL_SESSION_up_ref(ret);
500         }
501         CRYPTO_THREAD_unlock(s->session_ctx->lock);
502         if (ret == NULL)
503             s->session_ctx->stats.sess_miss++;
504     }
505
506     if (try_session_cache &&
507         ret == NULL && s->session_ctx->get_session_cb != NULL) {
508         int copy = 1;
509         ret = s->session_ctx->get_session_cb(s, PACKET_data(session_id),
510                                              PACKET_remaining(session_id),
511                                              &copy);
512
513         if (ret != NULL) {
514             s->session_ctx->stats.sess_cb_hit++;
515
516             /*
517              * Increment reference count now if the session callback asks us
518              * to do so (note that if the session structures returned by the
519              * callback are shared between threads, it must handle the
520              * reference count itself [i.e. copy == 0], or things won't be
521              * thread-safe).
522              */
523             if (copy)
524                 SSL_SESSION_up_ref(ret);
525
526             /*
527              * Add the externally cached session to the internal cache as
528              * well if and only if we are supposed to.
529              */
530             if (!
531                 (s->session_ctx->session_cache_mode &
532                  SSL_SESS_CACHE_NO_INTERNAL_STORE)) {
533                 /*
534                  * Either return value of SSL_CTX_add_session should not
535                  * interrupt the session resumption process. The return
536                  * value is intentionally ignored.
537                  */
538                 SSL_CTX_add_session(s->session_ctx, ret);
539             }
540         }
541     }
542
543     if (ret == NULL)
544         goto err;
545
546     /* Now ret is non-NULL and we own one of its reference counts. */
547
548     if (ret->sid_ctx_length != s->sid_ctx_length
549         || memcmp(ret->sid_ctx, s->sid_ctx, ret->sid_ctx_length)) {
550         /*
551          * We have the session requested by the client, but we don't want to
552          * use it in this context.
553          */
554         goto err;               /* treat like cache miss */
555     }
556
557     if ((s->verify_mode & SSL_VERIFY_PEER) && s->sid_ctx_length == 0) {
558         /*
559          * We can't be sure if this session is being used out of context,
560          * which is especially important for SSL_VERIFY_PEER. The application
561          * should have used SSL[_CTX]_set_session_id_context. For this error
562          * case, we generate an error instead of treating the event like a
563          * cache miss (otherwise it would be easy for applications to
564          * effectively disable the session cache by accident without anyone
565          * noticing).
566          */
567
568         SSLerr(SSL_F_SSL_GET_PREV_SESSION,
569                SSL_R_SESSION_ID_CONTEXT_UNINITIALIZED);
570         fatal = 1;
571         goto err;
572     }
573
574     if (ret->cipher == NULL) {
575         unsigned char buf[5], *p;
576         unsigned long l;
577
578         p = buf;
579         l = ret->cipher_id;
580         l2n(l, p);
581         if ((ret->ssl_version >> 8) >= SSL3_VERSION_MAJOR)
582             ret->cipher = ssl_get_cipher_by_char(s, &(buf[2]));
583         else
584             ret->cipher = ssl_get_cipher_by_char(s, &(buf[1]));
585         if (ret->cipher == NULL)
586             goto err;
587     }
588
589     if (ret->timeout < (long)(time(NULL) - ret->time)) { /* timeout */
590         s->session_ctx->stats.sess_timeout++;
591         if (try_session_cache) {
592             /* session was from the cache, so remove it */
593             SSL_CTX_remove_session(s->session_ctx, ret);
594         }
595         goto err;
596     }
597
598     /* Check extended master secret extension consistency */
599     if (ret->flags & SSL_SESS_FLAG_EXTMS) {
600         /* If old session includes extms, but new does not: abort handshake */
601         if (!(s->s3->flags & TLS1_FLAGS_RECEIVED_EXTMS)) {
602             SSLerr(SSL_F_SSL_GET_PREV_SESSION, SSL_R_INCONSISTENT_EXTMS);
603             ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
604             fatal = 1;
605             goto err;
606         }
607     } else if (s->s3->flags & TLS1_FLAGS_RECEIVED_EXTMS) {
608         /* If new session includes extms, but old does not: do not resume */
609         goto err;
610     }
611
612     s->session_ctx->stats.sess_hit++;
613
614     SSL_SESSION_free(s->session);
615     s->session = ret;
616     s->verify_result = s->session->verify_result;
617     return 1;
618
619  err:
620     if (ret != NULL) {
621         SSL_SESSION_free(ret);
622
623         if (!try_session_cache) {
624             /*
625              * The session was from a ticket, so we should issue a ticket for
626              * the new session
627              */
628             s->tlsext_ticket_expected = 1;
629         }
630     }
631     if (fatal)
632         return -1;
633     else
634         return 0;
635 }
636
637 int SSL_CTX_add_session(SSL_CTX *ctx, SSL_SESSION *c)
638 {
639     int ret = 0;
640     SSL_SESSION *s;
641
642     /*
643      * add just 1 reference count for the SSL_CTX's session cache even though
644      * it has two ways of access: each session is in a doubly linked list and
645      * an lhash
646      */
647     SSL_SESSION_up_ref(c);
648     /*
649      * if session c is in already in cache, we take back the increment later
650      */
651
652     CRYPTO_THREAD_write_lock(ctx->lock);
653     s = lh_SSL_SESSION_insert(ctx->sessions, c);
654
655     /*
656      * s != NULL iff we already had a session with the given PID. In this
657      * case, s == c should hold (then we did not really modify
658      * ctx->sessions), or we're in trouble.
659      */
660     if (s != NULL && s != c) {
661         /* We *are* in trouble ... */
662         SSL_SESSION_list_remove(ctx, s);
663         SSL_SESSION_free(s);
664         /*
665          * ... so pretend the other session did not exist in cache (we cannot
666          * handle two SSL_SESSION structures with identical session ID in the
667          * same cache, which could happen e.g. when two threads concurrently
668          * obtain the same session from an external cache)
669          */
670         s = NULL;
671     } else if (s == NULL &&
672                lh_SSL_SESSION_retrieve(ctx->sessions, c) == NULL) {
673         /* s == NULL can also mean OOM error in lh_SSL_SESSION_insert ... */
674
675         /*
676          * ... so take back the extra reference and also don't add
677          * the session to the SSL_SESSION_list at this time
678          */
679         s = c;
680     }
681
682     /* Put at the head of the queue unless it is already in the cache */
683     if (s == NULL)
684         SSL_SESSION_list_add(ctx, c);
685
686     if (s != NULL) {
687         /*
688          * existing cache entry -- decrement previously incremented reference
689          * count because it already takes into account the cache
690          */
691
692         SSL_SESSION_free(s);    /* s == c */
693         ret = 0;
694     } else {
695         /*
696          * new cache entry -- remove old ones if cache has become too large
697          */
698
699         ret = 1;
700
701         if (SSL_CTX_sess_get_cache_size(ctx) > 0) {
702             while (SSL_CTX_sess_number(ctx) > SSL_CTX_sess_get_cache_size(ctx)) {
703                 if (!remove_session_lock(ctx, ctx->session_cache_tail, 0))
704                     break;
705                 else
706                     ctx->stats.sess_cache_full++;
707             }
708         }
709     }
710     CRYPTO_THREAD_unlock(ctx->lock);
711     return ret;
712 }
713
714 int SSL_CTX_remove_session(SSL_CTX *ctx, SSL_SESSION *c)
715 {
716     return remove_session_lock(ctx, c, 1);
717 }
718
719 static int remove_session_lock(SSL_CTX *ctx, SSL_SESSION *c, int lck)
720 {
721     SSL_SESSION *r;
722     int ret = 0;
723
724     if ((c != NULL) && (c->session_id_length != 0)) {
725         if (lck)
726             CRYPTO_THREAD_write_lock(ctx->lock);
727         if ((r = lh_SSL_SESSION_retrieve(ctx->sessions, c)) == c) {
728             ret = 1;
729             r = lh_SSL_SESSION_delete(ctx->sessions, c);
730             SSL_SESSION_list_remove(ctx, c);
731         }
732         c->not_resumable = 1;
733
734         if (lck)
735             CRYPTO_THREAD_unlock(ctx->lock);
736
737         if (ctx->remove_session_cb != NULL)
738             ctx->remove_session_cb(ctx, c);
739
740         if (ret)
741             SSL_SESSION_free(r);
742     } else
743         ret = 0;
744     return (ret);
745 }
746
747 void SSL_SESSION_free(SSL_SESSION *ss)
748 {
749     int i;
750
751     if (ss == NULL)
752         return;
753
754     CRYPTO_atomic_add(&ss->references, -1, &i, ss->lock);
755     REF_PRINT_COUNT("SSL_SESSION", ss);
756     if (i > 0)
757         return;
758     REF_ASSERT_ISNT(i < 0);
759
760     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL_SESSION, ss, &ss->ex_data);
761
762     OPENSSL_cleanse(ss->master_key, sizeof(ss->master_key));
763     OPENSSL_cleanse(ss->session_id, sizeof(ss->session_id));
764     X509_free(ss->peer);
765     sk_X509_pop_free(ss->peer_chain, X509_free);
766     sk_SSL_CIPHER_free(ss->ciphers);
767     OPENSSL_free(ss->tlsext_hostname);
768     OPENSSL_free(ss->tlsext_tick);
769 #ifndef OPENSSL_NO_EC
770     ss->tlsext_ecpointformatlist_length = 0;
771     OPENSSL_free(ss->tlsext_ecpointformatlist);
772     ss->tlsext_ellipticcurvelist_length = 0;
773     OPENSSL_free(ss->tlsext_ellipticcurvelist);
774 #endif                          /* OPENSSL_NO_EC */
775 #ifndef OPENSSL_NO_PSK
776     OPENSSL_free(ss->psk_identity_hint);
777     OPENSSL_free(ss->psk_identity);
778 #endif
779 #ifndef OPENSSL_NO_SRP
780     OPENSSL_free(ss->srp_username);
781 #endif
782     CRYPTO_THREAD_lock_free(ss->lock);
783     OPENSSL_clear_free(ss, sizeof(*ss));
784 }
785
786 int SSL_SESSION_up_ref(SSL_SESSION *ss)
787 {
788     int i;
789
790     if (CRYPTO_atomic_add(&ss->references, 1, &i, ss->lock) <= 0)
791         return 0;
792
793     REF_PRINT_COUNT("SSL_SESSION", ss);
794     REF_ASSERT_ISNT(i < 2);
795     return ((i > 1) ? 1 : 0);
796 }
797
798 int SSL_set_session(SSL *s, SSL_SESSION *session)
799 {
800     ssl_clear_bad_session(s);
801     if (s->ctx->method != s->method) {
802         if (!SSL_set_ssl_method(s, s->ctx->method))
803             return 0;
804     }
805
806     if (session != NULL) {
807         SSL_SESSION_up_ref(session);
808         s->verify_result = session->verify_result;
809     }
810     SSL_SESSION_free(s->session);
811     s->session = session;
812
813     return 1;
814 }
815
816 int SSL_SESSION_set1_id(SSL_SESSION *s, const unsigned char *sid,
817                         unsigned int sid_len)
818 {
819     if (sid_len > SSL_MAX_SSL_SESSION_ID_LENGTH) {
820       SSLerr(SSL_F_SSL_SESSION_SET1_ID,
821              SSL_R_SSL_SESSION_ID_TOO_LONG);
822       return 0;
823     }
824     s->session_id_length = sid_len;
825     if (sid != s->session_id)
826         memcpy(s->session_id, sid, sid_len);
827     return 1;
828 }
829
830 long SSL_SESSION_set_timeout(SSL_SESSION *s, long t)
831 {
832     if (s == NULL)
833         return (0);
834     s->timeout = t;
835     return (1);
836 }
837
838 long SSL_SESSION_get_timeout(const SSL_SESSION *s)
839 {
840     if (s == NULL)
841         return (0);
842     return (s->timeout);
843 }
844
845 long SSL_SESSION_get_time(const SSL_SESSION *s)
846 {
847     if (s == NULL)
848         return (0);
849     return (s->time);
850 }
851
852 long SSL_SESSION_set_time(SSL_SESSION *s, long t)
853 {
854     if (s == NULL)
855         return (0);
856     s->time = t;
857     return (t);
858 }
859
860 int SSL_SESSION_get_protocol_version(const SSL_SESSION *s)
861 {
862     return s->ssl_version;
863 }
864
865 const SSL_CIPHER *SSL_SESSION_get0_cipher(const SSL_SESSION *s)
866 {
867     return s->cipher;
868 }
869
870 const char *SSL_SESSION_get0_hostname(const SSL_SESSION *s)
871 {
872     return s->tlsext_hostname;
873 }
874
875 int SSL_SESSION_has_ticket(const SSL_SESSION *s)
876 {
877     return (s->tlsext_ticklen > 0) ? 1 : 0;
878 }
879
880 unsigned long SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
881 {
882     return s->tlsext_tick_lifetime_hint;
883 }
884
885 void SSL_SESSION_get0_ticket(const SSL_SESSION *s, const unsigned char **tick,
886                              size_t *len)
887 {
888     *len = s->tlsext_ticklen;
889     if (tick != NULL)
890         *tick = s->tlsext_tick;
891 }
892
893 X509 *SSL_SESSION_get0_peer(SSL_SESSION *s)
894 {
895     return s->peer;
896 }
897
898 int SSL_SESSION_set1_id_context(SSL_SESSION *s, const unsigned char *sid_ctx,
899                                 unsigned int sid_ctx_len)
900 {
901     if (sid_ctx_len > SSL_MAX_SID_CTX_LENGTH) {
902         SSLerr(SSL_F_SSL_SESSION_SET1_ID_CONTEXT,
903                SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
904         return 0;
905     }
906     s->sid_ctx_length = sid_ctx_len;
907     if (sid_ctx != s->sid_ctx)
908         memcpy(s->sid_ctx, sid_ctx, sid_ctx_len);
909
910     return 1;
911 }
912
913 long SSL_CTX_set_timeout(SSL_CTX *s, long t)
914 {
915     long l;
916     if (s == NULL)
917         return (0);
918     l = s->session_timeout;
919     s->session_timeout = t;
920     return (l);
921 }
922
923 long SSL_CTX_get_timeout(const SSL_CTX *s)
924 {
925     if (s == NULL)
926         return (0);
927     return (s->session_timeout);
928 }
929
930 int SSL_set_session_secret_cb(SSL *s,
931                               int (*tls_session_secret_cb) (SSL *s,
932                                                             void *secret,
933                                                             int *secret_len,
934                                                             STACK_OF(SSL_CIPHER)
935                                                             *peer_ciphers,
936                                                             const SSL_CIPHER
937                                                             **cipher,
938                                                             void *arg),
939                               void *arg)
940 {
941     if (s == NULL)
942         return (0);
943     s->tls_session_secret_cb = tls_session_secret_cb;
944     s->tls_session_secret_cb_arg = arg;
945     return (1);
946 }
947
948 int SSL_set_session_ticket_ext_cb(SSL *s, tls_session_ticket_ext_cb_fn cb,
949                                   void *arg)
950 {
951     if (s == NULL)
952         return (0);
953     s->tls_session_ticket_ext_cb = cb;
954     s->tls_session_ticket_ext_cb_arg = arg;
955     return (1);
956 }
957
958 int SSL_set_session_ticket_ext(SSL *s, void *ext_data, int ext_len)
959 {
960     if (s->version >= TLS1_VERSION) {
961         OPENSSL_free(s->tlsext_session_ticket);
962         s->tlsext_session_ticket = NULL;
963         s->tlsext_session_ticket =
964             OPENSSL_malloc(sizeof(TLS_SESSION_TICKET_EXT) + ext_len);
965         if (s->tlsext_session_ticket == NULL) {
966             SSLerr(SSL_F_SSL_SET_SESSION_TICKET_EXT, ERR_R_MALLOC_FAILURE);
967             return 0;
968         }
969
970         if (ext_data) {
971             s->tlsext_session_ticket->length = ext_len;
972             s->tlsext_session_ticket->data = s->tlsext_session_ticket + 1;
973             memcpy(s->tlsext_session_ticket->data, ext_data, ext_len);
974         } else {
975             s->tlsext_session_ticket->length = 0;
976             s->tlsext_session_ticket->data = NULL;
977         }
978
979         return 1;
980     }
981
982     return 0;
983 }
984
985 typedef struct timeout_param_st {
986     SSL_CTX *ctx;
987     long time;
988     LHASH_OF(SSL_SESSION) *cache;
989 } TIMEOUT_PARAM;
990
991 static void timeout_cb(SSL_SESSION *s, TIMEOUT_PARAM *p)
992 {
993     if ((p->time == 0) || (p->time > (s->time + s->timeout))) { /* timeout */
994         /*
995          * The reason we don't call SSL_CTX_remove_session() is to save on
996          * locking overhead
997          */
998         (void)lh_SSL_SESSION_delete(p->cache, s);
999         SSL_SESSION_list_remove(p->ctx, s);
1000         s->not_resumable = 1;
1001         if (p->ctx->remove_session_cb != NULL)
1002             p->ctx->remove_session_cb(p->ctx, s);
1003         SSL_SESSION_free(s);
1004     }
1005 }
1006
1007 IMPLEMENT_LHASH_DOALL_ARG(SSL_SESSION, TIMEOUT_PARAM);
1008
1009 void SSL_CTX_flush_sessions(SSL_CTX *s, long t)
1010 {
1011     unsigned long i;
1012     TIMEOUT_PARAM tp;
1013
1014     tp.ctx = s;
1015     tp.cache = s->sessions;
1016     if (tp.cache == NULL)
1017         return;
1018     tp.time = t;
1019     CRYPTO_THREAD_write_lock(s->lock);
1020     i = lh_SSL_SESSION_get_down_load(s->sessions);
1021     lh_SSL_SESSION_set_down_load(s->sessions, 0);
1022     lh_SSL_SESSION_doall_TIMEOUT_PARAM(tp.cache, timeout_cb, &tp);
1023     lh_SSL_SESSION_set_down_load(s->sessions, i);
1024     CRYPTO_THREAD_unlock(s->lock);
1025 }
1026
1027 int ssl_clear_bad_session(SSL *s)
1028 {
1029     if ((s->session != NULL) &&
1030         !(s->shutdown & SSL_SENT_SHUTDOWN) &&
1031         !(SSL_in_init(s) || SSL_in_before(s))) {
1032         SSL_CTX_remove_session(s->session_ctx, s->session);
1033         return (1);
1034     } else
1035         return (0);
1036 }
1037
1038 /* locked by SSL_CTX in the calling function */
1039 static void SSL_SESSION_list_remove(SSL_CTX *ctx, SSL_SESSION *s)
1040 {
1041     if ((s->next == NULL) || (s->prev == NULL))
1042         return;
1043
1044     if (s->next == (SSL_SESSION *)&(ctx->session_cache_tail)) {
1045         /* last element in list */
1046         if (s->prev == (SSL_SESSION *)&(ctx->session_cache_head)) {
1047             /* only one element in list */
1048             ctx->session_cache_head = NULL;
1049             ctx->session_cache_tail = NULL;
1050         } else {
1051             ctx->session_cache_tail = s->prev;
1052             s->prev->next = (SSL_SESSION *)&(ctx->session_cache_tail);
1053         }
1054     } else {
1055         if (s->prev == (SSL_SESSION *)&(ctx->session_cache_head)) {
1056             /* first element in list */
1057             ctx->session_cache_head = s->next;
1058             s->next->prev = (SSL_SESSION *)&(ctx->session_cache_head);
1059         } else {
1060             /* middle of list */
1061             s->next->prev = s->prev;
1062             s->prev->next = s->next;
1063         }
1064     }
1065     s->prev = s->next = NULL;
1066 }
1067
1068 static void SSL_SESSION_list_add(SSL_CTX *ctx, SSL_SESSION *s)
1069 {
1070     if ((s->next != NULL) && (s->prev != NULL))
1071         SSL_SESSION_list_remove(ctx, s);
1072
1073     if (ctx->session_cache_head == NULL) {
1074         ctx->session_cache_head = s;
1075         ctx->session_cache_tail = s;
1076         s->prev = (SSL_SESSION *)&(ctx->session_cache_head);
1077         s->next = (SSL_SESSION *)&(ctx->session_cache_tail);
1078     } else {
1079         s->next = ctx->session_cache_head;
1080         s->next->prev = s;
1081         s->prev = (SSL_SESSION *)&(ctx->session_cache_head);
1082         ctx->session_cache_head = s;
1083     }
1084 }
1085
1086 void SSL_CTX_sess_set_new_cb(SSL_CTX *ctx,
1087                              int (*cb) (struct ssl_st *ssl, SSL_SESSION *sess))
1088 {
1089     ctx->new_session_cb = cb;
1090 }
1091
1092 int (*SSL_CTX_sess_get_new_cb(SSL_CTX *ctx)) (SSL *ssl, SSL_SESSION *sess) {
1093     return ctx->new_session_cb;
1094 }
1095
1096 void SSL_CTX_sess_set_remove_cb(SSL_CTX *ctx,
1097                                 void (*cb) (SSL_CTX *ctx, SSL_SESSION *sess))
1098 {
1099     ctx->remove_session_cb = cb;
1100 }
1101
1102 void (*SSL_CTX_sess_get_remove_cb(SSL_CTX *ctx)) (SSL_CTX *ctx,
1103                                                   SSL_SESSION *sess) {
1104     return ctx->remove_session_cb;
1105 }
1106
1107 void SSL_CTX_sess_set_get_cb(SSL_CTX *ctx,
1108                              SSL_SESSION *(*cb) (struct ssl_st *ssl,
1109                                                  const unsigned char *data,
1110                                                  int len, int *copy))
1111 {
1112     ctx->get_session_cb = cb;
1113 }
1114
1115 SSL_SESSION *(*SSL_CTX_sess_get_get_cb(SSL_CTX *ctx)) (SSL *ssl,
1116                                                        const unsigned char
1117                                                        *data, int len,
1118                                                        int *copy) {
1119     return ctx->get_session_cb;
1120 }
1121
1122 void SSL_CTX_set_info_callback(SSL_CTX *ctx,
1123                                void (*cb) (const SSL *ssl, int type, int val))
1124 {
1125     ctx->info_callback = cb;
1126 }
1127
1128 void (*SSL_CTX_get_info_callback(SSL_CTX *ctx)) (const SSL *ssl, int type,
1129                                                  int val) {
1130     return ctx->info_callback;
1131 }
1132
1133 void SSL_CTX_set_client_cert_cb(SSL_CTX *ctx,
1134                                 int (*cb) (SSL *ssl, X509 **x509,
1135                                            EVP_PKEY **pkey))
1136 {
1137     ctx->client_cert_cb = cb;
1138 }
1139
1140 int (*SSL_CTX_get_client_cert_cb(SSL_CTX *ctx)) (SSL *ssl, X509 **x509,
1141                                                  EVP_PKEY **pkey) {
1142     return ctx->client_cert_cb;
1143 }
1144
1145 #ifndef OPENSSL_NO_ENGINE
1146 int SSL_CTX_set_client_cert_engine(SSL_CTX *ctx, ENGINE *e)
1147 {
1148     if (!ENGINE_init(e)) {
1149         SSLerr(SSL_F_SSL_CTX_SET_CLIENT_CERT_ENGINE, ERR_R_ENGINE_LIB);
1150         return 0;
1151     }
1152     if (!ENGINE_get_ssl_client_cert_function(e)) {
1153         SSLerr(SSL_F_SSL_CTX_SET_CLIENT_CERT_ENGINE,
1154                SSL_R_NO_CLIENT_CERT_METHOD);
1155         ENGINE_finish(e);
1156         return 0;
1157     }
1158     ctx->client_cert_engine = e;
1159     return 1;
1160 }
1161 #endif
1162
1163 void SSL_CTX_set_cookie_generate_cb(SSL_CTX *ctx,
1164                                     int (*cb) (SSL *ssl,
1165                                                unsigned char *cookie,
1166                                                unsigned int *cookie_len))
1167 {
1168     ctx->app_gen_cookie_cb = cb;
1169 }
1170
1171 void SSL_CTX_set_cookie_verify_cb(SSL_CTX *ctx,
1172                                   int (*cb) (SSL *ssl,
1173                                              const unsigned char *cookie,
1174                                              unsigned int cookie_len))
1175 {
1176     ctx->app_verify_cookie_cb = cb;
1177 }
1178
1179 IMPLEMENT_PEM_rw(SSL_SESSION, SSL_SESSION, PEM_STRING_SSL_SESSION, SSL_SESSION)