Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / third_party / boringssl / src / ssl / ssl_sess.c
1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young (eay@cryptsoft.com).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young (eay@cryptsoft.com)"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.]
56  */
57 /* ====================================================================
58  * Copyright (c) 1998-2006 The OpenSSL Project.  All rights reserved.
59  *
60  * Redistribution and use in source and binary forms, with or without
61  * modification, are permitted provided that the following conditions
62  * are met:
63  *
64  * 1. Redistributions of source code must retain the above copyright
65  *    notice, this list of conditions and the following disclaimer.
66  *
67  * 2. Redistributions in binary form must reproduce the above copyright
68  *    notice, this list of conditions and the following disclaimer in
69  *    the documentation and/or other materials provided with the
70  *    distribution.
71  *
72  * 3. All advertising materials mentioning features or use of this
73  *    software must display the following acknowledgment:
74  *    "This product includes software developed by the OpenSSL Project
75  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
76  *
77  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78  *    endorse or promote products derived from this software without
79  *    prior written permission. For written permission, please contact
80  *    openssl-core@openssl.org.
81  *
82  * 5. Products derived from this software may not be called "OpenSSL"
83  *    nor may "OpenSSL" appear in their names without prior written
84  *    permission of the OpenSSL Project.
85  *
86  * 6. Redistributions of any form whatsoever must retain the following
87  *    acknowledgment:
88  *    "This product includes software developed by the OpenSSL Project
89  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
90  *
91  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
95  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102  * OF THE POSSIBILITY OF SUCH DAMAGE.
103  * ====================================================================
104  *
105  * This product includes cryptographic software written by Eric Young
106  * (eay@cryptsoft.com).  This product includes software written by Tim
107  * Hudson (tjh@cryptsoft.com).
108  *
109  */
110 /* ====================================================================
111  * Copyright 2005 Nokia. All rights reserved.
112  *
113  * The portions of the attached software ("Contribution") is developed by
114  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
115  * license.
116  *
117  * The Contribution, originally written by Mika Kousa and Pasi Eronen of
118  * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
119  * support (see RFC 4279) to OpenSSL.
120  *
121  * No patent licenses or other rights except those expressly stated in
122  * the OpenSSL open source license shall be deemed granted or received
123  * expressly, by implication, estoppel, or otherwise.
124  *
125  * No assurances are provided by Nokia that the Contribution does not
126  * infringe the patent or other intellectual property rights of any third
127  * party or that the license provides you with all the necessary rights
128  * to make use of the Contribution.
129  *
130  * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
131  * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
132  * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
133  * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
134  * OTHERWISE. */
135
136 #include <stdio.h>
137
138 #include <openssl/engine.h>
139 #include <openssl/err.h>
140 #include <openssl/lhash.h>
141 #include <openssl/mem.h>
142 #include <openssl/rand.h>
143
144 #include "ssl_locl.h"
145
146 /* The address of this is a magic value, a pointer to which is returned by
147  * SSL_magic_pending_session_ptr(). It allows a session callback to indicate
148  * that it needs to asynchronously fetch session information. */
149 static char g_pending_session_magic;
150
151 static void SSL_SESSION_list_remove(SSL_CTX *ctx, SSL_SESSION *s);
152 static void SSL_SESSION_list_add(SSL_CTX *ctx,SSL_SESSION *s);
153 static int remove_session_lock(SSL_CTX *ctx, SSL_SESSION *c, int lck);
154
155 SSL_SESSION *SSL_magic_pending_session_ptr()
156         {
157         return (SSL_SESSION*) &g_pending_session_magic;
158         }
159
160 SSL_SESSION *SSL_get_session(const SSL *ssl)
161 /* aka SSL_get0_session; gets 0 objects, just returns a copy of the pointer */
162         {
163         return(ssl->session);
164         }
165
166 SSL_SESSION *SSL_get1_session(SSL *ssl)
167 /* variant of SSL_get_session: caller really gets something */
168         {
169         SSL_SESSION *sess;
170         /* Need to lock this all up rather than just use CRYPTO_add so that
171          * somebody doesn't free ssl->session between when we check it's
172          * non-null and when we up the reference count. */
173         CRYPTO_w_lock(CRYPTO_LOCK_SSL_SESSION);
174         sess = ssl->session;
175         if(sess)
176                 sess->references++;
177         CRYPTO_w_unlock(CRYPTO_LOCK_SSL_SESSION);
178         return(sess);
179         }
180
181 int SSL_SESSION_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func,
182              CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func)
183         {
184         return CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL_SESSION, argl, argp,
185                         new_func, dup_func, free_func);
186         }
187
188 int SSL_SESSION_set_ex_data(SSL_SESSION *s, int idx, void *arg)
189         {
190         return(CRYPTO_set_ex_data(&s->ex_data,idx,arg));
191         }
192
193 void *SSL_SESSION_get_ex_data(const SSL_SESSION *s, int idx)
194         {
195         return(CRYPTO_get_ex_data(&s->ex_data,idx));
196         }
197
198 SSL_SESSION *SSL_SESSION_new(void)
199         {
200         SSL_SESSION *ss;
201
202         ss=(SSL_SESSION *)OPENSSL_malloc(sizeof(SSL_SESSION));
203         if (ss == NULL)
204                 {
205                 OPENSSL_PUT_ERROR(SSL, SSL_SESSION_new, ERR_R_MALLOC_FAILURE);
206                 return(0);
207                 }
208         memset(ss,0,sizeof(SSL_SESSION));
209
210         ss->verify_result = 1; /* avoid 0 (= X509_V_OK) just in case */
211         ss->references=1;
212         ss->timeout=60*5+4; /* 5 minute timeout by default */
213         ss->time=(unsigned long)time(NULL);
214         ss->prev=NULL;
215         ss->next=NULL;
216         ss->tlsext_hostname = NULL; 
217 #ifndef OPENSSL_NO_EC
218         ss->tlsext_ecpointformatlist_length = 0;
219         ss->tlsext_ecpointformatlist = NULL;
220         ss->tlsext_ellipticcurvelist_length = 0;
221         ss->tlsext_ellipticcurvelist = NULL;
222 #endif
223         CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL_SESSION, ss, &ss->ex_data);
224         ss->psk_identity_hint=NULL;
225         ss->psk_identity=NULL;
226         return(ss);
227         }
228
229 const unsigned char *SSL_SESSION_get_id(const SSL_SESSION *s, unsigned int *len)
230         {
231         if(len)
232                 *len = s->session_id_length;
233         return s->session_id;
234         }
235
236 /* Even with SSLv2, we have 16 bytes (128 bits) of session ID space. SSLv3/TLSv1
237  * has 32 bytes (256 bits). As such, filling the ID with random gunk repeatedly
238  * until we have no conflict is going to complete in one iteration pretty much
239  * "most" of the time (btw: understatement). So, if it takes us 10 iterations
240  * and we still can't avoid a conflict - well that's a reasonable point to call
241  * it quits. Either the RAND code is broken or someone is trying to open roughly
242  * very close to 2^128 (or 2^256) SSL sessions to our server. How you might
243  * store that many sessions is perhaps a more interesting question ... */
244
245 #define MAX_SESS_ID_ATTEMPTS 10
246 static int def_generate_session_id(const SSL *ssl, unsigned char *id,
247                                 unsigned int *id_len)
248 {
249         unsigned int retry = 0;
250         do
251                 if (RAND_pseudo_bytes(id, *id_len) <= 0)
252                         return 0;
253         while(SSL_has_matching_session_id(ssl, id, *id_len) &&
254                 (++retry < MAX_SESS_ID_ATTEMPTS));
255         if(retry < MAX_SESS_ID_ATTEMPTS)
256                 return 1;
257         /* else - woops a session_id match */
258         /* XXX We should also check the external cache --
259          * but the probability of a collision is negligible, and
260          * we could not prevent the concurrent creation of sessions
261          * with identical IDs since we currently don't have means
262          * to atomically check whether a session ID already exists
263          * and make a reservation for it if it does not
264          * (this problem applies to the internal cache as well).
265          */
266         return 0;
267 }
268
269 int ssl_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                 {
287                 SSL_SESSION_free(s->session);
288                 s->session=NULL;
289                 }
290
291         if (session)
292                 {
293                 if (s->version == SSL2_VERSION)
294                         {
295                         ss->ssl_version=SSL2_VERSION;
296                         ss->session_id_length=SSL2_SSL_SESSION_ID_LENGTH;
297                         }
298                 else if (s->version == SSL3_VERSION)
299                         {
300                         ss->ssl_version=SSL3_VERSION;
301                         ss->session_id_length=SSL3_SSL_SESSION_ID_LENGTH;
302                         }
303                 else if (s->version == TLS1_VERSION)
304                         {
305                         ss->ssl_version=TLS1_VERSION;
306                         ss->session_id_length=SSL3_SSL_SESSION_ID_LENGTH;
307                         }
308                 else if (s->version == TLS1_1_VERSION)
309                         {
310                         ss->ssl_version=TLS1_1_VERSION;
311                         ss->session_id_length=SSL3_SSL_SESSION_ID_LENGTH;
312                         }
313                 else if (s->version == TLS1_2_VERSION)
314                         {
315                         ss->ssl_version=TLS1_2_VERSION;
316                         ss->session_id_length=SSL3_SSL_SESSION_ID_LENGTH;
317                         }
318                 else if (s->version == DTLS1_BAD_VER)
319                         {
320                         ss->ssl_version=DTLS1_BAD_VER;
321                         ss->session_id_length=SSL3_SSL_SESSION_ID_LENGTH;
322                         }
323                 else if (s->version == DTLS1_VERSION)
324                         {
325                         ss->ssl_version=DTLS1_VERSION;
326                         ss->session_id_length=SSL3_SSL_SESSION_ID_LENGTH;
327                         }
328                 else if (s->version == DTLS1_2_VERSION)
329                         {
330                         ss->ssl_version=DTLS1_2_VERSION;
331                         ss->session_id_length=SSL3_SSL_SESSION_ID_LENGTH;
332                         }
333                 else
334                         {
335                         OPENSSL_PUT_ERROR(SSL, ssl_get_new_session, SSL_R_UNSUPPORTED_SSL_VERSION);
336                         SSL_SESSION_free(ss);
337                         return(0);
338                         }
339                 /* If RFC4507 ticket use empty session ID */
340                 if (s->tlsext_ticket_expected)
341                         {
342                         ss->session_id_length = 0;
343                         goto sess_id_done;
344                         }
345                 /* Choose which callback will set the session ID */
346                 CRYPTO_r_lock(CRYPTO_LOCK_SSL_CTX);
347                 if(s->generate_session_id)
348                         cb = s->generate_session_id;
349                 else if(s->session_ctx->generate_session_id)
350                         cb = s->session_ctx->generate_session_id;
351                 CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX);
352                 /* Choose a session ID */
353                 tmp = ss->session_id_length;
354                 if(!cb(s, ss->session_id, &tmp))
355                         {
356                         /* The callback failed */
357                         OPENSSL_PUT_ERROR(SSL, ssl_get_new_session, SSL_R_SSL_SESSION_ID_CALLBACK_FAILED);
358                         SSL_SESSION_free(ss);
359                         return(0);
360                         }
361                 /* Don't allow the callback to set the session length to zero.
362                  * nor set it higher than it was. */
363                 if(!tmp || (tmp > ss->session_id_length))
364                         {
365                         /* The callback set an illegal length */
366                         OPENSSL_PUT_ERROR(SSL, ssl_get_new_session, SSL_R_SSL_SESSION_ID_HAS_BAD_LENGTH);
367                         SSL_SESSION_free(ss);
368                         return(0);
369                         }
370                 /* If the session length was shrunk and we're SSLv2, pad it */
371                 if((tmp < ss->session_id_length) && (s->version == SSL2_VERSION))
372                         memset(ss->session_id + tmp, 0, ss->session_id_length - tmp);
373                 else
374                         ss->session_id_length = tmp;
375                 /* Finally, check for a conflict */
376                 if(SSL_has_matching_session_id(s, ss->session_id,
377                                                 ss->session_id_length))
378                         {
379                         OPENSSL_PUT_ERROR(SSL, ssl_get_new_session, SSL_R_SSL_SESSION_ID_CONFLICT);
380                         SSL_SESSION_free(ss);
381                         return(0);
382                         }
383                 sess_id_done:
384                 if (s->tlsext_hostname) {
385                         ss->tlsext_hostname = BUF_strdup(s->tlsext_hostname);
386                         if (ss->tlsext_hostname == NULL) {
387                                 OPENSSL_PUT_ERROR(SSL, ssl_get_new_session, ERR_R_INTERNAL_ERROR);
388                                 SSL_SESSION_free(ss);
389                                 return 0;
390                                 }
391                         }
392                 if (s->psk_identity_hint)
393                         {
394                         ss->psk_identity_hint = BUF_strdup(s->psk_identity_hint);
395                         if (ss->psk_identity_hint == NULL)
396                                 {
397                                 OPENSSL_PUT_ERROR(SSL, ssl_get_new_session, ERR_R_MALLOC_FAILURE);
398                                 SSL_SESSION_free(ss);
399                                 return 0;
400                                 }
401                         }
402                 }
403         else
404                 {
405                 ss->session_id_length=0;
406                 }
407
408         if (s->sid_ctx_length > sizeof ss->sid_ctx)
409                 {
410                 OPENSSL_PUT_ERROR(SSL, ssl_get_new_session, ERR_R_INTERNAL_ERROR);
411                 SSL_SESSION_free(ss);
412                 return 0;
413                 }
414         memcpy(ss->sid_ctx,s->sid_ctx,s->sid_ctx_length);
415         ss->sid_ctx_length=s->sid_ctx_length;
416         s->session=ss;
417         ss->ssl_version=s->version;
418         ss->verify_result = X509_V_OK;
419
420         return(1);
421         }
422
423 /* ssl_get_prev attempts to find an SSL_SESSION to be used to resume this
424  * connection. It is only called by servers.
425  *
426  *   ctx: contains the early callback context, which is the result of a
427  *       shallow parse of the ClientHello.
428  *
429  * Returns:
430  *   -1: error
431  *    0: a session may have been found.
432  *
433  * Side effects:
434  *   - If a session is found then s->session is pointed at it (after freeing an
435  *     existing session if need be) and s->verify_result is set from the session.
436  *   - Both for new and resumed sessions, s->tlsext_ticket_expected is set to 1
437  *     if the server should issue a new session ticket (to 0 otherwise).
438  */
439 int ssl_get_prev_session(SSL *s, const struct ssl_early_callback_ctx *ctx)
440         {
441         /* This is used only by servers. */
442
443         SSL_SESSION *ret=NULL;
444         int fatal = 0;
445         int try_session_cache = 1;
446         int r;
447
448         if (ctx->session_id_len > SSL_MAX_SSL_SESSION_ID_LENGTH)
449                 goto err;
450
451         if (ctx->session_id_len == 0)
452                 try_session_cache = 0;
453
454         r = tls1_process_ticket(s, ctx, &ret); /* sets s->tlsext_ticket_expected */
455         switch (r)
456                 {
457         case -1: /* Error during processing */
458                 fatal = 1;
459                 goto err;
460         case 0: /* No ticket found */
461         case 1: /* Zero length ticket found */
462                 break; /* Ok to carry on processing session id. */
463         case 2: /* Ticket found but not decrypted. */
464         case 3: /* Ticket decrypted, *ret has been set. */
465                 try_session_cache = 0;
466                 break;
467         default:
468                 abort();
469                 }
470
471         if (try_session_cache &&
472             ret == NULL &&
473             !(s->session_ctx->session_cache_mode & SSL_SESS_CACHE_NO_INTERNAL_LOOKUP))
474                 {
475                 SSL_SESSION data;
476                 data.ssl_version=s->version;
477                 data.session_id_length=ctx->session_id_len;
478                 if (ctx->session_id_len == 0)
479                         return 0;
480                 memcpy(data.session_id,ctx->session_id,ctx->session_id_len);
481                 CRYPTO_r_lock(CRYPTO_LOCK_SSL_CTX);
482                 ret=lh_SSL_SESSION_retrieve(s->session_ctx->sessions,&data);
483                 if (ret != NULL)
484                         {
485                         /* don't allow other threads to steal it: */
486                         CRYPTO_add(&ret->references,1,CRYPTO_LOCK_SSL_SESSION);
487                         }
488                 CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX);
489                 if (ret == NULL)
490                         s->session_ctx->stats.sess_miss++;
491                 }
492
493         if (try_session_cache &&
494             ret == NULL &&
495             s->session_ctx->get_session_cb != NULL)
496                 {
497                 int copy=1;
498         
499                 if ((ret=s->session_ctx->get_session_cb(s,(unsigned char *) ctx->session_id,ctx->session_id_len,&copy)))
500                         {
501                         if (ret == SSL_magic_pending_session_ptr())
502                                 {
503                                 /* This is a magic value which indicates that
504                                  * the callback needs to unwind the stack and
505                                  * figure out the session asynchronously. */
506                                 return PENDING_SESSION;
507                                 }
508                         s->session_ctx->stats.sess_cb_hit++;
509
510                         /* Increment reference count now if the session callback
511                          * asks us to do so (note that if the session structures
512                          * returned by the callback are shared between threads,
513                          * it must handle the reference count itself [i.e. copy == 0],
514                          * or things won't be thread-safe). */
515                         if (copy)
516                                 CRYPTO_add(&ret->references,1,CRYPTO_LOCK_SSL_SESSION);
517
518                         /* Add the externally cached session to the internal
519                          * cache as well if and only if we are supposed to. */
520                         if(!(s->session_ctx->session_cache_mode & SSL_SESS_CACHE_NO_INTERNAL_STORE))
521                                 /* The following should not return 1, otherwise,
522                                  * things are very strange */
523                                 SSL_CTX_add_session(s->session_ctx,ret);
524                         }
525                 }
526
527         if (ret == NULL)
528                 goto err;
529
530         /* Now ret is non-NULL and we own one of its reference counts. */
531
532         if (ret->sid_ctx_length != s->sid_ctx_length
533             || memcmp(ret->sid_ctx,s->sid_ctx,ret->sid_ctx_length))
534                 {
535                 /* We have the session requested by the client, but we don't
536                  * want to use it in this context. */
537                 goto err; /* treat like cache miss */
538                 }
539         
540         if((s->verify_mode & SSL_VERIFY_PEER) && s->sid_ctx_length == 0)
541                 {
542                 /* We can't be sure if this session is being used out of
543                  * context, which is especially important for SSL_VERIFY_PEER.
544                  * The application should have used SSL[_CTX]_set_session_id_context.
545                  *
546                  * For this error case, we generate an error instead of treating
547                  * the event like a cache miss (otherwise it would be easy for
548                  * applications to effectively disable the session cache by
549                  * accident without anyone noticing).
550                  */
551                 
552                 OPENSSL_PUT_ERROR(SSL, ssl_get_prev_session, SSL_R_SESSION_ID_CONTEXT_UNINITIALIZED);
553                 fatal = 1;
554                 goto err;
555                 }
556
557         if (ret->cipher == NULL)
558                 {
559                 /* The cipher id has a leading 0x03 to be removed (and then put
560                  * back for the binary search) as a remnant of SSLv2 support. */
561                 ret->cipher = ssl3_get_cipher_by_value(ret->cipher_id & 0xffff);
562                 if (ret->cipher == NULL)
563                         goto err;
564                 }
565
566         if (ret->timeout < (long)(time(NULL) - ret->time)) /* timeout */
567                 {
568                 s->session_ctx->stats.sess_timeout++;
569                 if (try_session_cache)
570                         {
571                         /* session was from the cache, so remove it */
572                         SSL_CTX_remove_session(s->session_ctx,ret);
573                         }
574                 goto err;
575                 }
576
577         s->session_ctx->stats.sess_hit++;
578
579         if (s->session != NULL)
580                 SSL_SESSION_free(s->session);
581         s->session=ret;
582         s->verify_result = s->session->verify_result;
583         return 1;
584
585  err:
586         if (ret != NULL)
587                 {
588                 SSL_SESSION_free(ret);
589                 if (!try_session_cache)
590                         {
591                         /* The session was from a ticket, so we should
592                          * issue a ticket for the new session */
593                         s->tlsext_ticket_expected = 1;
594                         }
595                 }
596         if (fatal)
597                 return -1;
598         else
599                 return 0;
600         }
601
602 int SSL_CTX_add_session(SSL_CTX *ctx, SSL_SESSION *c)
603         {
604         int ret=0;
605         SSL_SESSION *s;
606
607         /* add just 1 reference count for the SSL_CTX's session cache
608          * even though it has two ways of access: each session is in a
609          * doubly linked list and an lhash */
610         CRYPTO_add(&c->references,1,CRYPTO_LOCK_SSL_SESSION);
611         /* if session c is in already in cache, we take back the increment later */
612
613         CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
614         if (!lh_SSL_SESSION_insert(ctx->sessions,&s,c)) {
615           return 0;
616         }
617         
618         /* s != NULL iff we already had a session with the given PID.
619          * In this case, s == c should hold (then we did not really modify
620          * ctx->sessions), or we're in trouble. */
621         if (s != NULL && s != c)
622                 {
623                 /* We *are* in trouble ... */
624                 SSL_SESSION_list_remove(ctx,s);
625                 SSL_SESSION_free(s);
626                 /* ... so pretend the other session did not exist in cache
627                  * (we cannot handle two SSL_SESSION structures with identical
628                  * session ID in the same cache, which could happen e.g. when
629                  * two threads concurrently obtain the same session from an external
630                  * cache) */
631                 s = NULL;
632                 }
633
634         /* Put at the head of the queue unless it is already in the cache */
635         if (s == NULL)
636                 SSL_SESSION_list_add(ctx,c);
637
638         if (s != NULL)
639                 {
640                 /* existing cache entry -- decrement previously incremented reference
641                  * count because it already takes into account the cache */
642
643                 SSL_SESSION_free(s); /* s == c */
644                 ret=0;
645                 }
646         else
647                 {
648                 /* new cache entry -- remove old ones if cache has become too large */
649                 
650                 ret=1;
651
652                 if (SSL_CTX_sess_get_cache_size(ctx) > 0)
653                         {
654                         while (SSL_CTX_sess_number(ctx) >
655                                 SSL_CTX_sess_get_cache_size(ctx))
656                                 {
657                                 if (!remove_session_lock(ctx,
658                                         ctx->session_cache_tail, 0))
659                                         break;
660                                 else
661                                         ctx->stats.sess_cache_full++;
662                                 }
663                         }
664                 }
665         CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
666         return(ret);
667         }
668
669 int SSL_CTX_remove_session(SSL_CTX *ctx, SSL_SESSION *c)
670 {
671         return remove_session_lock(ctx, c, 1);
672 }
673
674 static int remove_session_lock(SSL_CTX *ctx, SSL_SESSION *c, int lck)
675         {
676         SSL_SESSION *r;
677         int ret=0;
678
679         if ((c != NULL) && (c->session_id_length != 0))
680                 {
681                 if(lck) CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
682                 if ((r = lh_SSL_SESSION_retrieve(ctx->sessions,c)) == c)
683                         {
684                         ret=1;
685                         r=lh_SSL_SESSION_delete(ctx->sessions,c);
686                         SSL_SESSION_list_remove(ctx,c);
687                         }
688
689                 if(lck) CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
690
691                 if (ret)
692                         {
693                         r->not_resumable=1;
694                         if (ctx->remove_session_cb != NULL)
695                                 ctx->remove_session_cb(ctx,r);
696                         SSL_SESSION_free(r);
697                         }
698                 }
699         else
700                 ret=0;
701         return(ret);
702         }
703
704 void SSL_SESSION_free(SSL_SESSION *ss)
705         {
706         int i;
707
708         if(ss == NULL)
709             return;
710
711         i=CRYPTO_add(&ss->references,-1,CRYPTO_LOCK_SSL_SESSION);
712 #ifdef REF_PRINT
713         REF_PRINT("SSL_SESSION",ss);
714 #endif
715         if (i > 0) return;
716 #ifdef REF_CHECK
717         if (i < 0)
718                 {
719                 fprintf(stderr,"SSL_SESSION_free, bad reference count\n");
720                 abort(); /* ok */
721                 }
722 #endif
723
724         CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL_SESSION, ss, &ss->ex_data);
725
726         OPENSSL_cleanse(ss->key_arg,sizeof ss->key_arg);
727         OPENSSL_cleanse(ss->master_key,sizeof ss->master_key);
728         OPENSSL_cleanse(ss->session_id,sizeof ss->session_id);
729         if (ss->sess_cert != NULL) ssl_sess_cert_free(ss->sess_cert);
730         if (ss->peer != NULL) X509_free(ss->peer);
731         if (ss->ciphers != NULL) sk_SSL_CIPHER_free(ss->ciphers);
732         if (ss->tlsext_hostname != NULL) OPENSSL_free(ss->tlsext_hostname);
733         if (ss->tlsext_tick != NULL) OPENSSL_free(ss->tlsext_tick);
734 #ifndef OPENSSL_NO_EC
735         ss->tlsext_ecpointformatlist_length = 0;
736         if (ss->tlsext_ecpointformatlist != NULL) OPENSSL_free(ss->tlsext_ecpointformatlist);
737         ss->tlsext_ellipticcurvelist_length = 0;
738         if (ss->tlsext_ellipticcurvelist != NULL) OPENSSL_free(ss->tlsext_ellipticcurvelist);
739 #endif /* OPENSSL_NO_EC */
740         if (ss->psk_identity_hint != NULL)
741                 OPENSSL_free(ss->psk_identity_hint);
742         if (ss->psk_identity != NULL)
743                 OPENSSL_free(ss->psk_identity);
744         OPENSSL_cleanse(ss,sizeof(*ss));
745         OPENSSL_free(ss);
746         }
747
748 int SSL_set_session(SSL *s, SSL_SESSION *session)
749         {
750         int ret=0;
751         const SSL_METHOD *meth;
752
753         if (session != NULL)
754                 {
755                 meth=s->ctx->method->get_ssl_method(session->ssl_version);
756                 if (meth == NULL)
757                         meth=s->method->get_ssl_method(session->ssl_version);
758                 if (meth == NULL)
759                         {
760                         OPENSSL_PUT_ERROR(SSL, SSL_set_session, SSL_R_UNABLE_TO_FIND_SSL_METHOD);
761                         return(0);
762                         }
763
764                 if (meth != s->method)
765                         {
766                         if (!SSL_set_ssl_method(s,meth))
767                                 return(0);
768                         }
769
770                 /* CRYPTO_w_lock(CRYPTO_LOCK_SSL);*/
771                 CRYPTO_add(&session->references,1,CRYPTO_LOCK_SSL_SESSION);
772                 if (s->session != NULL)
773                         SSL_SESSION_free(s->session);
774                 s->session=session;
775                 s->verify_result = s->session->verify_result;
776                 /* CRYPTO_w_unlock(CRYPTO_LOCK_SSL);*/
777                 ret=1;
778                 }
779         else
780                 {
781                 if (s->session != NULL)
782                         {
783                         SSL_SESSION_free(s->session);
784                         s->session=NULL;
785                         }
786
787                 meth=s->ctx->method;
788                 if (meth != s->method)
789                         {
790                         if (!SSL_set_ssl_method(s,meth))
791                                 return(0);
792                         }
793                 ret=1;
794                 }
795         return(ret);
796         }
797
798 long SSL_SESSION_set_timeout(SSL_SESSION *s, long t)
799         {
800         if (s == NULL) return(0);
801         s->timeout=t;
802         return(1);
803         }
804
805 long SSL_SESSION_get_timeout(const SSL_SESSION *s)
806         {
807         if (s == NULL) return(0);
808         return(s->timeout);
809         }
810
811 long SSL_SESSION_get_time(const SSL_SESSION *s)
812         {
813         if (s == NULL) return(0);
814         return(s->time);
815         }
816
817 long SSL_SESSION_set_time(SSL_SESSION *s, long t)
818         {
819         if (s == NULL) return(0);
820         s->time=t;
821         return(t);
822         }
823
824 X509 *SSL_SESSION_get0_peer(SSL_SESSION *s)
825         {
826         return s->peer;
827         }
828
829 int SSL_SESSION_set1_id_context(SSL_SESSION *s,const unsigned char *sid_ctx,
830                                unsigned int sid_ctx_len)
831         {
832         if(sid_ctx_len > SSL_MAX_SID_CTX_LENGTH)
833                 {
834                 OPENSSL_PUT_ERROR(SSL, SSL_SESSION_set1_id_context, SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
835                 return 0;
836                 }
837         s->sid_ctx_length=sid_ctx_len;
838         memcpy(s->sid_ctx,sid_ctx,sid_ctx_len);
839
840         return 1;
841         }
842
843 long SSL_CTX_set_timeout(SSL_CTX *s, long t)
844         {
845         long l;
846         if (s == NULL) return(0);
847         l=s->session_timeout;
848         s->session_timeout=t;
849         return(l);
850         }
851
852 long SSL_CTX_get_timeout(const SSL_CTX *s)
853         {
854         if (s == NULL) return(0);
855         return(s->session_timeout);
856         }
857
858 int SSL_set_session_secret_cb(SSL *s, int (*tls_session_secret_cb)(SSL *s, void *secret, int *secret_len,
859         STACK_OF(SSL_CIPHER) *peer_ciphers, SSL_CIPHER **cipher, void *arg), void *arg)
860         {
861         if (s == NULL) return(0);
862         s->tls_session_secret_cb = tls_session_secret_cb;
863         s->tls_session_secret_cb_arg = arg;
864         return(1);
865         }
866
867 int SSL_set_session_ticket_ext_cb(SSL *s, tls_session_ticket_ext_cb_fn cb,
868                                   void *arg)
869         {
870         if (s == NULL) return(0);
871         s->tls_session_ticket_ext_cb = cb;
872         s->tls_session_ticket_ext_cb_arg = arg;
873         return(1);
874         }
875
876 int SSL_set_session_ticket_ext(SSL *s, void *ext_data, int ext_len)
877         {
878         if (s->version >= TLS1_VERSION)
879                 {
880                 if (s->tlsext_session_ticket)
881                         {
882                         OPENSSL_free(s->tlsext_session_ticket);
883                         s->tlsext_session_ticket = NULL;
884                         }
885
886                 s->tlsext_session_ticket = OPENSSL_malloc(sizeof(TLS_SESSION_TICKET_EXT) + ext_len);
887                 if (!s->tlsext_session_ticket)
888                         {
889                         OPENSSL_PUT_ERROR(SSL, SSL_set_session_ticket_ext, ERR_R_MALLOC_FAILURE);
890                         return 0;
891                         }
892
893                 if (ext_data)
894                         {
895                         s->tlsext_session_ticket->length = ext_len;
896                         s->tlsext_session_ticket->data = s->tlsext_session_ticket + 1;
897                         memcpy(s->tlsext_session_ticket->data, ext_data, ext_len);
898                         }
899                 else
900                         {
901                         s->tlsext_session_ticket->length = 0;
902                         s->tlsext_session_ticket->data = NULL;
903                         }
904
905                 return 1;
906                 }
907
908         return 0;
909         }
910
911 typedef struct timeout_param_st
912         {
913         SSL_CTX *ctx;
914         long time;
915         LHASH_OF(SSL_SESSION) *cache;
916         } TIMEOUT_PARAM;
917
918 static void timeout_doall_arg(SSL_SESSION *sess, void *void_param)
919         {
920         TIMEOUT_PARAM *param = void_param;
921
922         if ((param->time == 0) || (param->time > (sess->time+sess->timeout))) /* timeout */
923                 {
924                 /* The reason we don't call SSL_CTX_remove_session() is to
925                  * save on locking overhead */
926                 (void)lh_SSL_SESSION_delete(param->cache,sess);
927                 SSL_SESSION_list_remove(param->ctx,sess);
928                 sess->not_resumable=1;
929                 if (param->ctx->remove_session_cb != NULL)
930                         param->ctx->remove_session_cb(param->ctx,sess);
931                 SSL_SESSION_free(sess);
932                 }
933         }
934
935 void SSL_CTX_flush_sessions(SSL_CTX *s, long t)
936         {
937         TIMEOUT_PARAM tp;
938
939         tp.ctx=s;
940         tp.cache=s->sessions;
941         if (tp.cache == NULL) return;
942         tp.time=t;
943         CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
944         lh_SSL_SESSION_doall_arg(tp.cache, timeout_doall_arg, &tp);
945         CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
946         }
947
948 int ssl_clear_bad_session(SSL *s)
949         {
950         if (    (s->session != NULL) &&
951                 !(s->shutdown & SSL_SENT_SHUTDOWN) &&
952                 !(SSL_in_init(s) || SSL_in_before(s)))
953                 {
954                 SSL_CTX_remove_session(s->ctx,s->session);
955                 return(1);
956                 }
957         else
958                 return(0);
959         }
960
961 /* locked by SSL_CTX in the calling function */
962 static void SSL_SESSION_list_remove(SSL_CTX *ctx, SSL_SESSION *s)
963         {
964         if ((s->next == NULL) || (s->prev == NULL)) return;
965
966         if (s->next == (SSL_SESSION *)&(ctx->session_cache_tail))
967                 { /* last element in list */
968                 if (s->prev == (SSL_SESSION *)&(ctx->session_cache_head))
969                         { /* only one element in list */
970                         ctx->session_cache_head=NULL;
971                         ctx->session_cache_tail=NULL;
972                         }
973                 else
974                         {
975                         ctx->session_cache_tail=s->prev;
976                         s->prev->next=(SSL_SESSION *)&(ctx->session_cache_tail);
977                         }
978                 }
979         else
980                 {
981                 if (s->prev == (SSL_SESSION *)&(ctx->session_cache_head))
982                         { /* first element in list */
983                         ctx->session_cache_head=s->next;
984                         s->next->prev=(SSL_SESSION *)&(ctx->session_cache_head);
985                         }
986                 else
987                         { /* middle of list */
988                         s->next->prev=s->prev;
989                         s->prev->next=s->next;
990                         }
991                 }
992         s->prev=s->next=NULL;
993         }
994
995 static void SSL_SESSION_list_add(SSL_CTX *ctx, SSL_SESSION *s)
996         {
997         if ((s->next != NULL) && (s->prev != NULL))
998                 SSL_SESSION_list_remove(ctx,s);
999
1000         if (ctx->session_cache_head == NULL)
1001                 {
1002                 ctx->session_cache_head=s;
1003                 ctx->session_cache_tail=s;
1004                 s->prev=(SSL_SESSION *)&(ctx->session_cache_head);
1005                 s->next=(SSL_SESSION *)&(ctx->session_cache_tail);
1006                 }
1007         else
1008                 {
1009                 s->next=ctx->session_cache_head;
1010                 s->next->prev=s;
1011                 s->prev=(SSL_SESSION *)&(ctx->session_cache_head);
1012                 ctx->session_cache_head=s;
1013                 }
1014         }
1015
1016 void SSL_CTX_sess_set_new_cb(SSL_CTX *ctx,
1017         int (*cb)(struct ssl_st *ssl,SSL_SESSION *sess))
1018         {
1019         ctx->new_session_cb=cb;
1020         }
1021
1022 int (*SSL_CTX_sess_get_new_cb(SSL_CTX *ctx))(SSL *ssl, SSL_SESSION *sess)
1023         {
1024         return ctx->new_session_cb;
1025         }
1026
1027 void SSL_CTX_sess_set_remove_cb(SSL_CTX *ctx,
1028         void (*cb)(SSL_CTX *ctx,SSL_SESSION *sess))
1029         {
1030         ctx->remove_session_cb=cb;
1031         }
1032
1033 void (*SSL_CTX_sess_get_remove_cb(SSL_CTX *ctx))(SSL_CTX * ctx,SSL_SESSION *sess)
1034         {
1035         return ctx->remove_session_cb;
1036         }
1037
1038 void SSL_CTX_sess_set_get_cb(SSL_CTX *ctx,
1039         SSL_SESSION *(*cb)(struct ssl_st *ssl,
1040                  unsigned char *data,int len,int *copy))
1041         {
1042         ctx->get_session_cb=cb;
1043         }
1044
1045 SSL_SESSION * (*SSL_CTX_sess_get_get_cb(SSL_CTX *ctx))(SSL *ssl,
1046                  unsigned char *data,int len,int *copy)
1047         {
1048         return ctx->get_session_cb;
1049         }
1050
1051 void SSL_CTX_set_info_callback(SSL_CTX *ctx, 
1052         void (*cb)(const SSL *ssl,int type,int val))
1053         {
1054         ctx->info_callback=cb;
1055         }
1056
1057 void (*SSL_CTX_get_info_callback(SSL_CTX *ctx))(const SSL *ssl,int type,int val)
1058         {
1059         return ctx->info_callback;
1060         }
1061
1062 void SSL_CTX_set_client_cert_cb(SSL_CTX *ctx,
1063         int (*cb)(SSL *ssl, X509 **x509, EVP_PKEY **pkey))
1064         {
1065         ctx->client_cert_cb=cb;
1066         }
1067
1068 int (*SSL_CTX_get_client_cert_cb(SSL_CTX *ctx))(SSL * ssl, X509 ** x509 , EVP_PKEY **pkey)
1069         {
1070         return ctx->client_cert_cb;
1071         }
1072
1073 void SSL_CTX_set_cookie_generate_cb(SSL_CTX *ctx,
1074         int (*cb)(SSL *ssl, unsigned char *cookie, unsigned int *cookie_len))
1075         {
1076         ctx->app_gen_cookie_cb=cb;
1077         }
1078
1079 /* TODO(davidben): |cookie| should be a const pointer. */
1080 void SSL_CTX_set_cookie_verify_cb(SSL_CTX *ctx,
1081         int (*cb)(SSL *ssl, unsigned char *cookie, unsigned int cookie_len))
1082         {
1083         ctx->app_verify_cookie_cb=cb;
1084         }
1085
1086 void SSL_CTX_set_channel_id_cb(SSL_CTX *ctx,
1087         void (*cb)(SSL *ssl, EVP_PKEY **pkey))
1088         {
1089         ctx->channel_id_cb=cb;
1090         }
1091
1092 void (*SSL_CTX_get_channel_id_cb(SSL_CTX *ctx))(SSL * ssl, EVP_PKEY **pkey)
1093         {
1094         return ctx->channel_id_cb;
1095         }
1096
1097 IMPLEMENT_PEM_rw(SSL_SESSION, SSL_SESSION, PEM_STRING_SSL_SESSION, SSL_SESSION)