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