994d09346681ce77456a983b3f6f43ca34ed555d
[openssl.git] / ssl / ssl_lib.c
1 /*
2  * ! \file ssl/ssl_lib.c \brief Version independent SSL functions.
3  */
4 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
5  * All rights reserved.
6  *
7  * This package is an SSL implementation written
8  * by Eric Young (eay@cryptsoft.com).
9  * The implementation was written so as to conform with Netscapes SSL.
10  *
11  * This library is free for commercial and non-commercial use as long as
12  * the following conditions are aheared to.  The following conditions
13  * apply to all code found in this distribution, be it the RC4, RSA,
14  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
15  * included with this distribution is covered by the same copyright terms
16  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
17  *
18  * Copyright remains Eric Young's, and as such any Copyright notices in
19  * the code are not to be removed.
20  * If this package is used in a product, Eric Young should be given attribution
21  * as the author of the parts of the library used.
22  * This can be in the form of a textual message at program startup or
23  * in documentation (online or textual) provided with the package.
24  *
25  * Redistribution and use in source and binary forms, with or without
26  * modification, are permitted provided that the following conditions
27  * are met:
28  * 1. Redistributions of source code must retain the copyright
29  *    notice, this list of conditions and the following disclaimer.
30  * 2. Redistributions in binary form must reproduce the above copyright
31  *    notice, this list of conditions and the following disclaimer in the
32  *    documentation and/or other materials provided with the distribution.
33  * 3. All advertising materials mentioning features or use of this software
34  *    must display the following acknowledgement:
35  *    "This product includes cryptographic software written by
36  *     Eric Young (eay@cryptsoft.com)"
37  *    The word 'cryptographic' can be left out if the rouines from the library
38  *    being used are not cryptographic related :-).
39  * 4. If you include any Windows specific code (or a derivative thereof) from
40  *    the apps directory (application code) you must include an acknowledgement:
41  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
42  *
43  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
44  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
45  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
46  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
47  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
48  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
49  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
50  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
51  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
52  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
53  * SUCH DAMAGE.
54  *
55  * The licence and distribution terms for any publically available version or
56  * derivative of this code cannot be changed.  i.e. this code cannot simply be
57  * copied and put under another distribution licence
58  * [including the GNU Public Licence.]
59  */
60 /* ====================================================================
61  * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
62  *
63  * Redistribution and use in source and binary forms, with or without
64  * modification, are permitted provided that the following conditions
65  * are met:
66  *
67  * 1. Redistributions of source code must retain the above copyright
68  *    notice, this list of conditions and the following disclaimer.
69  *
70  * 2. Redistributions in binary form must reproduce the above copyright
71  *    notice, this list of conditions and the following disclaimer in
72  *    the documentation and/or other materials provided with the
73  *    distribution.
74  *
75  * 3. All advertising materials mentioning features or use of this
76  *    software must display the following acknowledgment:
77  *    "This product includes software developed by the OpenSSL Project
78  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
79  *
80  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
81  *    endorse or promote products derived from this software without
82  *    prior written permission. For written permission, please contact
83  *    openssl-core@openssl.org.
84  *
85  * 5. Products derived from this software may not be called "OpenSSL"
86  *    nor may "OpenSSL" appear in their names without prior written
87  *    permission of the OpenSSL Project.
88  *
89  * 6. Redistributions of any form whatsoever must retain the following
90  *    acknowledgment:
91  *    "This product includes software developed by the OpenSSL Project
92  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
93  *
94  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
95  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
96  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
97  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
98  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
99  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
100  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
101  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
102  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
103  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
104  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
105  * OF THE POSSIBILITY OF SUCH DAMAGE.
106  * ====================================================================
107  *
108  * This product includes cryptographic software written by Eric Young
109  * (eay@cryptsoft.com).  This product includes software written by Tim
110  * Hudson (tjh@cryptsoft.com).
111  *
112  */
113 /* ====================================================================
114  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
115  * ECC cipher suite support in OpenSSL originally developed by
116  * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project.
117  */
118 /* ====================================================================
119  * Copyright 2005 Nokia. All rights reserved.
120  *
121  * The portions of the attached software ("Contribution") is developed by
122  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
123  * license.
124  *
125  * The Contribution, originally written by Mika Kousa and Pasi Eronen of
126  * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
127  * support (see RFC 4279) to OpenSSL.
128  *
129  * No patent licenses or other rights except those expressly stated in
130  * the OpenSSL open source license shall be deemed granted or received
131  * expressly, by implication, estoppel, or otherwise.
132  *
133  * No assurances are provided by Nokia that the Contribution does not
134  * infringe the patent or other intellectual property rights of any third
135  * party or that the license provides you with all the necessary rights
136  * to make use of the Contribution.
137  *
138  * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
139  * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
140  * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
141  * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
142  * OTHERWISE.
143  */
144
145 #include <assert.h>
146 #include <stdio.h>
147 #include "ssl_locl.h"
148 #include <openssl/objects.h>
149 #include <openssl/lhash.h>
150 #include <openssl/x509v3.h>
151 #include <openssl/rand.h>
152 #include <openssl/ocsp.h>
153 #include <openssl/dh.h>
154 #include <openssl/engine.h>
155 #include <openssl/async.h>
156 #include <openssl/ct.h>
157
158 const char SSL_version_str[] = OPENSSL_VERSION_TEXT;
159
160 SSL3_ENC_METHOD ssl3_undef_enc_method = {
161     /*
162      * evil casts, but these functions are only called if there's a library
163      * bug
164      */
165     (int (*)(SSL *, SSL3_RECORD *, unsigned int, int))ssl_undefined_function,
166     (int (*)(SSL *, SSL3_RECORD *, unsigned char *, int))ssl_undefined_function,
167     ssl_undefined_function,
168     (int (*)(SSL *, unsigned char *, unsigned char *, int))
169         ssl_undefined_function,
170     (int (*)(SSL *, int))ssl_undefined_function,
171     (int (*)(SSL *, const char *, int, unsigned char *))
172         ssl_undefined_function,
173     0,                          /* finish_mac_length */
174     NULL,                       /* client_finished_label */
175     0,                          /* client_finished_label_len */
176     NULL,                       /* server_finished_label */
177     0,                          /* server_finished_label_len */
178     (int (*)(int))ssl_undefined_function,
179     (int (*)(SSL *, unsigned char *, size_t, const char *,
180              size_t, const unsigned char *, size_t,
181              int use_context))ssl_undefined_function,
182 };
183
184 struct ssl_async_args {
185     SSL *s;
186     void *buf;
187     int num;
188     enum { READFUNC, WRITEFUNC,  OTHERFUNC} type;
189     union {
190         int (*func_read)(SSL *, void *, int);
191         int (*func_write)(SSL *, const void *, int);
192         int (*func_other)(SSL *);
193     } f;
194 };
195
196 static const struct {
197     uint8_t mtype;
198     uint8_t ord;
199     int     nid;
200 } dane_mds[] = {
201     { DANETLS_MATCHING_FULL, 0, NID_undef },
202     { DANETLS_MATCHING_2256, 1, NID_sha256 },
203     { DANETLS_MATCHING_2512, 2, NID_sha512 },
204 };
205
206 static int dane_ctx_enable(struct dane_ctx_st *dctx)
207 {
208     const EVP_MD **mdevp;
209     uint8_t *mdord;
210     uint8_t mdmax = DANETLS_MATCHING_LAST;
211     int n = ((int) mdmax) + 1;          /* int to handle PrivMatch(255) */
212     size_t i;
213
214     mdevp = OPENSSL_zalloc(n * sizeof(*mdevp));
215     mdord = OPENSSL_zalloc(n * sizeof(*mdord));
216
217     if (mdord == NULL || mdevp == NULL) {
218         OPENSSL_free(mdevp);
219         SSLerr(SSL_F_DANE_CTX_ENABLE, ERR_R_MALLOC_FAILURE);
220         return 0;
221     }
222
223     /* Install default entries */
224     for (i = 0; i < OSSL_NELEM(dane_mds); ++i) {
225         const EVP_MD *md;
226
227         if (dane_mds[i].nid == NID_undef ||
228             (md = EVP_get_digestbynid(dane_mds[i].nid)) == NULL)
229             continue;
230         mdevp[dane_mds[i].mtype] = md;
231         mdord[dane_mds[i].mtype] = dane_mds[i].ord;
232     }
233
234     dctx->mdevp = mdevp;
235     dctx->mdord = mdord;
236     dctx->mdmax = mdmax;
237
238     return 1;
239 }
240
241 static void dane_ctx_final(struct dane_ctx_st *dctx)
242 {
243     OPENSSL_free(dctx->mdevp);
244     dctx->mdevp = NULL;
245
246     OPENSSL_free(dctx->mdord);
247     dctx->mdord = NULL;
248     dctx->mdmax = 0;
249 }
250
251 static void tlsa_free(danetls_record *t)
252 {
253     if (t == NULL)
254         return;
255     OPENSSL_free(t->data);
256     EVP_PKEY_free(t->spki);
257     OPENSSL_free(t);
258 }
259
260 static void dane_final(SSL_DANE *dane)
261 {
262     sk_danetls_record_pop_free(dane->trecs, tlsa_free);
263     dane->trecs = NULL;
264
265     sk_X509_pop_free(dane->certs, X509_free);
266     dane->certs = NULL;
267
268     X509_free(dane->mcert);
269     dane->mcert = NULL;
270     dane->mtlsa = NULL;
271     dane->mdpth = -1;
272     dane->pdpth = -1;
273 }
274
275 /*
276  * dane_copy - Copy dane configuration, sans verification state.
277  */
278 static int ssl_dane_dup(SSL *to, SSL *from)
279 {
280     int num;
281     int i;
282
283     if (!DANETLS_ENABLED(&from->dane))
284         return 1;
285
286     dane_final(&to->dane);
287     to->dane.dctx = &to->ctx->dane;
288     to->dane.trecs = sk_danetls_record_new_null();
289
290     if (to->dane.trecs == NULL) {
291         SSLerr(SSL_F_SSL_DANE_DUP, ERR_R_MALLOC_FAILURE);
292         return 0;
293     }
294
295     num  = sk_danetls_record_num(from->dane.trecs);
296     for (i = 0; i < num; ++i) {
297         danetls_record *t = sk_danetls_record_value(from->dane.trecs, i);
298
299         if (SSL_dane_tlsa_add(to, t->usage, t->selector, t->mtype,
300                               t->data, t->dlen) <= 0)
301             return 0;
302     }
303     return 1;
304 }
305
306 static int dane_mtype_set(
307     struct dane_ctx_st *dctx,
308     const EVP_MD *md,
309     uint8_t mtype,
310     uint8_t ord)
311 {
312     int i;
313
314     if (mtype == DANETLS_MATCHING_FULL && md != NULL) {
315         SSLerr(SSL_F_DANE_MTYPE_SET,
316                 SSL_R_DANE_CANNOT_OVERRIDE_MTYPE_FULL);
317         return 0;
318     }
319
320     if (mtype > dctx->mdmax) {
321         const EVP_MD **mdevp;
322         uint8_t *mdord;
323         int n = ((int) mtype) + 1;
324
325         mdevp = OPENSSL_realloc(dctx->mdevp, n * sizeof(*mdevp));
326         if (mdevp == NULL) {
327             SSLerr(SSL_F_DANE_MTYPE_SET, ERR_R_MALLOC_FAILURE);
328             return -1;
329         }
330         dctx->mdevp = mdevp;
331
332         mdord = OPENSSL_realloc(dctx->mdord, n * sizeof(*mdord));
333         if (mdord == NULL) {
334             SSLerr(SSL_F_DANE_MTYPE_SET, ERR_R_MALLOC_FAILURE);
335             return -1;
336         }
337         dctx->mdord = mdord;
338
339         /* Zero-fill any gaps */
340         for (i = dctx->mdmax+1; i < mtype; ++i) {
341             mdevp[i] = NULL;
342             mdord[i] = 0;
343         }
344
345         dctx->mdmax = mtype;
346     }
347
348     dctx->mdevp[mtype] = md;
349     /* Coerce ordinal of disabled matching types to 0 */
350     dctx->mdord[mtype] = (md == NULL) ? 0 : ord;
351
352     return 1;
353 }
354
355 static const EVP_MD *tlsa_md_get(SSL_DANE *dane, uint8_t mtype)
356 {
357     if (mtype > dane->dctx->mdmax)
358         return NULL;
359     return dane->dctx->mdevp[mtype];
360 }
361
362 static int dane_tlsa_add(
363     SSL_DANE *dane,
364     uint8_t usage,
365     uint8_t selector,
366     uint8_t mtype,
367     unsigned char *data,
368     size_t dlen)
369 {
370     danetls_record *t;
371     const EVP_MD *md = NULL;
372     int ilen = (int)dlen;
373     int i;
374     int num;
375
376     if (dane->trecs == NULL) {
377         SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_NOT_ENABLED);
378         return -1;
379     }
380
381     if (ilen < 0 || dlen != (size_t)ilen) {
382         SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_DATA_LENGTH);
383         return 0;
384     }
385
386     if (usage > DANETLS_USAGE_LAST) {
387         SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_CERTIFICATE_USAGE);
388         return 0;
389     }
390
391     if (selector > DANETLS_SELECTOR_LAST) {
392         SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_SELECTOR);
393         return 0;
394     }
395
396     if (mtype != DANETLS_MATCHING_FULL) {
397         md = tlsa_md_get(dane, mtype);
398         if (md == NULL) {
399             SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_MATCHING_TYPE);
400             return 0;
401         }
402     }
403
404     if (md != NULL && dlen != (size_t)EVP_MD_size(md)) {
405         SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_DIGEST_LENGTH);
406         return 0;
407     }
408     if (!data) {
409         SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_NULL_DATA);
410         return 0;
411     }
412
413     if ((t = OPENSSL_zalloc(sizeof(*t))) == NULL) {
414         SSLerr(SSL_F_DANE_TLSA_ADD, ERR_R_MALLOC_FAILURE);
415         return -1;
416     }
417
418     t->usage = usage;
419     t->selector = selector;
420     t->mtype = mtype;
421     t->data = OPENSSL_malloc(ilen);
422     if (t->data == NULL) {
423         tlsa_free(t);
424         SSLerr(SSL_F_DANE_TLSA_ADD, ERR_R_MALLOC_FAILURE);
425         return -1;
426     }
427     memcpy(t->data, data, ilen);
428     t->dlen = ilen;
429
430     /* Validate and cache full certificate or public key */
431     if (mtype == DANETLS_MATCHING_FULL) {
432         const unsigned char *p = data;
433         X509 *cert = NULL;
434         EVP_PKEY *pkey = NULL;
435
436         switch (selector) {
437         case DANETLS_SELECTOR_CERT:
438             if (!d2i_X509(&cert, &p, dlen) || p < data ||
439                 dlen != (size_t)(p - data)) {
440                 tlsa_free(t);
441                 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_CERTIFICATE);
442                 return 0;
443             }
444             if (X509_get0_pubkey(cert) == NULL) {
445                 tlsa_free(t);
446                 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_CERTIFICATE);
447                 return 0;
448             }
449
450             if ((DANETLS_USAGE_BIT(usage) & DANETLS_TA_MASK) == 0) {
451                 X509_free(cert);
452                 break;
453             }
454
455             /*
456              * For usage DANE-TA(2), we support authentication via "2 0 0" TLSA
457              * records that contain full certificates of trust-anchors that are
458              * not present in the wire chain.  For usage PKIX-TA(0), we augment
459              * the chain with untrusted Full(0) certificates from DNS, in case
460              * they are missing from the chain.
461              */
462             if ((dane->certs == NULL &&
463                  (dane->certs = sk_X509_new_null()) == NULL) ||
464                 !sk_X509_push(dane->certs, cert)) {
465                 SSLerr(SSL_F_DANE_TLSA_ADD, ERR_R_MALLOC_FAILURE);
466                 X509_free(cert);
467                 tlsa_free(t);
468                 return -1;
469             }
470             break;
471
472         case DANETLS_SELECTOR_SPKI:
473             if (!d2i_PUBKEY(&pkey, &p, dlen) || p < data ||
474                 dlen != (size_t)(p - data)) {
475                 tlsa_free(t);
476                 SSLerr(SSL_F_DANE_TLSA_ADD, SSL_R_DANE_TLSA_BAD_PUBLIC_KEY);
477                 return 0;
478             }
479
480             /*
481              * For usage DANE-TA(2), we support authentication via "2 1 0" TLSA
482              * records that contain full bare keys of trust-anchors that are
483              * not present in the wire chain.
484              */
485             if (usage == DANETLS_USAGE_DANE_TA)
486                 t->spki = pkey;
487             else
488                 EVP_PKEY_free(pkey);
489             break;
490         }
491     }
492
493     /*-
494      * Find the right insertion point for the new record.
495      *
496      * See crypto/x509/x509_vfy.c.  We sort DANE-EE(3) records first, so that
497      * they can be processed first, as they require no chain building, and no
498      * expiration or hostname checks.  Because DANE-EE(3) is numerically
499      * largest, this is accomplished via descending sort by "usage".
500      *
501      * We also sort in descending order by matching ordinal to simplify
502      * the implementation of digest agility in the verification code.
503      *
504      * The choice of order for the selector is not significant, so we
505      * use the same descending order for consistency.
506      */
507     num = sk_danetls_record_num(dane->trecs);
508     for (i = 0; i < num; ++i) {
509         danetls_record *rec = sk_danetls_record_value(dane->trecs, i);
510
511         if (rec->usage > usage)
512             continue;
513         if (rec->usage < usage)
514             break;
515         if (rec->selector > selector)
516             continue;
517         if (rec->selector < selector)
518             break;
519         if (dane->dctx->mdord[rec->mtype] > dane->dctx->mdord[mtype])
520             continue;
521         break;
522     }
523
524     if (!sk_danetls_record_insert(dane->trecs, t, i)) {
525         tlsa_free(t);
526         SSLerr(SSL_F_DANE_TLSA_ADD, ERR_R_MALLOC_FAILURE);
527         return -1;
528     }
529     dane->umask |= DANETLS_USAGE_BIT(usage);
530
531     return 1;
532 }
533
534 static void clear_ciphers(SSL *s)
535 {
536     /* clear the current cipher */
537     ssl_clear_cipher_ctx(s);
538     ssl_clear_hash_ctx(&s->read_hash);
539     ssl_clear_hash_ctx(&s->write_hash);
540 }
541
542 int SSL_clear(SSL *s)
543 {
544     if (s->method == NULL) {
545         SSLerr(SSL_F_SSL_CLEAR, SSL_R_NO_METHOD_SPECIFIED);
546         return (0);
547     }
548
549     if (ssl_clear_bad_session(s)) {
550         SSL_SESSION_free(s->session);
551         s->session = NULL;
552     }
553
554     s->error = 0;
555     s->hit = 0;
556     s->shutdown = 0;
557
558     if (s->renegotiate) {
559         SSLerr(SSL_F_SSL_CLEAR, ERR_R_INTERNAL_ERROR);
560         return 0;
561     }
562
563     ossl_statem_clear(s);
564
565     s->version = s->method->version;
566     s->client_version = s->version;
567     s->rwstate = SSL_NOTHING;
568
569     BUF_MEM_free(s->init_buf);
570     s->init_buf = NULL;
571     clear_ciphers(s);
572     s->first_packet = 0;
573
574     /* Reset DANE verification result state */
575     s->dane.mdpth = -1;
576     s->dane.pdpth = -1;
577     X509_free(s->dane.mcert);
578     s->dane.mcert = NULL;
579     s->dane.mtlsa = NULL;
580
581     /* Clear the verification result peername */
582     X509_VERIFY_PARAM_move_peername(s->param, NULL);
583
584     /*
585      * Check to see if we were changed into a different method, if so, revert
586      * back if we are not doing session-id reuse.
587      */
588     if (!ossl_statem_get_in_handshake(s) && (s->session == NULL)
589         && (s->method != s->ctx->method)) {
590         s->method->ssl_free(s);
591         s->method = s->ctx->method;
592         if (!s->method->ssl_new(s))
593             return (0);
594     } else
595         s->method->ssl_clear(s);
596
597     RECORD_LAYER_clear(&s->rlayer);
598
599     return (1);
600 }
601
602 /** Used to change an SSL_CTXs default SSL method type */
603 int SSL_CTX_set_ssl_version(SSL_CTX *ctx, const SSL_METHOD *meth)
604 {
605     STACK_OF(SSL_CIPHER) *sk;
606
607     ctx->method = meth;
608
609     sk = ssl_create_cipher_list(ctx->method, &(ctx->cipher_list),
610                                 &(ctx->cipher_list_by_id),
611                                 SSL_DEFAULT_CIPHER_LIST, ctx->cert);
612     if ((sk == NULL) || (sk_SSL_CIPHER_num(sk) <= 0)) {
613         SSLerr(SSL_F_SSL_CTX_SET_SSL_VERSION,
614                SSL_R_SSL_LIBRARY_HAS_NO_CIPHERS);
615         return (0);
616     }
617     return (1);
618 }
619
620 SSL *SSL_new(SSL_CTX *ctx)
621 {
622     SSL *s;
623
624     if (ctx == NULL) {
625         SSLerr(SSL_F_SSL_NEW, SSL_R_NULL_SSL_CTX);
626         return (NULL);
627     }
628     if (ctx->method == NULL) {
629         SSLerr(SSL_F_SSL_NEW, SSL_R_SSL_CTX_HAS_NO_DEFAULT_SSL_VERSION);
630         return (NULL);
631     }
632
633     s = OPENSSL_zalloc(sizeof(*s));
634     if (s == NULL)
635         goto err;
636
637     s->lock = CRYPTO_THREAD_lock_new();
638     if (s->lock == NULL) {
639         SSLerr(SSL_F_SSL_NEW, ERR_R_MALLOC_FAILURE);
640         OPENSSL_free(s);
641         return NULL;
642     }
643
644     RECORD_LAYER_init(&s->rlayer, s);
645
646     s->options = ctx->options;
647     s->min_proto_version = ctx->min_proto_version;
648     s->max_proto_version = ctx->max_proto_version;
649     s->mode = ctx->mode;
650     s->max_cert_list = ctx->max_cert_list;
651     s->references = 1;
652
653     /*
654      * Earlier library versions used to copy the pointer to the CERT, not
655      * its contents; only when setting new parameters for the per-SSL
656      * copy, ssl_cert_new would be called (and the direct reference to
657      * the per-SSL_CTX settings would be lost, but those still were
658      * indirectly accessed for various purposes, and for that reason they
659      * used to be known as s->ctx->default_cert). Now we don't look at the
660      * SSL_CTX's CERT after having duplicated it once.
661      */
662     s->cert = ssl_cert_dup(ctx->cert);
663     if (s->cert == NULL)
664         goto err;
665
666     RECORD_LAYER_set_read_ahead(&s->rlayer, ctx->read_ahead);
667     s->msg_callback = ctx->msg_callback;
668     s->msg_callback_arg = ctx->msg_callback_arg;
669     s->verify_mode = ctx->verify_mode;
670     s->not_resumable_session_cb = ctx->not_resumable_session_cb;
671     s->sid_ctx_length = ctx->sid_ctx_length;
672     OPENSSL_assert(s->sid_ctx_length <= sizeof s->sid_ctx);
673     memcpy(&s->sid_ctx, &ctx->sid_ctx, sizeof(s->sid_ctx));
674     s->verify_callback = ctx->default_verify_callback;
675     s->generate_session_id = ctx->generate_session_id;
676
677     s->param = X509_VERIFY_PARAM_new();
678     if (s->param == NULL)
679         goto err;
680     X509_VERIFY_PARAM_inherit(s->param, ctx->param);
681     s->quiet_shutdown = ctx->quiet_shutdown;
682     s->max_send_fragment = ctx->max_send_fragment;
683     s->split_send_fragment = ctx->split_send_fragment;
684     s->max_pipelines = ctx->max_pipelines;
685     if (s->max_pipelines > 1)
686         RECORD_LAYER_set_read_ahead(&s->rlayer, 1);
687     if (ctx->default_read_buf_len > 0)
688         SSL_set_default_read_buffer_len(s, ctx->default_read_buf_len);
689
690     SSL_CTX_up_ref(ctx);
691     s->ctx = ctx;
692     s->tlsext_debug_cb = 0;
693     s->tlsext_debug_arg = NULL;
694     s->tlsext_ticket_expected = 0;
695     s->tlsext_status_type = -1;
696     s->tlsext_status_expected = 0;
697     s->tlsext_ocsp_ids = NULL;
698     s->tlsext_ocsp_exts = NULL;
699     s->tlsext_ocsp_resp = NULL;
700     s->tlsext_ocsp_resplen = -1;
701     SSL_CTX_up_ref(ctx);
702     s->initial_ctx = ctx;
703 # ifndef OPENSSL_NO_EC
704     if (ctx->tlsext_ecpointformatlist) {
705         s->tlsext_ecpointformatlist =
706             OPENSSL_memdup(ctx->tlsext_ecpointformatlist,
707                            ctx->tlsext_ecpointformatlist_length);
708         if (!s->tlsext_ecpointformatlist)
709             goto err;
710         s->tlsext_ecpointformatlist_length =
711             ctx->tlsext_ecpointformatlist_length;
712     }
713     if (ctx->tlsext_ellipticcurvelist) {
714         s->tlsext_ellipticcurvelist =
715             OPENSSL_memdup(ctx->tlsext_ellipticcurvelist,
716                            ctx->tlsext_ellipticcurvelist_length);
717         if (!s->tlsext_ellipticcurvelist)
718             goto err;
719         s->tlsext_ellipticcurvelist_length =
720             ctx->tlsext_ellipticcurvelist_length;
721     }
722 # endif
723 # ifndef OPENSSL_NO_NEXTPROTONEG
724     s->next_proto_negotiated = NULL;
725 # endif
726
727     if (s->ctx->alpn_client_proto_list) {
728         s->alpn_client_proto_list =
729             OPENSSL_malloc(s->ctx->alpn_client_proto_list_len);
730         if (s->alpn_client_proto_list == NULL)
731             goto err;
732         memcpy(s->alpn_client_proto_list, s->ctx->alpn_client_proto_list,
733                s->ctx->alpn_client_proto_list_len);
734         s->alpn_client_proto_list_len = s->ctx->alpn_client_proto_list_len;
735     }
736
737     s->verified_chain = NULL;
738     s->verify_result = X509_V_OK;
739
740     s->default_passwd_callback = ctx->default_passwd_callback;
741     s->default_passwd_callback_userdata = ctx->default_passwd_callback_userdata;
742
743     s->method = ctx->method;
744
745     if (!s->method->ssl_new(s))
746         goto err;
747
748     s->server = (ctx->method->ssl_accept == ssl_undefined_function) ? 0 : 1;
749
750     if (!SSL_clear(s))
751         goto err;
752
753     CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL, s, &s->ex_data);
754
755 #ifndef OPENSSL_NO_PSK
756     s->psk_client_callback = ctx->psk_client_callback;
757     s->psk_server_callback = ctx->psk_server_callback;
758 #endif
759
760     s->job = NULL;
761
762 #ifndef OPENSSL_NO_CT
763     if (!SSL_set_ct_validation_callback(s, ctx->ct_validation_callback,
764             ctx->ct_validation_callback_arg))
765         goto err;
766 #endif
767
768     return s;
769  err:
770     SSL_free(s);
771     SSLerr(SSL_F_SSL_NEW, ERR_R_MALLOC_FAILURE);
772     return NULL;
773 }
774
775 void SSL_up_ref(SSL *s)
776 {
777     int i;
778     CRYPTO_atomic_add(&s->references, 1, &i, s->lock);
779 }
780
781 int SSL_CTX_set_session_id_context(SSL_CTX *ctx, const unsigned char *sid_ctx,
782                                    unsigned int sid_ctx_len)
783 {
784     if (sid_ctx_len > sizeof ctx->sid_ctx) {
785         SSLerr(SSL_F_SSL_CTX_SET_SESSION_ID_CONTEXT,
786                SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
787         return 0;
788     }
789     ctx->sid_ctx_length = sid_ctx_len;
790     memcpy(ctx->sid_ctx, sid_ctx, sid_ctx_len);
791
792     return 1;
793 }
794
795 int SSL_set_session_id_context(SSL *ssl, const unsigned char *sid_ctx,
796                                unsigned int sid_ctx_len)
797 {
798     if (sid_ctx_len > SSL_MAX_SID_CTX_LENGTH) {
799         SSLerr(SSL_F_SSL_SET_SESSION_ID_CONTEXT,
800                SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG);
801         return 0;
802     }
803     ssl->sid_ctx_length = sid_ctx_len;
804     memcpy(ssl->sid_ctx, sid_ctx, sid_ctx_len);
805
806     return 1;
807 }
808
809 int SSL_CTX_set_generate_session_id(SSL_CTX *ctx, GEN_SESSION_CB cb)
810 {
811     CRYPTO_THREAD_write_lock(ctx->lock);
812     ctx->generate_session_id = cb;
813     CRYPTO_THREAD_unlock(ctx->lock);
814     return 1;
815 }
816
817 int SSL_set_generate_session_id(SSL *ssl, GEN_SESSION_CB cb)
818 {
819     CRYPTO_THREAD_write_lock(ssl->lock);
820     ssl->generate_session_id = cb;
821     CRYPTO_THREAD_unlock(ssl->lock);
822     return 1;
823 }
824
825 int SSL_has_matching_session_id(const SSL *ssl, const unsigned char *id,
826                                 unsigned int id_len)
827 {
828     /*
829      * A quick examination of SSL_SESSION_hash and SSL_SESSION_cmp shows how
830      * we can "construct" a session to give us the desired check - ie. to
831      * find if there's a session in the hash table that would conflict with
832      * any new session built out of this id/id_len and the ssl_version in use
833      * by this SSL.
834      */
835     SSL_SESSION r, *p;
836
837     if (id_len > sizeof r.session_id)
838         return 0;
839
840     r.ssl_version = ssl->version;
841     r.session_id_length = id_len;
842     memcpy(r.session_id, id, id_len);
843
844     CRYPTO_THREAD_read_lock(ssl->ctx->lock);
845     p = lh_SSL_SESSION_retrieve(ssl->ctx->sessions, &r);
846     CRYPTO_THREAD_unlock(ssl->ctx->lock);
847     return (p != NULL);
848 }
849
850 int SSL_CTX_set_purpose(SSL_CTX *s, int purpose)
851 {
852     return X509_VERIFY_PARAM_set_purpose(s->param, purpose);
853 }
854
855 int SSL_set_purpose(SSL *s, int purpose)
856 {
857     return X509_VERIFY_PARAM_set_purpose(s->param, purpose);
858 }
859
860 int SSL_CTX_set_trust(SSL_CTX *s, int trust)
861 {
862     return X509_VERIFY_PARAM_set_trust(s->param, trust);
863 }
864
865 int SSL_set_trust(SSL *s, int trust)
866 {
867     return X509_VERIFY_PARAM_set_trust(s->param, trust);
868 }
869
870 int SSL_set1_host(SSL *s, const char *hostname)
871 {
872     return X509_VERIFY_PARAM_set1_host(s->param, hostname, 0);
873 }
874
875 int SSL_add1_host(SSL *s, const char *hostname)
876 {
877     return X509_VERIFY_PARAM_add1_host(s->param, hostname, 0);
878 }
879
880 void SSL_set_hostflags(SSL *s, unsigned int flags)
881 {
882     X509_VERIFY_PARAM_set_hostflags(s->param, flags);
883 }
884
885 const char *SSL_get0_peername(SSL *s)
886 {
887     return X509_VERIFY_PARAM_get0_peername(s->param);
888 }
889
890 int SSL_CTX_dane_enable(SSL_CTX *ctx)
891 {
892     return dane_ctx_enable(&ctx->dane);
893 }
894
895 int SSL_dane_enable(SSL *s, const char *basedomain)
896 {
897     SSL_DANE *dane = &s->dane;
898
899     if (s->ctx->dane.mdmax == 0) {
900         SSLerr(SSL_F_SSL_DANE_ENABLE, SSL_R_CONTEXT_NOT_DANE_ENABLED);
901         return 0;
902     }
903     if (dane->trecs != NULL) {
904         SSLerr(SSL_F_SSL_DANE_ENABLE, SSL_R_DANE_ALREADY_ENABLED);
905         return 0;
906     }
907
908     /*
909      * Default SNI name.  This rejects empty names, while set1_host below
910      * accepts them and disables host name checks.  To avoid side-effects with
911      * invalid input, set the SNI name first.
912      */
913     if (s->tlsext_hostname == NULL) {
914         if (!SSL_set_tlsext_host_name(s, basedomain)) {
915             SSLerr(SSL_F_SSL_DANE_ENABLE, SSL_R_ERROR_SETTING_TLSA_BASE_DOMAIN);
916             return -1;
917         }
918     }
919
920     /* Primary RFC6125 reference identifier */
921     if (!X509_VERIFY_PARAM_set1_host(s->param, basedomain, 0)) {
922         SSLerr(SSL_F_SSL_DANE_ENABLE, SSL_R_ERROR_SETTING_TLSA_BASE_DOMAIN);
923         return -1;
924     }
925
926     dane->mdpth = -1;
927     dane->pdpth = -1;
928     dane->dctx = &s->ctx->dane;
929     dane->trecs = sk_danetls_record_new_null();
930
931     if (dane->trecs == NULL) {
932         SSLerr(SSL_F_SSL_DANE_ENABLE, ERR_R_MALLOC_FAILURE);
933         return -1;
934     }
935     return 1;
936 }
937
938 int SSL_get0_dane_authority(SSL *s, X509 **mcert, EVP_PKEY **mspki)
939 {
940     SSL_DANE *dane = &s->dane;
941
942     if (!DANETLS_ENABLED(dane) || s->verify_result != X509_V_OK)
943         return -1;
944     if (dane->mtlsa) {
945         if (mcert)
946             *mcert = dane->mcert;
947         if (mspki)
948             *mspki = (dane->mcert == NULL) ? dane->mtlsa->spki : NULL;
949     }
950     return dane->mdpth;
951 }
952
953 int SSL_get0_dane_tlsa(SSL *s, uint8_t *usage, uint8_t *selector,
954                        uint8_t *mtype, unsigned const char **data, size_t *dlen)
955 {
956     SSL_DANE *dane = &s->dane;
957
958     if (!DANETLS_ENABLED(dane) || s->verify_result != X509_V_OK)
959         return -1;
960     if (dane->mtlsa) {
961         if (usage)
962             *usage = dane->mtlsa->usage;
963         if (selector)
964             *selector = dane->mtlsa->selector;
965         if (mtype)
966             *mtype = dane->mtlsa->mtype;
967         if (data)
968             *data = dane->mtlsa->data;
969         if (dlen)
970             *dlen = dane->mtlsa->dlen;
971     }
972     return dane->mdpth;
973 }
974
975 SSL_DANE *SSL_get0_dane(SSL *s)
976 {
977     return &s->dane;
978 }
979
980 int SSL_dane_tlsa_add(SSL *s, uint8_t usage, uint8_t selector,
981                       uint8_t mtype, unsigned char *data, size_t dlen)
982 {
983     return dane_tlsa_add(&s->dane, usage, selector, mtype, data, dlen);
984 }
985
986 int SSL_CTX_dane_mtype_set(SSL_CTX *ctx, const EVP_MD *md, uint8_t mtype, uint8_t ord)
987 {
988     return dane_mtype_set(&ctx->dane, md, mtype, ord);
989 }
990
991 int SSL_CTX_set1_param(SSL_CTX *ctx, X509_VERIFY_PARAM *vpm)
992 {
993     return X509_VERIFY_PARAM_set1(ctx->param, vpm);
994 }
995
996 int SSL_set1_param(SSL *ssl, X509_VERIFY_PARAM *vpm)
997 {
998     return X509_VERIFY_PARAM_set1(ssl->param, vpm);
999 }
1000
1001 X509_VERIFY_PARAM *SSL_CTX_get0_param(SSL_CTX *ctx)
1002 {
1003     return ctx->param;
1004 }
1005
1006 X509_VERIFY_PARAM *SSL_get0_param(SSL *ssl)
1007 {
1008     return ssl->param;
1009 }
1010
1011 void SSL_certs_clear(SSL *s)
1012 {
1013     ssl_cert_clear_certs(s->cert);
1014 }
1015
1016 void SSL_free(SSL *s)
1017 {
1018     int i;
1019
1020     if (s == NULL)
1021         return;
1022
1023     CRYPTO_atomic_add(&s->references, -1, &i, s->lock);
1024     REF_PRINT_COUNT("SSL", s);
1025     if (i > 0)
1026         return;
1027     REF_ASSERT_ISNT(i < 0);
1028
1029     X509_VERIFY_PARAM_free(s->param);
1030     dane_final(&s->dane);
1031     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL, s, &s->ex_data);
1032
1033     if (s->bbio != NULL) {
1034         /* If the buffering BIO is in place, pop it off */
1035         if (s->bbio == s->wbio) {
1036             s->wbio = BIO_pop(s->wbio);
1037         }
1038         BIO_free(s->bbio);
1039         s->bbio = NULL;
1040     }
1041     BIO_free_all(s->rbio);
1042     if (s->wbio != s->rbio)
1043         BIO_free_all(s->wbio);
1044
1045     BUF_MEM_free(s->init_buf);
1046
1047     /* add extra stuff */
1048     sk_SSL_CIPHER_free(s->cipher_list);
1049     sk_SSL_CIPHER_free(s->cipher_list_by_id);
1050
1051     /* Make the next call work :-) */
1052     if (s->session != NULL) {
1053         ssl_clear_bad_session(s);
1054         SSL_SESSION_free(s->session);
1055     }
1056
1057     clear_ciphers(s);
1058
1059     ssl_cert_free(s->cert);
1060     /* Free up if allocated */
1061
1062     OPENSSL_free(s->tlsext_hostname);
1063     SSL_CTX_free(s->initial_ctx);
1064 #ifndef OPENSSL_NO_EC
1065     OPENSSL_free(s->tlsext_ecpointformatlist);
1066     OPENSSL_free(s->tlsext_ellipticcurvelist);
1067 #endif                         /* OPENSSL_NO_EC */
1068     sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts, X509_EXTENSION_free);
1069 #ifndef OPENSSL_NO_OCSP
1070     sk_OCSP_RESPID_pop_free(s->tlsext_ocsp_ids, OCSP_RESPID_free);
1071 #endif
1072 #ifndef OPENSSL_NO_CT
1073     SCT_LIST_free(s->scts);
1074     OPENSSL_free(s->tlsext_scts);
1075 #endif
1076     OPENSSL_free(s->tlsext_ocsp_resp);
1077     OPENSSL_free(s->alpn_client_proto_list);
1078
1079     sk_X509_NAME_pop_free(s->client_CA, X509_NAME_free);
1080
1081     sk_X509_pop_free(s->verified_chain, X509_free);
1082
1083     if (s->method != NULL)
1084         s->method->ssl_free(s);
1085
1086     RECORD_LAYER_release(&s->rlayer);
1087
1088     SSL_CTX_free(s->ctx);
1089
1090     ASYNC_WAIT_CTX_free(s->waitctx);
1091
1092 #if !defined(OPENSSL_NO_NEXTPROTONEG)
1093     OPENSSL_free(s->next_proto_negotiated);
1094 #endif
1095
1096 #ifndef OPENSSL_NO_SRTP
1097     sk_SRTP_PROTECTION_PROFILE_free(s->srtp_profiles);
1098 #endif
1099
1100     CRYPTO_THREAD_lock_free(s->lock);
1101
1102     OPENSSL_free(s);
1103 }
1104
1105 void SSL_set_rbio(SSL *s, BIO *rbio)
1106 {
1107     if (s->rbio != rbio)
1108         BIO_free_all(s->rbio);
1109     s->rbio = rbio;
1110 }
1111
1112 void SSL_set_wbio(SSL *s, BIO *wbio)
1113 {
1114     /*
1115      * If the output buffering BIO is still in place, remove it
1116      */
1117     if (s->bbio != NULL) {
1118         if (s->wbio == s->bbio) {
1119             s->wbio = BIO_next(s->wbio);
1120             BIO_set_next(s->bbio, NULL);
1121         }
1122     }
1123     if (s->wbio != wbio && s->rbio != s->wbio)
1124         BIO_free_all(s->wbio);
1125     s->wbio = wbio;
1126 }
1127
1128 void SSL_set_bio(SSL *s, BIO *rbio, BIO *wbio)
1129 {
1130     SSL_set_wbio(s, wbio);
1131     SSL_set_rbio(s, rbio);
1132 }
1133
1134 BIO *SSL_get_rbio(const SSL *s)
1135 {
1136     return (s->rbio);
1137 }
1138
1139 BIO *SSL_get_wbio(const SSL *s)
1140 {
1141     return (s->wbio);
1142 }
1143
1144 int SSL_get_fd(const SSL *s)
1145 {
1146     return (SSL_get_rfd(s));
1147 }
1148
1149 int SSL_get_rfd(const SSL *s)
1150 {
1151     int ret = -1;
1152     BIO *b, *r;
1153
1154     b = SSL_get_rbio(s);
1155     r = BIO_find_type(b, BIO_TYPE_DESCRIPTOR);
1156     if (r != NULL)
1157         BIO_get_fd(r, &ret);
1158     return (ret);
1159 }
1160
1161 int SSL_get_wfd(const SSL *s)
1162 {
1163     int ret = -1;
1164     BIO *b, *r;
1165
1166     b = SSL_get_wbio(s);
1167     r = BIO_find_type(b, BIO_TYPE_DESCRIPTOR);
1168     if (r != NULL)
1169         BIO_get_fd(r, &ret);
1170     return (ret);
1171 }
1172
1173 #ifndef OPENSSL_NO_SOCK
1174 int SSL_set_fd(SSL *s, int fd)
1175 {
1176     int ret = 0;
1177     BIO *bio = NULL;
1178
1179     bio = BIO_new(BIO_s_socket());
1180
1181     if (bio == NULL) {
1182         SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
1183         goto err;
1184     }
1185     BIO_set_fd(bio, fd, BIO_NOCLOSE);
1186     SSL_set_bio(s, bio, bio);
1187     ret = 1;
1188  err:
1189     return (ret);
1190 }
1191
1192 int SSL_set_wfd(SSL *s, int fd)
1193 {
1194     int ret = 0;
1195     BIO *bio = NULL;
1196
1197     if ((s->rbio == NULL) || (BIO_method_type(s->rbio) != BIO_TYPE_SOCKET)
1198         || ((int)BIO_get_fd(s->rbio, NULL) != fd)) {
1199         bio = BIO_new(BIO_s_socket());
1200
1201         if (bio == NULL) {
1202             SSLerr(SSL_F_SSL_SET_WFD, ERR_R_BUF_LIB);
1203             goto err;
1204         }
1205         BIO_set_fd(bio, fd, BIO_NOCLOSE);
1206         SSL_set_bio(s, SSL_get_rbio(s), bio);
1207     } else
1208         SSL_set_bio(s, SSL_get_rbio(s), SSL_get_rbio(s));
1209     ret = 1;
1210  err:
1211     return (ret);
1212 }
1213
1214 int SSL_set_rfd(SSL *s, int fd)
1215 {
1216     int ret = 0;
1217     BIO *bio = NULL;
1218
1219     if ((s->wbio == NULL) || (BIO_method_type(s->wbio) != BIO_TYPE_SOCKET)
1220         || ((int)BIO_get_fd(s->wbio, NULL) != fd)) {
1221         bio = BIO_new(BIO_s_socket());
1222
1223         if (bio == NULL) {
1224             SSLerr(SSL_F_SSL_SET_RFD, ERR_R_BUF_LIB);
1225             goto err;
1226         }
1227         BIO_set_fd(bio, fd, BIO_NOCLOSE);
1228         SSL_set_bio(s, bio, SSL_get_wbio(s));
1229     } else
1230         SSL_set_bio(s, SSL_get_wbio(s), SSL_get_wbio(s));
1231     ret = 1;
1232  err:
1233     return (ret);
1234 }
1235 #endif
1236
1237 /* return length of latest Finished message we sent, copy to 'buf' */
1238 size_t SSL_get_finished(const SSL *s, void *buf, size_t count)
1239 {
1240     size_t ret = 0;
1241
1242     if (s->s3 != NULL) {
1243         ret = s->s3->tmp.finish_md_len;
1244         if (count > ret)
1245             count = ret;
1246         memcpy(buf, s->s3->tmp.finish_md, count);
1247     }
1248     return ret;
1249 }
1250
1251 /* return length of latest Finished message we expected, copy to 'buf' */
1252 size_t SSL_get_peer_finished(const SSL *s, void *buf, size_t count)
1253 {
1254     size_t ret = 0;
1255
1256     if (s->s3 != NULL) {
1257         ret = s->s3->tmp.peer_finish_md_len;
1258         if (count > ret)
1259             count = ret;
1260         memcpy(buf, s->s3->tmp.peer_finish_md, count);
1261     }
1262     return ret;
1263 }
1264
1265 int SSL_get_verify_mode(const SSL *s)
1266 {
1267     return (s->verify_mode);
1268 }
1269
1270 int SSL_get_verify_depth(const SSL *s)
1271 {
1272     return X509_VERIFY_PARAM_get_depth(s->param);
1273 }
1274
1275 int (*SSL_get_verify_callback(const SSL *s)) (int, X509_STORE_CTX *) {
1276     return (s->verify_callback);
1277 }
1278
1279 int SSL_CTX_get_verify_mode(const SSL_CTX *ctx)
1280 {
1281     return (ctx->verify_mode);
1282 }
1283
1284 int SSL_CTX_get_verify_depth(const SSL_CTX *ctx)
1285 {
1286     return X509_VERIFY_PARAM_get_depth(ctx->param);
1287 }
1288
1289 int (*SSL_CTX_get_verify_callback(const SSL_CTX *ctx)) (int, X509_STORE_CTX *) {
1290     return (ctx->default_verify_callback);
1291 }
1292
1293 void SSL_set_verify(SSL *s, int mode,
1294                     int (*callback) (int ok, X509_STORE_CTX *ctx))
1295 {
1296     s->verify_mode = mode;
1297     if (callback != NULL)
1298         s->verify_callback = callback;
1299 }
1300
1301 void SSL_set_verify_depth(SSL *s, int depth)
1302 {
1303     X509_VERIFY_PARAM_set_depth(s->param, depth);
1304 }
1305
1306 void SSL_set_read_ahead(SSL *s, int yes)
1307 {
1308     RECORD_LAYER_set_read_ahead(&s->rlayer, yes);
1309 }
1310
1311 int SSL_get_read_ahead(const SSL *s)
1312 {
1313     return RECORD_LAYER_get_read_ahead(&s->rlayer);
1314 }
1315
1316 int SSL_pending(const SSL *s)
1317 {
1318     /*
1319      * SSL_pending cannot work properly if read-ahead is enabled
1320      * (SSL_[CTX_]ctrl(..., SSL_CTRL_SET_READ_AHEAD, 1, NULL)), and it is
1321      * impossible to fix since SSL_pending cannot report errors that may be
1322      * observed while scanning the new data. (Note that SSL_pending() is
1323      * often used as a boolean value, so we'd better not return -1.)
1324      */
1325     return (s->method->ssl_pending(s));
1326 }
1327
1328 int SSL_has_pending(const SSL *s)
1329 {
1330     /*
1331      * Similar to SSL_pending() but returns a 1 to indicate that we have
1332      * unprocessed data available or 0 otherwise (as opposed to the number of
1333      * bytes available). Unlike SSL_pending() this will take into account
1334      * read_ahead data. A 1 return simply indicates that we have unprocessed
1335      * data. That data may not result in any application data, or we may fail
1336      * to parse the records for some reason.
1337      */
1338     if (SSL_pending(s))
1339         return 1;
1340
1341     return RECORD_LAYER_read_pending(&s->rlayer);
1342 }
1343
1344 X509 *SSL_get_peer_certificate(const SSL *s)
1345 {
1346     X509 *r;
1347
1348     if ((s == NULL) || (s->session == NULL))
1349         r = NULL;
1350     else
1351         r = s->session->peer;
1352
1353     if (r == NULL)
1354         return (r);
1355
1356     X509_up_ref(r);
1357
1358     return (r);
1359 }
1360
1361 STACK_OF(X509) *SSL_get_peer_cert_chain(const SSL *s)
1362 {
1363     STACK_OF(X509) *r;
1364
1365     if ((s == NULL) || (s->session == NULL))
1366         r = NULL;
1367     else
1368         r = s->session->peer_chain;
1369
1370     /*
1371      * If we are a client, cert_chain includes the peer's own certificate; if
1372      * we are a server, it does not.
1373      */
1374
1375     return (r);
1376 }
1377
1378 /*
1379  * Now in theory, since the calling process own 't' it should be safe to
1380  * modify.  We need to be able to read f without being hassled
1381  */
1382 int SSL_copy_session_id(SSL *t, const SSL *f)
1383 {
1384     int i;
1385     /* Do we need to to SSL locking? */
1386     if (!SSL_set_session(t, SSL_get_session(f))) {
1387         return 0;
1388     }
1389
1390     /*
1391      * what if we are setup for one protocol version but want to talk another
1392      */
1393     if (t->method != f->method) {
1394         t->method->ssl_free(t);
1395         t->method = f->method;
1396         if (t->method->ssl_new(t) == 0)
1397             return 0;
1398     }
1399
1400     CRYPTO_atomic_add(&f->cert->references, 1, &i, f->cert->lock);
1401     ssl_cert_free(t->cert);
1402     t->cert = f->cert;
1403     if (!SSL_set_session_id_context(t, f->sid_ctx, f->sid_ctx_length)) {
1404         return 0;
1405     }
1406
1407     return 1;
1408 }
1409
1410 /* Fix this so it checks all the valid key/cert options */
1411 int SSL_CTX_check_private_key(const SSL_CTX *ctx)
1412 {
1413     if ((ctx == NULL) ||
1414         (ctx->cert->key->x509 == NULL)) {
1415         SSLerr(SSL_F_SSL_CTX_CHECK_PRIVATE_KEY,
1416                SSL_R_NO_CERTIFICATE_ASSIGNED);
1417         return (0);
1418     }
1419     if (ctx->cert->key->privatekey == NULL) {
1420         SSLerr(SSL_F_SSL_CTX_CHECK_PRIVATE_KEY,
1421                SSL_R_NO_PRIVATE_KEY_ASSIGNED);
1422         return (0);
1423     }
1424     return (X509_check_private_key
1425             (ctx->cert->key->x509, ctx->cert->key->privatekey));
1426 }
1427
1428 /* Fix this function so that it takes an optional type parameter */
1429 int SSL_check_private_key(const SSL *ssl)
1430 {
1431     if (ssl == NULL) {
1432         SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY, ERR_R_PASSED_NULL_PARAMETER);
1433         return (0);
1434     }
1435     if (ssl->cert->key->x509 == NULL) {
1436         SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY, SSL_R_NO_CERTIFICATE_ASSIGNED);
1437         return (0);
1438     }
1439     if (ssl->cert->key->privatekey == NULL) {
1440         SSLerr(SSL_F_SSL_CHECK_PRIVATE_KEY, SSL_R_NO_PRIVATE_KEY_ASSIGNED);
1441         return (0);
1442     }
1443     return (X509_check_private_key(ssl->cert->key->x509,
1444                                    ssl->cert->key->privatekey));
1445 }
1446
1447 int SSL_waiting_for_async(SSL *s)
1448 {
1449     if(s->job)
1450         return 1;
1451
1452     return 0;
1453 }
1454
1455 int SSL_get_all_async_fds(SSL *s, OSSL_ASYNC_FD *fds, size_t *numfds)
1456 {
1457     ASYNC_WAIT_CTX *ctx = s->waitctx;
1458
1459     if (ctx == NULL)
1460         return 0;
1461     return ASYNC_WAIT_CTX_get_all_fds(ctx, fds, numfds);
1462 }
1463
1464 int SSL_get_changed_async_fds(SSL *s, OSSL_ASYNC_FD *addfd, size_t *numaddfds,
1465                               OSSL_ASYNC_FD *delfd, size_t *numdelfds)
1466 {
1467     ASYNC_WAIT_CTX *ctx = s->waitctx;
1468
1469     if (ctx == NULL)
1470         return 0;
1471     return ASYNC_WAIT_CTX_get_changed_fds(ctx, addfd, numaddfds, delfd,
1472                                           numdelfds);
1473 }
1474
1475 int SSL_accept(SSL *s)
1476 {
1477     if (s->handshake_func == NULL) {
1478         /* Not properly initialized yet */
1479         SSL_set_accept_state(s);
1480     }
1481
1482     return SSL_do_handshake(s);
1483 }
1484
1485 int SSL_connect(SSL *s)
1486 {
1487     if (s->handshake_func == NULL) {
1488         /* Not properly initialized yet */
1489         SSL_set_connect_state(s);
1490     }
1491
1492     return SSL_do_handshake(s);
1493 }
1494
1495 long SSL_get_default_timeout(const SSL *s)
1496 {
1497     return (s->method->get_timeout());
1498 }
1499
1500 static int ssl_start_async_job(SSL *s, struct ssl_async_args *args,
1501                           int (*func)(void *)) {
1502     int ret;
1503     if (s->waitctx == NULL) {
1504         s->waitctx = ASYNC_WAIT_CTX_new();
1505         if (s->waitctx == NULL)
1506             return -1;
1507     }
1508     switch(ASYNC_start_job(&s->job, s->waitctx, &ret, func, args,
1509         sizeof(struct ssl_async_args))) {
1510     case ASYNC_ERR:
1511         s->rwstate = SSL_NOTHING;
1512         SSLerr(SSL_F_SSL_START_ASYNC_JOB, SSL_R_FAILED_TO_INIT_ASYNC);
1513         return -1;
1514     case ASYNC_PAUSE:
1515         s->rwstate = SSL_ASYNC_PAUSED;
1516         return -1;
1517     case ASYNC_FINISH:
1518         s->job = NULL;
1519         return ret;
1520     default:
1521         s->rwstate = SSL_NOTHING;
1522         SSLerr(SSL_F_SSL_START_ASYNC_JOB, ERR_R_INTERNAL_ERROR);
1523         /* Shouldn't happen */
1524         return -1;
1525     }
1526 }
1527
1528 static int ssl_io_intern(void *vargs)
1529 {
1530     struct ssl_async_args *args;
1531     SSL *s;
1532     void *buf;
1533     int num;
1534
1535     args = (struct ssl_async_args *)vargs;
1536     s = args->s;
1537     buf = args->buf;
1538     num = args->num;
1539     switch (args->type) {
1540     case READFUNC:
1541         return args->f.func_read(s, buf, num);
1542     case WRITEFUNC:
1543         return args->f.func_write(s, buf, num);
1544     case OTHERFUNC:
1545         return args->f.func_other(s);
1546     }
1547     return -1;
1548 }
1549
1550 int SSL_read(SSL *s, void *buf, int num)
1551 {
1552     if (s->handshake_func == NULL) {
1553         SSLerr(SSL_F_SSL_READ, SSL_R_UNINITIALIZED);
1554         return -1;
1555     }
1556
1557     if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
1558         s->rwstate = SSL_NOTHING;
1559         return (0);
1560     }
1561
1562     if((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
1563         struct ssl_async_args args;
1564
1565         args.s = s;
1566         args.buf = buf;
1567         args.num = num;
1568         args.type = READFUNC;
1569         args.f.func_read = s->method->ssl_read;
1570
1571         return ssl_start_async_job(s, &args, ssl_io_intern);
1572     } else {
1573         return s->method->ssl_read(s, buf, num);
1574     }
1575 }
1576
1577 int SSL_peek(SSL *s, void *buf, int num)
1578 {
1579     if (s->handshake_func == NULL) {
1580         SSLerr(SSL_F_SSL_PEEK, SSL_R_UNINITIALIZED);
1581         return -1;
1582     }
1583
1584     if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
1585         return (0);
1586     }
1587     if((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
1588         struct ssl_async_args args;
1589
1590         args.s = s;
1591         args.buf = buf;
1592         args.num = num;
1593         args.type = READFUNC;
1594         args.f.func_read = s->method->ssl_peek;
1595
1596         return ssl_start_async_job(s, &args, ssl_io_intern);
1597     } else {
1598         return s->method->ssl_peek(s, buf, num);
1599     }
1600 }
1601
1602 int SSL_write(SSL *s, const void *buf, int num)
1603 {
1604     if (s->handshake_func == NULL) {
1605         SSLerr(SSL_F_SSL_WRITE, SSL_R_UNINITIALIZED);
1606         return -1;
1607     }
1608
1609     if (s->shutdown & SSL_SENT_SHUTDOWN) {
1610         s->rwstate = SSL_NOTHING;
1611         SSLerr(SSL_F_SSL_WRITE, SSL_R_PROTOCOL_IS_SHUTDOWN);
1612         return (-1);
1613     }
1614
1615     if((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
1616         struct ssl_async_args args;
1617
1618         args.s = s;
1619         args.buf = (void *)buf;
1620         args.num = num;
1621         args.type = WRITEFUNC;
1622         args.f.func_write = s->method->ssl_write;
1623
1624         return ssl_start_async_job(s, &args, ssl_io_intern);
1625     } else {
1626         return s->method->ssl_write(s, buf, num);
1627     }
1628 }
1629
1630 int SSL_shutdown(SSL *s)
1631 {
1632     /*
1633      * Note that this function behaves differently from what one might
1634      * expect.  Return values are 0 for no success (yet), 1 for success; but
1635      * calling it once is usually not enough, even if blocking I/O is used
1636      * (see ssl3_shutdown).
1637      */
1638
1639     if (s->handshake_func == NULL) {
1640         SSLerr(SSL_F_SSL_SHUTDOWN, SSL_R_UNINITIALIZED);
1641         return -1;
1642     }
1643
1644     if (!SSL_in_init(s)) {
1645         if((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
1646             struct ssl_async_args args;
1647
1648             args.s = s;
1649             args.type = OTHERFUNC;
1650             args.f.func_other = s->method->ssl_shutdown;
1651
1652             return ssl_start_async_job(s, &args, ssl_io_intern);
1653         } else {
1654             return s->method->ssl_shutdown(s);
1655         }
1656     } else {
1657         SSLerr(SSL_F_SSL_SHUTDOWN, SSL_R_SHUTDOWN_WHILE_IN_INIT);
1658         return -1;
1659     }
1660 }
1661
1662 int SSL_renegotiate(SSL *s)
1663 {
1664     if (s->renegotiate == 0)
1665         s->renegotiate = 1;
1666
1667     s->new_session = 1;
1668
1669     return (s->method->ssl_renegotiate(s));
1670 }
1671
1672 int SSL_renegotiate_abbreviated(SSL *s)
1673 {
1674     if (s->renegotiate == 0)
1675         s->renegotiate = 1;
1676
1677     s->new_session = 0;
1678
1679     return (s->method->ssl_renegotiate(s));
1680 }
1681
1682 int SSL_renegotiate_pending(SSL *s)
1683 {
1684     /*
1685      * becomes true when negotiation is requested; false again once a
1686      * handshake has finished
1687      */
1688     return (s->renegotiate != 0);
1689 }
1690
1691 long SSL_ctrl(SSL *s, int cmd, long larg, void *parg)
1692 {
1693     long l;
1694
1695     switch (cmd) {
1696     case SSL_CTRL_GET_READ_AHEAD:
1697         return (RECORD_LAYER_get_read_ahead(&s->rlayer));
1698     case SSL_CTRL_SET_READ_AHEAD:
1699         l = RECORD_LAYER_get_read_ahead(&s->rlayer);
1700         RECORD_LAYER_set_read_ahead(&s->rlayer, larg);
1701         return (l);
1702
1703     case SSL_CTRL_SET_MSG_CALLBACK_ARG:
1704         s->msg_callback_arg = parg;
1705         return 1;
1706
1707     case SSL_CTRL_MODE:
1708         return (s->mode |= larg);
1709     case SSL_CTRL_CLEAR_MODE:
1710         return (s->mode &= ~larg);
1711     case SSL_CTRL_GET_MAX_CERT_LIST:
1712         return (s->max_cert_list);
1713     case SSL_CTRL_SET_MAX_CERT_LIST:
1714         l = s->max_cert_list;
1715         s->max_cert_list = larg;
1716         return (l);
1717     case SSL_CTRL_SET_MAX_SEND_FRAGMENT:
1718         if (larg < 512 || larg > SSL3_RT_MAX_PLAIN_LENGTH)
1719             return 0;
1720         s->max_send_fragment = larg;
1721         if (s->max_send_fragment < s->split_send_fragment)
1722             s->split_send_fragment = s->max_send_fragment;
1723         return 1;
1724     case SSL_CTRL_SET_SPLIT_SEND_FRAGMENT:
1725         if ((unsigned int)larg > s->max_send_fragment || larg == 0)
1726             return 0;
1727         s->split_send_fragment = larg;
1728         return 1;
1729     case SSL_CTRL_SET_MAX_PIPELINES:
1730         if (larg < 1 || larg > SSL_MAX_PIPELINES)
1731             return 0;
1732         s->max_pipelines = larg;
1733         if (larg > 1)
1734             RECORD_LAYER_set_read_ahead(&s->rlayer, 1);
1735         return 1;
1736     case SSL_CTRL_GET_RI_SUPPORT:
1737         if (s->s3)
1738             return s->s3->send_connection_binding;
1739         else
1740             return 0;
1741     case SSL_CTRL_CERT_FLAGS:
1742         return (s->cert->cert_flags |= larg);
1743     case SSL_CTRL_CLEAR_CERT_FLAGS:
1744         return (s->cert->cert_flags &= ~larg);
1745
1746     case SSL_CTRL_GET_RAW_CIPHERLIST:
1747         if (parg) {
1748             if (s->s3->tmp.ciphers_raw == NULL)
1749                 return 0;
1750             *(unsigned char **)parg = s->s3->tmp.ciphers_raw;
1751             return (int)s->s3->tmp.ciphers_rawlen;
1752         } else {
1753             return TLS_CIPHER_LEN;
1754         }
1755     case SSL_CTRL_GET_EXTMS_SUPPORT:
1756         if (!s->session || SSL_in_init(s) || ossl_statem_get_in_handshake(s))
1757                 return -1;
1758         if (s->session->flags & SSL_SESS_FLAG_EXTMS)
1759             return 1;
1760         else
1761             return 0;
1762     case SSL_CTRL_SET_MIN_PROTO_VERSION:
1763         return ssl_set_version_bound(s->ctx->method->version, (int)larg,
1764                                      &s->min_proto_version);
1765     case SSL_CTRL_SET_MAX_PROTO_VERSION:
1766         return ssl_set_version_bound(s->ctx->method->version, (int)larg,
1767                                      &s->max_proto_version);
1768     default:
1769         return (s->method->ssl_ctrl(s, cmd, larg, parg));
1770     }
1771 }
1772
1773 long SSL_callback_ctrl(SSL *s, int cmd, void (*fp) (void))
1774 {
1775     switch (cmd) {
1776     case SSL_CTRL_SET_MSG_CALLBACK:
1777         s->msg_callback = (void (*)
1778                            (int write_p, int version, int content_type,
1779                             const void *buf, size_t len, SSL *ssl,
1780                             void *arg))(fp);
1781         return 1;
1782
1783     default:
1784         return (s->method->ssl_callback_ctrl(s, cmd, fp));
1785     }
1786 }
1787
1788 LHASH_OF(SSL_SESSION) *SSL_CTX_sessions(SSL_CTX *ctx)
1789 {
1790     return ctx->sessions;
1791 }
1792
1793 long SSL_CTX_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg)
1794 {
1795     long l;
1796     /* For some cases with ctx == NULL perform syntax checks */
1797     if (ctx == NULL) {
1798         switch (cmd) {
1799 #ifndef OPENSSL_NO_EC
1800         case SSL_CTRL_SET_CURVES_LIST:
1801             return tls1_set_curves_list(NULL, NULL, parg);
1802 #endif
1803         case SSL_CTRL_SET_SIGALGS_LIST:
1804         case SSL_CTRL_SET_CLIENT_SIGALGS_LIST:
1805             return tls1_set_sigalgs_list(NULL, parg, 0);
1806         default:
1807             return 0;
1808         }
1809     }
1810
1811     switch (cmd) {
1812     case SSL_CTRL_GET_READ_AHEAD:
1813         return (ctx->read_ahead);
1814     case SSL_CTRL_SET_READ_AHEAD:
1815         l = ctx->read_ahead;
1816         ctx->read_ahead = larg;
1817         return (l);
1818
1819     case SSL_CTRL_SET_MSG_CALLBACK_ARG:
1820         ctx->msg_callback_arg = parg;
1821         return 1;
1822
1823     case SSL_CTRL_GET_MAX_CERT_LIST:
1824         return (ctx->max_cert_list);
1825     case SSL_CTRL_SET_MAX_CERT_LIST:
1826         l = ctx->max_cert_list;
1827         ctx->max_cert_list = larg;
1828         return (l);
1829
1830     case SSL_CTRL_SET_SESS_CACHE_SIZE:
1831         l = ctx->session_cache_size;
1832         ctx->session_cache_size = larg;
1833         return (l);
1834     case SSL_CTRL_GET_SESS_CACHE_SIZE:
1835         return (ctx->session_cache_size);
1836     case SSL_CTRL_SET_SESS_CACHE_MODE:
1837         l = ctx->session_cache_mode;
1838         ctx->session_cache_mode = larg;
1839         return (l);
1840     case SSL_CTRL_GET_SESS_CACHE_MODE:
1841         return (ctx->session_cache_mode);
1842
1843     case SSL_CTRL_SESS_NUMBER:
1844         return (lh_SSL_SESSION_num_items(ctx->sessions));
1845     case SSL_CTRL_SESS_CONNECT:
1846         return (ctx->stats.sess_connect);
1847     case SSL_CTRL_SESS_CONNECT_GOOD:
1848         return (ctx->stats.sess_connect_good);
1849     case SSL_CTRL_SESS_CONNECT_RENEGOTIATE:
1850         return (ctx->stats.sess_connect_renegotiate);
1851     case SSL_CTRL_SESS_ACCEPT:
1852         return (ctx->stats.sess_accept);
1853     case SSL_CTRL_SESS_ACCEPT_GOOD:
1854         return (ctx->stats.sess_accept_good);
1855     case SSL_CTRL_SESS_ACCEPT_RENEGOTIATE:
1856         return (ctx->stats.sess_accept_renegotiate);
1857     case SSL_CTRL_SESS_HIT:
1858         return (ctx->stats.sess_hit);
1859     case SSL_CTRL_SESS_CB_HIT:
1860         return (ctx->stats.sess_cb_hit);
1861     case SSL_CTRL_SESS_MISSES:
1862         return (ctx->stats.sess_miss);
1863     case SSL_CTRL_SESS_TIMEOUTS:
1864         return (ctx->stats.sess_timeout);
1865     case SSL_CTRL_SESS_CACHE_FULL:
1866         return (ctx->stats.sess_cache_full);
1867     case SSL_CTRL_MODE:
1868         return (ctx->mode |= larg);
1869     case SSL_CTRL_CLEAR_MODE:
1870         return (ctx->mode &= ~larg);
1871     case SSL_CTRL_SET_MAX_SEND_FRAGMENT:
1872         if (larg < 512 || larg > SSL3_RT_MAX_PLAIN_LENGTH)
1873             return 0;
1874         ctx->max_send_fragment = larg;
1875         if (ctx->max_send_fragment < ctx->split_send_fragment)
1876             ctx->split_send_fragment = ctx->split_send_fragment;
1877         return 1;
1878     case SSL_CTRL_SET_SPLIT_SEND_FRAGMENT:
1879         if ((unsigned int)larg > ctx->max_send_fragment || larg == 0)
1880             return 0;
1881         ctx->split_send_fragment = larg;
1882         return 1;
1883     case SSL_CTRL_SET_MAX_PIPELINES:
1884         if (larg < 1 || larg > SSL_MAX_PIPELINES)
1885             return 0;
1886         ctx->max_pipelines = larg;
1887         return 1;
1888     case SSL_CTRL_CERT_FLAGS:
1889         return (ctx->cert->cert_flags |= larg);
1890     case SSL_CTRL_CLEAR_CERT_FLAGS:
1891         return (ctx->cert->cert_flags &= ~larg);
1892     case SSL_CTRL_SET_MIN_PROTO_VERSION:
1893         return ssl_set_version_bound(ctx->method->version, (int)larg,
1894                                      &ctx->min_proto_version);
1895     case SSL_CTRL_SET_MAX_PROTO_VERSION:
1896         return ssl_set_version_bound(ctx->method->version, (int)larg,
1897                                      &ctx->max_proto_version);
1898     default:
1899         return (ctx->method->ssl_ctx_ctrl(ctx, cmd, larg, parg));
1900     }
1901 }
1902
1903 long SSL_CTX_callback_ctrl(SSL_CTX *ctx, int cmd, void (*fp) (void))
1904 {
1905     switch (cmd) {
1906     case SSL_CTRL_SET_MSG_CALLBACK:
1907         ctx->msg_callback = (void (*)
1908                              (int write_p, int version, int content_type,
1909                               const void *buf, size_t len, SSL *ssl,
1910                               void *arg))(fp);
1911         return 1;
1912
1913     default:
1914         return (ctx->method->ssl_ctx_callback_ctrl(ctx, cmd, fp));
1915     }
1916 }
1917
1918 int ssl_cipher_id_cmp(const SSL_CIPHER *a, const SSL_CIPHER *b)
1919 {
1920     if (a->id > b->id)
1921         return 1;
1922     if (a->id < b->id)
1923         return -1;
1924     return 0;
1925 }
1926
1927 int ssl_cipher_ptr_id_cmp(const SSL_CIPHER *const *ap,
1928                           const SSL_CIPHER *const *bp)
1929 {
1930     if ((*ap)->id > (*bp)->id)
1931         return 1;
1932     if ((*ap)->id < (*bp)->id)
1933         return -1;
1934     return 0;
1935 }
1936
1937 /** return a STACK of the ciphers available for the SSL and in order of
1938  * preference */
1939 STACK_OF(SSL_CIPHER) *SSL_get_ciphers(const SSL *s)
1940 {
1941     if (s != NULL) {
1942         if (s->cipher_list != NULL) {
1943             return (s->cipher_list);
1944         } else if ((s->ctx != NULL) && (s->ctx->cipher_list != NULL)) {
1945             return (s->ctx->cipher_list);
1946         }
1947     }
1948     return (NULL);
1949 }
1950
1951 STACK_OF(SSL_CIPHER) *SSL_get_client_ciphers(const SSL *s)
1952 {
1953     if ((s == NULL) || (s->session == NULL) || !s->server)
1954         return NULL;
1955     return s->session->ciphers;
1956 }
1957
1958 STACK_OF(SSL_CIPHER) *SSL_get1_supported_ciphers(SSL *s)
1959 {
1960     STACK_OF(SSL_CIPHER) *sk = NULL, *ciphers;
1961     int i;
1962     ciphers = SSL_get_ciphers(s);
1963     if (!ciphers)
1964         return NULL;
1965     ssl_set_client_disabled(s);
1966     for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1967         const SSL_CIPHER *c = sk_SSL_CIPHER_value(ciphers, i);
1968         if (!ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_SUPPORTED)) {
1969             if (!sk)
1970                 sk = sk_SSL_CIPHER_new_null();
1971             if (!sk)
1972                 return NULL;
1973             if (!sk_SSL_CIPHER_push(sk, c)) {
1974                 sk_SSL_CIPHER_free(sk);
1975                 return NULL;
1976             }
1977         }
1978     }
1979     return sk;
1980 }
1981
1982 /** return a STACK of the ciphers available for the SSL and in order of
1983  * algorithm id */
1984 STACK_OF(SSL_CIPHER) *ssl_get_ciphers_by_id(SSL *s)
1985 {
1986     if (s != NULL) {
1987         if (s->cipher_list_by_id != NULL) {
1988             return (s->cipher_list_by_id);
1989         } else if ((s->ctx != NULL) && (s->ctx->cipher_list_by_id != NULL)) {
1990             return (s->ctx->cipher_list_by_id);
1991         }
1992     }
1993     return (NULL);
1994 }
1995
1996 /** The old interface to get the same thing as SSL_get_ciphers() */
1997 const char *SSL_get_cipher_list(const SSL *s, int n)
1998 {
1999     const SSL_CIPHER *c;
2000     STACK_OF(SSL_CIPHER) *sk;
2001
2002     if (s == NULL)
2003         return (NULL);
2004     sk = SSL_get_ciphers(s);
2005     if ((sk == NULL) || (sk_SSL_CIPHER_num(sk) <= n))
2006         return (NULL);
2007     c = sk_SSL_CIPHER_value(sk, n);
2008     if (c == NULL)
2009         return (NULL);
2010     return (c->name);
2011 }
2012
2013 /** return a STACK of the ciphers available for the SSL_CTX and in order of
2014  * preference */
2015 STACK_OF(SSL_CIPHER) *SSL_CTX_get_ciphers(const SSL_CTX *ctx)
2016 {
2017     if (ctx != NULL)
2018         return ctx->cipher_list;
2019     return NULL;
2020 }
2021
2022 /** specify the ciphers to be used by default by the SSL_CTX */
2023 int SSL_CTX_set_cipher_list(SSL_CTX *ctx, const char *str)
2024 {
2025     STACK_OF(SSL_CIPHER) *sk;
2026
2027     sk = ssl_create_cipher_list(ctx->method, &ctx->cipher_list,
2028                                 &ctx->cipher_list_by_id, str, ctx->cert);
2029     /*
2030      * ssl_create_cipher_list may return an empty stack if it was unable to
2031      * find a cipher matching the given rule string (for example if the rule
2032      * string specifies a cipher which has been disabled). This is not an
2033      * error as far as ssl_create_cipher_list is concerned, and hence
2034      * ctx->cipher_list and ctx->cipher_list_by_id has been updated.
2035      */
2036     if (sk == NULL)
2037         return 0;
2038     else if (sk_SSL_CIPHER_num(sk) == 0) {
2039         SSLerr(SSL_F_SSL_CTX_SET_CIPHER_LIST, SSL_R_NO_CIPHER_MATCH);
2040         return 0;
2041     }
2042     return 1;
2043 }
2044
2045 /** specify the ciphers to be used by the SSL */
2046 int SSL_set_cipher_list(SSL *s, const char *str)
2047 {
2048     STACK_OF(SSL_CIPHER) *sk;
2049
2050     sk = ssl_create_cipher_list(s->ctx->method, &s->cipher_list,
2051                                 &s->cipher_list_by_id, str, s->cert);
2052     /* see comment in SSL_CTX_set_cipher_list */
2053     if (sk == NULL)
2054         return 0;
2055     else if (sk_SSL_CIPHER_num(sk) == 0) {
2056         SSLerr(SSL_F_SSL_SET_CIPHER_LIST, SSL_R_NO_CIPHER_MATCH);
2057         return 0;
2058     }
2059     return 1;
2060 }
2061
2062 char *SSL_get_shared_ciphers(const SSL *s, char *buf, int len)
2063 {
2064     char *p;
2065     STACK_OF(SSL_CIPHER) *sk;
2066     const SSL_CIPHER *c;
2067     int i;
2068
2069     if ((s->session == NULL) || (s->session->ciphers == NULL) || (len < 2))
2070         return (NULL);
2071
2072     p = buf;
2073     sk = s->session->ciphers;
2074
2075     if (sk_SSL_CIPHER_num(sk) == 0)
2076         return NULL;
2077
2078     for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
2079         int n;
2080
2081         c = sk_SSL_CIPHER_value(sk, i);
2082         n = strlen(c->name);
2083         if (n + 1 > len) {
2084             if (p != buf)
2085                 --p;
2086             *p = '\0';
2087             return buf;
2088         }
2089         memcpy(p, c->name, n + 1);
2090         p += n;
2091         *(p++) = ':';
2092         len -= n + 1;
2093     }
2094     p[-1] = '\0';
2095     return (buf);
2096 }
2097
2098 /** return a servername extension value if provided in Client Hello, or NULL.
2099  * So far, only host_name types are defined (RFC 3546).
2100  */
2101
2102 const char *SSL_get_servername(const SSL *s, const int type)
2103 {
2104     if (type != TLSEXT_NAMETYPE_host_name)
2105         return NULL;
2106
2107     return s->session && !s->tlsext_hostname ?
2108         s->session->tlsext_hostname : s->tlsext_hostname;
2109 }
2110
2111 int SSL_get_servername_type(const SSL *s)
2112 {
2113     if (s->session
2114         && (!s->tlsext_hostname ? s->session->
2115             tlsext_hostname : s->tlsext_hostname))
2116         return TLSEXT_NAMETYPE_host_name;
2117     return -1;
2118 }
2119
2120 /*
2121  * SSL_select_next_proto implements the standard protocol selection. It is
2122  * expected that this function is called from the callback set by
2123  * SSL_CTX_set_next_proto_select_cb. The protocol data is assumed to be a
2124  * vector of 8-bit, length prefixed byte strings. The length byte itself is
2125  * not included in the length. A byte string of length 0 is invalid. No byte
2126  * string may be truncated. The current, but experimental algorithm for
2127  * selecting the protocol is: 1) If the server doesn't support NPN then this
2128  * is indicated to the callback. In this case, the client application has to
2129  * abort the connection or have a default application level protocol. 2) If
2130  * the server supports NPN, but advertises an empty list then the client
2131  * selects the first protcol in its list, but indicates via the API that this
2132  * fallback case was enacted. 3) Otherwise, the client finds the first
2133  * protocol in the server's list that it supports and selects this protocol.
2134  * This is because it's assumed that the server has better information about
2135  * which protocol a client should use. 4) If the client doesn't support any
2136  * of the server's advertised protocols, then this is treated the same as
2137  * case 2. It returns either OPENSSL_NPN_NEGOTIATED if a common protocol was
2138  * found, or OPENSSL_NPN_NO_OVERLAP if the fallback case was reached.
2139  */
2140 int SSL_select_next_proto(unsigned char **out, unsigned char *outlen,
2141                           const unsigned char *server,
2142                           unsigned int server_len,
2143                           const unsigned char *client,
2144                           unsigned int client_len)
2145 {
2146     unsigned int i, j;
2147     const unsigned char *result;
2148     int status = OPENSSL_NPN_UNSUPPORTED;
2149
2150     /*
2151      * For each protocol in server preference order, see if we support it.
2152      */
2153     for (i = 0; i < server_len;) {
2154         for (j = 0; j < client_len;) {
2155             if (server[i] == client[j] &&
2156                 memcmp(&server[i + 1], &client[j + 1], server[i]) == 0) {
2157                 /* We found a match */
2158                 result = &server[i];
2159                 status = OPENSSL_NPN_NEGOTIATED;
2160                 goto found;
2161             }
2162             j += client[j];
2163             j++;
2164         }
2165         i += server[i];
2166         i++;
2167     }
2168
2169     /* There's no overlap between our protocols and the server's list. */
2170     result = client;
2171     status = OPENSSL_NPN_NO_OVERLAP;
2172
2173  found:
2174     *out = (unsigned char *)result + 1;
2175     *outlen = result[0];
2176     return status;
2177 }
2178
2179 #ifndef OPENSSL_NO_NEXTPROTONEG
2180 /*
2181  * SSL_get0_next_proto_negotiated sets *data and *len to point to the
2182  * client's requested protocol for this connection and returns 0. If the
2183  * client didn't request any protocol, then *data is set to NULL. Note that
2184  * the client can request any protocol it chooses. The value returned from
2185  * this function need not be a member of the list of supported protocols
2186  * provided by the callback.
2187  */
2188 void SSL_get0_next_proto_negotiated(const SSL *s, const unsigned char **data,
2189                                     unsigned *len)
2190 {
2191     *data = s->next_proto_negotiated;
2192     if (!*data) {
2193         *len = 0;
2194     } else {
2195         *len = s->next_proto_negotiated_len;
2196     }
2197 }
2198
2199 /*
2200  * SSL_CTX_set_next_protos_advertised_cb sets a callback that is called when
2201  * a TLS server needs a list of supported protocols for Next Protocol
2202  * Negotiation. The returned list must be in wire format.  The list is
2203  * returned by setting |out| to point to it and |outlen| to its length. This
2204  * memory will not be modified, but one should assume that the SSL* keeps a
2205  * reference to it. The callback should return SSL_TLSEXT_ERR_OK if it
2206  * wishes to advertise. Otherwise, no such extension will be included in the
2207  * ServerHello.
2208  */
2209 void SSL_CTX_set_next_protos_advertised_cb(SSL_CTX *ctx,
2210                                            int (*cb) (SSL *ssl,
2211                                                       const unsigned char
2212                                                       **out,
2213                                                       unsigned int *outlen,
2214                                                       void *arg), void *arg)
2215 {
2216     ctx->next_protos_advertised_cb = cb;
2217     ctx->next_protos_advertised_cb_arg = arg;
2218 }
2219
2220 /*
2221  * SSL_CTX_set_next_proto_select_cb sets a callback that is called when a
2222  * client needs to select a protocol from the server's provided list. |out|
2223  * must be set to point to the selected protocol (which may be within |in|).
2224  * The length of the protocol name must be written into |outlen|. The
2225  * server's advertised protocols are provided in |in| and |inlen|. The
2226  * callback can assume that |in| is syntactically valid. The client must
2227  * select a protocol. It is fatal to the connection if this callback returns
2228  * a value other than SSL_TLSEXT_ERR_OK.
2229  */
2230 void SSL_CTX_set_next_proto_select_cb(SSL_CTX *ctx,
2231                                       int (*cb) (SSL *s, unsigned char **out,
2232                                                  unsigned char *outlen,
2233                                                  const unsigned char *in,
2234                                                  unsigned int inlen,
2235                                                  void *arg), void *arg)
2236 {
2237     ctx->next_proto_select_cb = cb;
2238     ctx->next_proto_select_cb_arg = arg;
2239 }
2240 #endif
2241
2242 /*
2243  * SSL_CTX_set_alpn_protos sets the ALPN protocol list on |ctx| to |protos|.
2244  * |protos| must be in wire-format (i.e. a series of non-empty, 8-bit
2245  * length-prefixed strings). Returns 0 on success.
2246  */
2247 int SSL_CTX_set_alpn_protos(SSL_CTX *ctx, const unsigned char *protos,
2248                             unsigned int protos_len)
2249 {
2250     OPENSSL_free(ctx->alpn_client_proto_list);
2251     ctx->alpn_client_proto_list = OPENSSL_memdup(protos, protos_len);
2252     if (ctx->alpn_client_proto_list == NULL) {
2253         SSLerr(SSL_F_SSL_CTX_SET_ALPN_PROTOS, ERR_R_MALLOC_FAILURE);
2254         return 1;
2255     }
2256     ctx->alpn_client_proto_list_len = protos_len;
2257
2258     return 0;
2259 }
2260
2261 /*
2262  * SSL_set_alpn_protos sets the ALPN protocol list on |ssl| to |protos|.
2263  * |protos| must be in wire-format (i.e. a series of non-empty, 8-bit
2264  * length-prefixed strings). Returns 0 on success.
2265  */
2266 int SSL_set_alpn_protos(SSL *ssl, const unsigned char *protos,
2267                         unsigned int protos_len)
2268 {
2269     OPENSSL_free(ssl->alpn_client_proto_list);
2270     ssl->alpn_client_proto_list = OPENSSL_memdup(protos, protos_len);
2271     if (ssl->alpn_client_proto_list == NULL) {
2272         SSLerr(SSL_F_SSL_SET_ALPN_PROTOS, ERR_R_MALLOC_FAILURE);
2273         return 1;
2274     }
2275     ssl->alpn_client_proto_list_len = protos_len;
2276
2277     return 0;
2278 }
2279
2280 /*
2281  * SSL_CTX_set_alpn_select_cb sets a callback function on |ctx| that is
2282  * called during ClientHello processing in order to select an ALPN protocol
2283  * from the client's list of offered protocols.
2284  */
2285 void SSL_CTX_set_alpn_select_cb(SSL_CTX *ctx,
2286                                 int (*cb) (SSL *ssl,
2287                                            const unsigned char **out,
2288                                            unsigned char *outlen,
2289                                            const unsigned char *in,
2290                                            unsigned int inlen,
2291                                            void *arg), void *arg)
2292 {
2293     ctx->alpn_select_cb = cb;
2294     ctx->alpn_select_cb_arg = arg;
2295 }
2296
2297 /*
2298  * SSL_get0_alpn_selected gets the selected ALPN protocol (if any) from
2299  * |ssl|. On return it sets |*data| to point to |*len| bytes of protocol name
2300  * (not including the leading length-prefix byte). If the server didn't
2301  * respond with a negotiated protocol then |*len| will be zero.
2302  */
2303 void SSL_get0_alpn_selected(const SSL *ssl, const unsigned char **data,
2304                             unsigned int *len)
2305 {
2306     *data = NULL;
2307     if (ssl->s3)
2308         *data = ssl->s3->alpn_selected;
2309     if (*data == NULL)
2310         *len = 0;
2311     else
2312         *len = ssl->s3->alpn_selected_len;
2313 }
2314
2315
2316 int SSL_export_keying_material(SSL *s, unsigned char *out, size_t olen,
2317                                const char *label, size_t llen,
2318                                const unsigned char *p, size_t plen,
2319                                int use_context)
2320 {
2321     if (s->version < TLS1_VERSION)
2322         return -1;
2323
2324     return s->method->ssl3_enc->export_keying_material(s, out, olen, label,
2325                                                        llen, p, plen,
2326                                                        use_context);
2327 }
2328
2329 static unsigned long ssl_session_hash(const SSL_SESSION *a)
2330 {
2331     unsigned long l;
2332
2333     l = (unsigned long)
2334         ((unsigned int)a->session_id[0]) |
2335         ((unsigned int)a->session_id[1] << 8L) |
2336         ((unsigned long)a->session_id[2] << 16L) |
2337         ((unsigned long)a->session_id[3] << 24L);
2338     return (l);
2339 }
2340
2341 /*
2342  * NB: If this function (or indeed the hash function which uses a sort of
2343  * coarser function than this one) is changed, ensure
2344  * SSL_CTX_has_matching_session_id() is checked accordingly. It relies on
2345  * being able to construct an SSL_SESSION that will collide with any existing
2346  * session with a matching session ID.
2347  */
2348 static int ssl_session_cmp(const SSL_SESSION *a, const SSL_SESSION *b)
2349 {
2350     if (a->ssl_version != b->ssl_version)
2351         return (1);
2352     if (a->session_id_length != b->session_id_length)
2353         return (1);
2354     return (memcmp(a->session_id, b->session_id, a->session_id_length));
2355 }
2356
2357 /*
2358  * These wrapper functions should remain rather than redeclaring
2359  * SSL_SESSION_hash and SSL_SESSION_cmp for void* types and casting each
2360  * variable. The reason is that the functions aren't static, they're exposed
2361  * via ssl.h.
2362  */
2363
2364 SSL_CTX *SSL_CTX_new(const SSL_METHOD *meth)
2365 {
2366     SSL_CTX *ret = NULL;
2367
2368     if (meth == NULL) {
2369         SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_NULL_SSL_METHOD_PASSED);
2370         return (NULL);
2371     }
2372
2373     if (!OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, NULL))
2374         return NULL;
2375
2376     if (FIPS_mode() && (meth->version < TLS1_VERSION)) {
2377         SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_AT_LEAST_TLS_1_0_NEEDED_IN_FIPS_MODE);
2378         return NULL;
2379     }
2380
2381     if (SSL_get_ex_data_X509_STORE_CTX_idx() < 0) {
2382         SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_X509_VERIFICATION_SETUP_PROBLEMS);
2383         goto err;
2384     }
2385     ret = OPENSSL_zalloc(sizeof(*ret));
2386     if (ret == NULL)
2387         goto err;
2388
2389     ret->method = meth;
2390     ret->min_proto_version = 0;
2391     ret->max_proto_version = 0;
2392     ret->session_cache_mode = SSL_SESS_CACHE_SERVER;
2393     ret->session_cache_size = SSL_SESSION_CACHE_MAX_SIZE_DEFAULT;
2394     /* We take the system default. */
2395     ret->session_timeout = meth->get_timeout();
2396     ret->references = 1;
2397     ret->lock = CRYPTO_THREAD_lock_new();
2398     if (ret->lock == NULL) {
2399         SSLerr(SSL_F_SSL_CTX_NEW, ERR_R_MALLOC_FAILURE);
2400         OPENSSL_free(ret);
2401         return NULL;
2402     }
2403     ret->max_cert_list = SSL_MAX_CERT_LIST_DEFAULT;
2404     ret->verify_mode = SSL_VERIFY_NONE;
2405     if ((ret->cert = ssl_cert_new()) == NULL)
2406         goto err;
2407
2408     ret->sessions = lh_SSL_SESSION_new(ssl_session_hash, ssl_session_cmp);
2409     if (ret->sessions == NULL)
2410         goto err;
2411     ret->cert_store = X509_STORE_new();
2412     if (ret->cert_store == NULL)
2413         goto err;
2414 #ifndef OPENSSL_NO_CT
2415     ret->ctlog_store = CTLOG_STORE_new();
2416     if (ret->ctlog_store == NULL)
2417         goto err;
2418 #endif
2419     if (!ssl_create_cipher_list(ret->method,
2420                            &ret->cipher_list, &ret->cipher_list_by_id,
2421                            SSL_DEFAULT_CIPHER_LIST, ret->cert)
2422        || sk_SSL_CIPHER_num(ret->cipher_list) <= 0) {
2423         SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_LIBRARY_HAS_NO_CIPHERS);
2424         goto err2;
2425     }
2426
2427     ret->param = X509_VERIFY_PARAM_new();
2428     if (ret->param == NULL)
2429         goto err;
2430
2431     if ((ret->md5 = EVP_get_digestbyname("ssl3-md5")) == NULL) {
2432         SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_UNABLE_TO_LOAD_SSL3_MD5_ROUTINES);
2433         goto err2;
2434     }
2435     if ((ret->sha1 = EVP_get_digestbyname("ssl3-sha1")) == NULL) {
2436         SSLerr(SSL_F_SSL_CTX_NEW, SSL_R_UNABLE_TO_LOAD_SSL3_SHA1_ROUTINES);
2437         goto err2;
2438     }
2439
2440     if ((ret->client_CA = sk_X509_NAME_new_null()) == NULL)
2441         goto err;
2442
2443     CRYPTO_new_ex_data(CRYPTO_EX_INDEX_SSL_CTX, ret, &ret->ex_data);
2444
2445     /* No compression for DTLS */
2446     if (!(meth->ssl3_enc->enc_flags & SSL_ENC_FLAG_DTLS))
2447         ret->comp_methods = SSL_COMP_get_compression_methods();
2448
2449     ret->max_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH;
2450     ret->split_send_fragment = SSL3_RT_MAX_PLAIN_LENGTH;
2451
2452     /* Setup RFC4507 ticket keys */
2453     if ((RAND_bytes(ret->tlsext_tick_key_name, 16) <= 0)
2454         || (RAND_bytes(ret->tlsext_tick_hmac_key, 16) <= 0)
2455         || (RAND_bytes(ret->tlsext_tick_aes_key, 16) <= 0))
2456         ret->options |= SSL_OP_NO_TICKET;
2457
2458 #ifndef OPENSSL_NO_SRP
2459     if (!SSL_CTX_SRP_CTX_init(ret))
2460         goto err;
2461 #endif
2462 #ifndef OPENSSL_NO_ENGINE
2463 # ifdef OPENSSL_SSL_CLIENT_ENGINE_AUTO
2464 #  define eng_strx(x)     #x
2465 #  define eng_str(x)      eng_strx(x)
2466     /* Use specific client engine automatically... ignore errors */
2467     {
2468         ENGINE *eng;
2469         eng = ENGINE_by_id(eng_str(OPENSSL_SSL_CLIENT_ENGINE_AUTO));
2470         if (!eng) {
2471             ERR_clear_error();
2472             ENGINE_load_builtin_engines();
2473             eng = ENGINE_by_id(eng_str(OPENSSL_SSL_CLIENT_ENGINE_AUTO));
2474         }
2475         if (!eng || !SSL_CTX_set_client_cert_engine(ret, eng))
2476             ERR_clear_error();
2477     }
2478 # endif
2479 #endif
2480     /*
2481      * Default is to connect to non-RI servers. When RI is more widely
2482      * deployed might change this.
2483      */
2484     ret->options |= SSL_OP_LEGACY_SERVER_CONNECT;
2485     /*
2486      * Disable compression by default to prevent CRIME. Applications can
2487      * re-enable compression by configuring
2488      * SSL_CTX_clear_options(ctx, SSL_OP_NO_COMPRESSION);
2489      * or by using the SSL_CONF library.
2490      */
2491     ret->options |= SSL_OP_NO_COMPRESSION;
2492
2493     return ret;
2494  err:
2495     SSLerr(SSL_F_SSL_CTX_NEW, ERR_R_MALLOC_FAILURE);
2496  err2:
2497     SSL_CTX_free(ret);
2498     return NULL;
2499 }
2500
2501 void SSL_CTX_up_ref(SSL_CTX *ctx)
2502 {
2503     int i;
2504     CRYPTO_atomic_add(&ctx->references, 1, &i, ctx->lock);
2505 }
2506
2507 void SSL_CTX_free(SSL_CTX *a)
2508 {
2509     int i;
2510
2511     if (a == NULL)
2512         return;
2513
2514     CRYPTO_atomic_add(&a->references, -1, &i, a->lock);
2515     REF_PRINT_COUNT("SSL_CTX", a);
2516     if (i > 0)
2517         return;
2518     REF_ASSERT_ISNT(i < 0);
2519
2520     X509_VERIFY_PARAM_free(a->param);
2521     dane_ctx_final(&a->dane);
2522
2523     /*
2524      * Free internal session cache. However: the remove_cb() may reference
2525      * the ex_data of SSL_CTX, thus the ex_data store can only be removed
2526      * after the sessions were flushed.
2527      * As the ex_data handling routines might also touch the session cache,
2528      * the most secure solution seems to be: empty (flush) the cache, then
2529      * free ex_data, then finally free the cache.
2530      * (See ticket [openssl.org #212].)
2531      */
2532     if (a->sessions != NULL)
2533         SSL_CTX_flush_sessions(a, 0);
2534
2535     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_SSL_CTX, a, &a->ex_data);
2536     lh_SSL_SESSION_free(a->sessions);
2537     X509_STORE_free(a->cert_store);
2538 #ifndef OPENSSL_NO_CT
2539     CTLOG_STORE_free(a->ctlog_store);
2540 #endif
2541     sk_SSL_CIPHER_free(a->cipher_list);
2542     sk_SSL_CIPHER_free(a->cipher_list_by_id);
2543     ssl_cert_free(a->cert);
2544     sk_X509_NAME_pop_free(a->client_CA, X509_NAME_free);
2545     sk_X509_pop_free(a->extra_certs, X509_free);
2546     a->comp_methods = NULL;
2547 #ifndef OPENSSL_NO_SRTP
2548     sk_SRTP_PROTECTION_PROFILE_free(a->srtp_profiles);
2549 #endif
2550 #ifndef OPENSSL_NO_SRP
2551     SSL_CTX_SRP_CTX_free(a);
2552 #endif
2553 #ifndef OPENSSL_NO_ENGINE
2554     ENGINE_finish(a->client_cert_engine);
2555 #endif
2556
2557 #ifndef OPENSSL_NO_EC
2558     OPENSSL_free(a->tlsext_ecpointformatlist);
2559     OPENSSL_free(a->tlsext_ellipticcurvelist);
2560 #endif
2561     OPENSSL_free(a->alpn_client_proto_list);
2562
2563     CRYPTO_THREAD_lock_free(a->lock);
2564
2565     OPENSSL_free(a);
2566 }
2567
2568 void SSL_CTX_set_default_passwd_cb(SSL_CTX *ctx, pem_password_cb *cb)
2569 {
2570     ctx->default_passwd_callback = cb;
2571 }
2572
2573 void SSL_CTX_set_default_passwd_cb_userdata(SSL_CTX *ctx, void *u)
2574 {
2575     ctx->default_passwd_callback_userdata = u;
2576 }
2577
2578 pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
2579 {
2580     return ctx->default_passwd_callback;
2581 }
2582
2583 void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
2584 {
2585     return ctx->default_passwd_callback_userdata;
2586 }
2587
2588 void SSL_set_default_passwd_cb(SSL *s, pem_password_cb *cb)
2589 {
2590     s->default_passwd_callback = cb;
2591 }
2592
2593 void SSL_set_default_passwd_cb_userdata(SSL *s, void *u)
2594 {
2595     s->default_passwd_callback_userdata = u;
2596 }
2597
2598 pem_password_cb *SSL_get_default_passwd_cb(SSL *s)
2599 {
2600     return s->default_passwd_callback;
2601 }
2602
2603 void *SSL_get_default_passwd_cb_userdata(SSL *s)
2604 {
2605     return s->default_passwd_callback_userdata;
2606 }
2607
2608 void SSL_CTX_set_cert_verify_callback(SSL_CTX *ctx,
2609                                       int (*cb) (X509_STORE_CTX *, void *),
2610                                       void *arg)
2611 {
2612     ctx->app_verify_callback = cb;
2613     ctx->app_verify_arg = arg;
2614 }
2615
2616 void SSL_CTX_set_verify(SSL_CTX *ctx, int mode,
2617                         int (*cb) (int, X509_STORE_CTX *))
2618 {
2619     ctx->verify_mode = mode;
2620     ctx->default_verify_callback = cb;
2621 }
2622
2623 void SSL_CTX_set_verify_depth(SSL_CTX *ctx, int depth)
2624 {
2625     X509_VERIFY_PARAM_set_depth(ctx->param, depth);
2626 }
2627
2628 void SSL_CTX_set_cert_cb(SSL_CTX *c, int (*cb) (SSL *ssl, void *arg),
2629                          void *arg)
2630 {
2631     ssl_cert_set_cert_cb(c->cert, cb, arg);
2632 }
2633
2634 void SSL_set_cert_cb(SSL *s, int (*cb) (SSL *ssl, void *arg), void *arg)
2635 {
2636     ssl_cert_set_cert_cb(s->cert, cb, arg);
2637 }
2638
2639 void ssl_set_masks(SSL *s)
2640 {
2641 #if !defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_GOST)
2642     CERT_PKEY *cpk;
2643 #endif
2644     CERT *c = s->cert;
2645     uint32_t *pvalid = s->s3->tmp.valid_flags;
2646     int rsa_enc, rsa_sign, dh_tmp, dsa_sign;
2647     unsigned long mask_k, mask_a;
2648 #ifndef OPENSSL_NO_EC
2649     int have_ecc_cert, ecdsa_ok;
2650     X509 *x = NULL;
2651 #endif
2652     if (c == NULL)
2653         return;
2654
2655 #ifndef OPENSSL_NO_DH
2656     dh_tmp = (c->dh_tmp != NULL || c->dh_tmp_cb != NULL || c->dh_tmp_auto);
2657 #else
2658     dh_tmp = 0;
2659 #endif
2660
2661     rsa_enc = pvalid[SSL_PKEY_RSA_ENC] & CERT_PKEY_VALID;
2662     rsa_sign = pvalid[SSL_PKEY_RSA_SIGN] & CERT_PKEY_SIGN;
2663     dsa_sign = pvalid[SSL_PKEY_DSA_SIGN] & CERT_PKEY_SIGN;
2664 #ifndef OPENSSL_NO_EC
2665     have_ecc_cert = pvalid[SSL_PKEY_ECC] & CERT_PKEY_VALID;
2666 #endif
2667     mask_k = 0;
2668     mask_a = 0;
2669
2670 #ifdef CIPHER_DEBUG
2671     fprintf(stderr, "dht=%d re=%d rs=%d ds=%d\n",
2672             dh_tmp, rsa_enc, rsa_sign, dsa_sign);
2673 #endif
2674
2675 #ifndef OPENSSL_NO_GOST
2676     cpk = &(c->pkeys[SSL_PKEY_GOST12_512]);
2677     if (cpk->x509 != NULL && cpk->privatekey != NULL) {
2678         mask_k |= SSL_kGOST;
2679         mask_a |= SSL_aGOST12;
2680     }
2681     cpk = &(c->pkeys[SSL_PKEY_GOST12_256]);
2682     if (cpk->x509 != NULL && cpk->privatekey != NULL) {
2683         mask_k |= SSL_kGOST;
2684         mask_a |= SSL_aGOST12;
2685     }
2686     cpk = &(c->pkeys[SSL_PKEY_GOST01]);
2687     if (cpk->x509 != NULL && cpk->privatekey != NULL) {
2688         mask_k |= SSL_kGOST;
2689         mask_a |= SSL_aGOST01;
2690     }
2691 #endif
2692
2693     if (rsa_enc)
2694         mask_k |= SSL_kRSA;
2695
2696     if (dh_tmp)
2697         mask_k |= SSL_kDHE;
2698
2699     if (rsa_enc || rsa_sign) {
2700         mask_a |= SSL_aRSA;
2701     }
2702
2703     if (dsa_sign) {
2704         mask_a |= SSL_aDSS;
2705     }
2706
2707     mask_a |= SSL_aNULL;
2708
2709     /*
2710      * An ECC certificate may be usable for ECDH and/or ECDSA cipher suites
2711      * depending on the key usage extension.
2712      */
2713 #ifndef OPENSSL_NO_EC
2714     if (have_ecc_cert) {
2715         uint32_t ex_kusage;
2716         cpk = &c->pkeys[SSL_PKEY_ECC];
2717         x = cpk->x509;
2718         ex_kusage = X509_get_key_usage(x);
2719         ecdsa_ok = ex_kusage & X509v3_KU_DIGITAL_SIGNATURE;
2720         if (!(pvalid[SSL_PKEY_ECC] & CERT_PKEY_SIGN))
2721             ecdsa_ok = 0;
2722         if (ecdsa_ok)
2723             mask_a |= SSL_aECDSA;
2724     }
2725 #endif
2726
2727 #ifndef OPENSSL_NO_EC
2728     mask_k |= SSL_kECDHE;
2729 #endif
2730
2731 #ifndef OPENSSL_NO_PSK
2732     mask_k |= SSL_kPSK;
2733     mask_a |= SSL_aPSK;
2734     if (mask_k & SSL_kRSA)
2735         mask_k |= SSL_kRSAPSK;
2736     if (mask_k & SSL_kDHE)
2737         mask_k |= SSL_kDHEPSK;
2738     if (mask_k & SSL_kECDHE)
2739         mask_k |= SSL_kECDHEPSK;
2740 #endif
2741
2742     s->s3->tmp.mask_k = mask_k;
2743     s->s3->tmp.mask_a = mask_a;
2744 }
2745
2746 #ifndef OPENSSL_NO_EC
2747
2748 int ssl_check_srvr_ecc_cert_and_alg(X509 *x, SSL *s)
2749 {
2750     if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aECDSA) {
2751         /* key usage, if present, must allow signing */
2752         if (!(X509_get_key_usage(x) & X509v3_KU_DIGITAL_SIGNATURE)) {
2753             SSLerr(SSL_F_SSL_CHECK_SRVR_ECC_CERT_AND_ALG,
2754                    SSL_R_ECC_CERT_NOT_FOR_SIGNING);
2755             return 0;
2756         }
2757     }
2758     return 1;                   /* all checks are ok */
2759 }
2760
2761 #endif
2762
2763 static int ssl_get_server_cert_index(const SSL *s)
2764 {
2765     int idx;
2766     idx = ssl_cipher_get_cert_index(s->s3->tmp.new_cipher);
2767     if (idx == SSL_PKEY_RSA_ENC && !s->cert->pkeys[SSL_PKEY_RSA_ENC].x509)
2768         idx = SSL_PKEY_RSA_SIGN;
2769     if (idx == SSL_PKEY_GOST_EC) {
2770         if (s->cert->pkeys[SSL_PKEY_GOST12_512].x509)
2771             idx = SSL_PKEY_GOST12_512;
2772         else if (s->cert->pkeys[SSL_PKEY_GOST12_256].x509)
2773             idx = SSL_PKEY_GOST12_256;
2774         else if (s->cert->pkeys[SSL_PKEY_GOST01].x509)
2775             idx = SSL_PKEY_GOST01;
2776         else
2777             idx = -1;
2778     }
2779     if (idx == -1)
2780         SSLerr(SSL_F_SSL_GET_SERVER_CERT_INDEX, ERR_R_INTERNAL_ERROR);
2781     return idx;
2782 }
2783
2784 CERT_PKEY *ssl_get_server_send_pkey(SSL *s)
2785 {
2786     CERT *c;
2787     int i;
2788
2789     c = s->cert;
2790     if (!s->s3 || !s->s3->tmp.new_cipher)
2791         return NULL;
2792     ssl_set_masks(s);
2793
2794     i = ssl_get_server_cert_index(s);
2795
2796     /* This may or may not be an error. */
2797     if (i < 0)
2798         return NULL;
2799
2800     /* May be NULL. */
2801     return &c->pkeys[i];
2802 }
2803
2804 EVP_PKEY *ssl_get_sign_pkey(SSL *s, const SSL_CIPHER *cipher,
2805                             const EVP_MD **pmd)
2806 {
2807     unsigned long alg_a;
2808     CERT *c;
2809     int idx = -1;
2810
2811     alg_a = cipher->algorithm_auth;
2812     c = s->cert;
2813
2814     if ((alg_a & SSL_aDSS) &&
2815             (c->pkeys[SSL_PKEY_DSA_SIGN].privatekey != NULL))
2816         idx = SSL_PKEY_DSA_SIGN;
2817     else if (alg_a & SSL_aRSA) {
2818         if (c->pkeys[SSL_PKEY_RSA_SIGN].privatekey != NULL)
2819             idx = SSL_PKEY_RSA_SIGN;
2820         else if (c->pkeys[SSL_PKEY_RSA_ENC].privatekey != NULL)
2821             idx = SSL_PKEY_RSA_ENC;
2822     } else if ((alg_a & SSL_aECDSA) &&
2823                (c->pkeys[SSL_PKEY_ECC].privatekey != NULL))
2824         idx = SSL_PKEY_ECC;
2825     if (idx == -1) {
2826         SSLerr(SSL_F_SSL_GET_SIGN_PKEY, ERR_R_INTERNAL_ERROR);
2827         return (NULL);
2828     }
2829     if (pmd)
2830         *pmd = s->s3->tmp.md[idx];
2831     return c->pkeys[idx].privatekey;
2832 }
2833
2834 int ssl_get_server_cert_serverinfo(SSL *s, const unsigned char **serverinfo,
2835                                    size_t *serverinfo_length)
2836 {
2837     CERT *c = NULL;
2838     int i = 0;
2839     *serverinfo_length = 0;
2840
2841     c = s->cert;
2842     i = ssl_get_server_cert_index(s);
2843
2844     if (i == -1)
2845         return 0;
2846     if (c->pkeys[i].serverinfo == NULL)
2847         return 0;
2848
2849     *serverinfo = c->pkeys[i].serverinfo;
2850     *serverinfo_length = c->pkeys[i].serverinfo_length;
2851     return 1;
2852 }
2853
2854 void ssl_update_cache(SSL *s, int mode)
2855 {
2856     int i;
2857
2858     /*
2859      * If the session_id_length is 0, we are not supposed to cache it, and it
2860      * would be rather hard to do anyway :-)
2861      */
2862     if (s->session->session_id_length == 0)
2863         return;
2864
2865     i = s->session_ctx->session_cache_mode;
2866     if ((i & mode) && (!s->hit)
2867         && ((i & SSL_SESS_CACHE_NO_INTERNAL_STORE)
2868             || SSL_CTX_add_session(s->session_ctx, s->session))
2869         && (s->session_ctx->new_session_cb != NULL)) {
2870         SSL_SESSION_up_ref(s->session);
2871         if (!s->session_ctx->new_session_cb(s, s->session))
2872             SSL_SESSION_free(s->session);
2873     }
2874
2875     /* auto flush every 255 connections */
2876     if ((!(i & SSL_SESS_CACHE_NO_AUTO_CLEAR)) && ((i & mode) == mode)) {
2877         if ((((mode & SSL_SESS_CACHE_CLIENT)
2878               ? s->session_ctx->stats.sess_connect_good
2879               : s->session_ctx->stats.sess_accept_good) & 0xff) == 0xff) {
2880             SSL_CTX_flush_sessions(s->session_ctx, (unsigned long)time(NULL));
2881         }
2882     }
2883 }
2884
2885 const SSL_METHOD *SSL_CTX_get_ssl_method(SSL_CTX *ctx)
2886 {
2887     return ctx->method;
2888 }
2889
2890 const SSL_METHOD *SSL_get_ssl_method(SSL *s)
2891 {
2892     return (s->method);
2893 }
2894
2895 int SSL_set_ssl_method(SSL *s, const SSL_METHOD *meth)
2896 {
2897     int ret = 1;
2898
2899     if (s->method != meth) {
2900         const SSL_METHOD *sm = s->method;
2901         int (*hf)(SSL *) = s->handshake_func;
2902
2903         if (sm->version == meth->version)
2904             s->method = meth;
2905         else {
2906             sm->ssl_free(s);
2907             s->method = meth;
2908             ret = s->method->ssl_new(s);
2909         }
2910
2911         if (hf == sm->ssl_connect)
2912             s->handshake_func = meth->ssl_connect;
2913         else if (hf == sm->ssl_accept)
2914             s->handshake_func = meth->ssl_accept;
2915     }
2916     return (ret);
2917 }
2918
2919 int SSL_get_error(const SSL *s, int i)
2920 {
2921     int reason;
2922     unsigned long l;
2923     BIO *bio;
2924
2925     if (i > 0)
2926         return (SSL_ERROR_NONE);
2927
2928     /*
2929      * Make things return SSL_ERROR_SYSCALL when doing SSL_do_handshake etc,
2930      * where we do encode the error
2931      */
2932     if ((l = ERR_peek_error()) != 0) {
2933         if (ERR_GET_LIB(l) == ERR_LIB_SYS)
2934             return (SSL_ERROR_SYSCALL);
2935         else
2936             return (SSL_ERROR_SSL);
2937     }
2938
2939     if ((i < 0) && SSL_want_read(s)) {
2940         bio = SSL_get_rbio(s);
2941         if (BIO_should_read(bio))
2942             return (SSL_ERROR_WANT_READ);
2943         else if (BIO_should_write(bio))
2944             /*
2945              * This one doesn't make too much sense ... We never try to write
2946              * to the rbio, and an application program where rbio and wbio
2947              * are separate couldn't even know what it should wait for.
2948              * However if we ever set s->rwstate incorrectly (so that we have
2949              * SSL_want_read(s) instead of SSL_want_write(s)) and rbio and
2950              * wbio *are* the same, this test works around that bug; so it
2951              * might be safer to keep it.
2952              */
2953             return (SSL_ERROR_WANT_WRITE);
2954         else if (BIO_should_io_special(bio)) {
2955             reason = BIO_get_retry_reason(bio);
2956             if (reason == BIO_RR_CONNECT)
2957                 return (SSL_ERROR_WANT_CONNECT);
2958             else if (reason == BIO_RR_ACCEPT)
2959                 return (SSL_ERROR_WANT_ACCEPT);
2960             else
2961                 return (SSL_ERROR_SYSCALL); /* unknown */
2962         }
2963     }
2964
2965     if ((i < 0) && SSL_want_write(s)) {
2966         bio = SSL_get_wbio(s);
2967         if (BIO_should_write(bio))
2968             return (SSL_ERROR_WANT_WRITE);
2969         else if (BIO_should_read(bio))
2970             /*
2971              * See above (SSL_want_read(s) with BIO_should_write(bio))
2972              */
2973             return (SSL_ERROR_WANT_READ);
2974         else if (BIO_should_io_special(bio)) {
2975             reason = BIO_get_retry_reason(bio);
2976             if (reason == BIO_RR_CONNECT)
2977                 return (SSL_ERROR_WANT_CONNECT);
2978             else if (reason == BIO_RR_ACCEPT)
2979                 return (SSL_ERROR_WANT_ACCEPT);
2980             else
2981                 return (SSL_ERROR_SYSCALL);
2982         }
2983     }
2984     if ((i < 0) && SSL_want_x509_lookup(s)) {
2985         return (SSL_ERROR_WANT_X509_LOOKUP);
2986     }
2987     if ((i < 0) && SSL_want_async(s)) {
2988         return SSL_ERROR_WANT_ASYNC;
2989     }
2990
2991     if (i == 0) {
2992         if ((s->shutdown & SSL_RECEIVED_SHUTDOWN) &&
2993             (s->s3->warn_alert == SSL_AD_CLOSE_NOTIFY))
2994             return (SSL_ERROR_ZERO_RETURN);
2995     }
2996     return (SSL_ERROR_SYSCALL);
2997 }
2998
2999 static int ssl_do_handshake_intern(void *vargs)
3000 {
3001     struct ssl_async_args *args;
3002     SSL *s;
3003
3004     args = (struct ssl_async_args *)vargs;
3005     s = args->s;
3006
3007     return s->handshake_func(s);
3008 }
3009
3010 int SSL_do_handshake(SSL *s)
3011 {
3012     int ret = 1;
3013
3014     if (s->handshake_func == NULL) {
3015         SSLerr(SSL_F_SSL_DO_HANDSHAKE, SSL_R_CONNECTION_TYPE_NOT_SET);
3016         return -1;
3017     }
3018
3019     s->method->ssl_renegotiate_check(s);
3020
3021     if (SSL_in_init(s) || SSL_in_before(s)) {
3022         if((s->mode & SSL_MODE_ASYNC) && ASYNC_get_current_job() == NULL) {
3023             struct ssl_async_args args;
3024
3025             args.s = s;
3026
3027             ret = ssl_start_async_job(s, &args, ssl_do_handshake_intern);
3028         } else {
3029             ret = s->handshake_func(s);
3030         }
3031     }
3032     return ret;
3033 }
3034
3035 void SSL_set_accept_state(SSL *s)
3036 {
3037     s->server = 1;
3038     s->shutdown = 0;
3039     ossl_statem_clear(s);
3040     s->handshake_func = s->method->ssl_accept;
3041     clear_ciphers(s);
3042 }
3043
3044 void SSL_set_connect_state(SSL *s)
3045 {
3046     s->server = 0;
3047     s->shutdown = 0;
3048     ossl_statem_clear(s);
3049     s->handshake_func = s->method->ssl_connect;
3050     clear_ciphers(s);
3051 }
3052
3053 int ssl_undefined_function(SSL *s)
3054 {
3055     SSLerr(SSL_F_SSL_UNDEFINED_FUNCTION, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
3056     return (0);
3057 }
3058
3059 int ssl_undefined_void_function(void)
3060 {
3061     SSLerr(SSL_F_SSL_UNDEFINED_VOID_FUNCTION,
3062            ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
3063     return (0);
3064 }
3065
3066 int ssl_undefined_const_function(const SSL *s)
3067 {
3068     return (0);
3069 }
3070
3071 const SSL_METHOD *ssl_bad_method(int ver)
3072 {
3073     SSLerr(SSL_F_SSL_BAD_METHOD, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
3074     return (NULL);
3075 }
3076
3077 const char *ssl_protocol_to_string(int version)
3078 {
3079     if (version == TLS1_2_VERSION)
3080         return "TLSv1.2";
3081     else if (version == TLS1_1_VERSION)
3082         return "TLSv1.1";
3083     else if (version == TLS1_VERSION)
3084         return "TLSv1";
3085     else if (version == SSL3_VERSION)
3086         return "SSLv3";
3087     else if (version == DTLS1_BAD_VER)
3088         return "DTLSv0.9";
3089     else if (version == DTLS1_VERSION)
3090         return "DTLSv1";
3091     else if (version == DTLS1_2_VERSION)
3092         return "DTLSv1.2";
3093     else
3094         return ("unknown");
3095 }
3096
3097 const char *SSL_get_version(const SSL *s)
3098 {
3099     return ssl_protocol_to_string(s->version);
3100 }
3101
3102 SSL *SSL_dup(SSL *s)
3103 {
3104     STACK_OF(X509_NAME) *sk;
3105     X509_NAME *xn;
3106     SSL *ret;
3107     int i;
3108
3109     /* If we're not quiescent, just up_ref! */
3110     if (!SSL_in_init(s) || !SSL_in_before(s)) {
3111         CRYPTO_atomic_add(&s->references, 1, &i, s->lock);
3112         return s;
3113     }
3114
3115     /*
3116      * Otherwise, copy configuration state, and session if set.
3117      */
3118     if ((ret = SSL_new(SSL_get_SSL_CTX(s))) == NULL)
3119         return (NULL);
3120
3121     if (s->session != NULL) {
3122         /*
3123          * Arranges to share the same session via up_ref.  This "copies"
3124          * session-id, SSL_METHOD, sid_ctx, and 'cert'
3125          */
3126         if (!SSL_copy_session_id(ret, s))
3127             goto err;
3128     } else {
3129         /*
3130          * No session has been established yet, so we have to expect that
3131          * s->cert or ret->cert will be changed later -- they should not both
3132          * point to the same object, and thus we can't use
3133          * SSL_copy_session_id.
3134          */
3135         if (!SSL_set_ssl_method(ret, s->method))
3136             goto err;
3137
3138         if (s->cert != NULL) {
3139             ssl_cert_free(ret->cert);
3140             ret->cert = ssl_cert_dup(s->cert);
3141             if (ret->cert == NULL)
3142                 goto err;
3143         }
3144
3145         if (!SSL_set_session_id_context(ret, s->sid_ctx, s->sid_ctx_length))
3146             goto err;
3147     }
3148
3149     if (!ssl_dane_dup(ret, s))
3150         goto err;
3151     ret->version = s->version;
3152     ret->options = s->options;
3153     ret->mode = s->mode;
3154     SSL_set_max_cert_list(ret, SSL_get_max_cert_list(s));
3155     SSL_set_read_ahead(ret, SSL_get_read_ahead(s));
3156     ret->msg_callback = s->msg_callback;
3157     ret->msg_callback_arg = s->msg_callback_arg;
3158     SSL_set_verify(ret, SSL_get_verify_mode(s), SSL_get_verify_callback(s));
3159     SSL_set_verify_depth(ret, SSL_get_verify_depth(s));
3160     ret->generate_session_id = s->generate_session_id;
3161
3162     SSL_set_info_callback(ret, SSL_get_info_callback(s));
3163
3164     /* copy app data, a little dangerous perhaps */
3165     if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_SSL, &ret->ex_data, &s->ex_data))
3166         goto err;
3167
3168     /* setup rbio, and wbio */
3169     if (s->rbio != NULL) {
3170         if (!BIO_dup_state(s->rbio, (char *)&ret->rbio))
3171             goto err;
3172     }
3173     if (s->wbio != NULL) {
3174         if (s->wbio != s->rbio) {
3175             if (!BIO_dup_state(s->wbio, (char *)&ret->wbio))
3176                 goto err;
3177         } else
3178             ret->wbio = ret->rbio;
3179     }
3180
3181     ret->server = s->server;
3182     if (s->handshake_func) {
3183         if (s->server)
3184             SSL_set_accept_state(ret);
3185         else
3186             SSL_set_connect_state(ret);
3187     }
3188     ret->shutdown = s->shutdown;
3189     ret->hit = s->hit;
3190
3191     ret->default_passwd_callback = s->default_passwd_callback;
3192     ret->default_passwd_callback_userdata = s->default_passwd_callback_userdata;
3193
3194     X509_VERIFY_PARAM_inherit(ret->param, s->param);
3195
3196     /* dup the cipher_list and cipher_list_by_id stacks */
3197     if (s->cipher_list != NULL) {
3198         if ((ret->cipher_list = sk_SSL_CIPHER_dup(s->cipher_list)) == NULL)
3199             goto err;
3200     }
3201     if (s->cipher_list_by_id != NULL)
3202         if ((ret->cipher_list_by_id = sk_SSL_CIPHER_dup(s->cipher_list_by_id))
3203             == NULL)
3204             goto err;
3205
3206     /* Dup the client_CA list */
3207     if (s->client_CA != NULL) {
3208         if ((sk = sk_X509_NAME_dup(s->client_CA)) == NULL)
3209             goto err;
3210         ret->client_CA = sk;
3211         for (i = 0; i < sk_X509_NAME_num(sk); i++) {
3212             xn = sk_X509_NAME_value(sk, i);
3213             if (sk_X509_NAME_set(sk, i, X509_NAME_dup(xn)) == NULL) {
3214                 X509_NAME_free(xn);
3215                 goto err;
3216             }
3217         }
3218     }
3219     return ret;
3220
3221  err:
3222     SSL_free(ret);
3223     return NULL;
3224 }
3225
3226 void ssl_clear_cipher_ctx(SSL *s)
3227 {
3228     if (s->enc_read_ctx != NULL) {
3229         EVP_CIPHER_CTX_free(s->enc_read_ctx);
3230         s->enc_read_ctx = NULL;
3231     }
3232     if (s->enc_write_ctx != NULL) {
3233         EVP_CIPHER_CTX_free(s->enc_write_ctx);
3234         s->enc_write_ctx = NULL;
3235     }
3236 #ifndef OPENSSL_NO_COMP
3237     COMP_CTX_free(s->expand);
3238     s->expand = NULL;
3239     COMP_CTX_free(s->compress);
3240     s->compress = NULL;
3241 #endif
3242 }
3243
3244 X509 *SSL_get_certificate(const SSL *s)
3245 {
3246     if (s->cert != NULL)
3247         return (s->cert->key->x509);
3248     else
3249         return (NULL);
3250 }
3251
3252 EVP_PKEY *SSL_get_privatekey(const SSL *s)
3253 {
3254     if (s->cert != NULL)
3255         return (s->cert->key->privatekey);
3256     else
3257         return (NULL);
3258 }
3259
3260 X509 *SSL_CTX_get0_certificate(const SSL_CTX *ctx)
3261 {
3262     if (ctx->cert != NULL)
3263         return ctx->cert->key->x509;
3264     else
3265         return NULL;
3266 }
3267
3268 EVP_PKEY *SSL_CTX_get0_privatekey(const SSL_CTX *ctx)
3269 {
3270     if (ctx->cert != NULL)
3271         return ctx->cert->key->privatekey;
3272     else
3273         return NULL;
3274 }
3275
3276 const SSL_CIPHER *SSL_get_current_cipher(const SSL *s)
3277 {
3278     if ((s->session != NULL) && (s->session->cipher != NULL))
3279         return (s->session->cipher);
3280     return (NULL);
3281 }
3282
3283 const COMP_METHOD *SSL_get_current_compression(SSL *s)
3284 {
3285 #ifndef OPENSSL_NO_COMP
3286     return s->compress ? COMP_CTX_get_method(s->compress) : NULL;
3287 #else
3288     return NULL;
3289 #endif
3290 }
3291
3292 const COMP_METHOD *SSL_get_current_expansion(SSL *s)
3293 {
3294 #ifndef OPENSSL_NO_COMP
3295     return s->expand ? COMP_CTX_get_method(s->expand) : NULL;
3296 #else
3297     return NULL;
3298 #endif
3299 }
3300
3301 int ssl_init_wbio_buffer(SSL *s, int push)
3302 {
3303     BIO *bbio;
3304
3305     if (s->bbio == NULL) {
3306         bbio = BIO_new(BIO_f_buffer());
3307         if (bbio == NULL)
3308             return (0);
3309         s->bbio = bbio;
3310     } else {
3311         bbio = s->bbio;
3312         if (s->bbio == s->wbio)
3313             s->wbio = BIO_pop(s->wbio);
3314     }
3315     (void)BIO_reset(bbio);
3316 /*      if (!BIO_set_write_buffer_size(bbio,16*1024)) */
3317     if (!BIO_set_read_buffer_size(bbio, 1)) {
3318         SSLerr(SSL_F_SSL_INIT_WBIO_BUFFER, ERR_R_BUF_LIB);
3319         return (0);
3320     }
3321     if (push) {
3322         if (s->wbio != bbio)
3323             s->wbio = BIO_push(bbio, s->wbio);
3324     } else {
3325         if (s->wbio == bbio)
3326             s->wbio = BIO_pop(bbio);
3327     }
3328     return (1);
3329 }
3330
3331 void ssl_free_wbio_buffer(SSL *s)
3332 {
3333     /* callers ensure s is never null */
3334     if (s->bbio == NULL)
3335         return;
3336
3337     if (s->bbio == s->wbio) {
3338         /* remove buffering */
3339         s->wbio = BIO_pop(s->wbio);
3340         assert(s->wbio != NULL);
3341     }
3342     BIO_free(s->bbio);
3343     s->bbio = NULL;
3344 }
3345
3346 void SSL_CTX_set_quiet_shutdown(SSL_CTX *ctx, int mode)
3347 {
3348     ctx->quiet_shutdown = mode;
3349 }
3350
3351 int SSL_CTX_get_quiet_shutdown(const SSL_CTX *ctx)
3352 {
3353     return (ctx->quiet_shutdown);
3354 }
3355
3356 void SSL_set_quiet_shutdown(SSL *s, int mode)
3357 {
3358     s->quiet_shutdown = mode;
3359 }
3360
3361 int SSL_get_quiet_shutdown(const SSL *s)
3362 {
3363     return (s->quiet_shutdown);
3364 }
3365
3366 void SSL_set_shutdown(SSL *s, int mode)
3367 {
3368     s->shutdown = mode;
3369 }
3370
3371 int SSL_get_shutdown(const SSL *s)
3372 {
3373     return (s->shutdown);
3374 }
3375
3376 int SSL_version(const SSL *s)
3377 {
3378     return (s->version);
3379 }
3380
3381 SSL_CTX *SSL_get_SSL_CTX(const SSL *ssl)
3382 {
3383     return (ssl->ctx);
3384 }
3385
3386 SSL_CTX *SSL_set_SSL_CTX(SSL *ssl, SSL_CTX *ctx)
3387 {
3388     CERT *new_cert;
3389     if (ssl->ctx == ctx)
3390         return ssl->ctx;
3391     if (ctx == NULL)
3392         ctx = ssl->initial_ctx;
3393     new_cert = ssl_cert_dup(ctx->cert);
3394     if (new_cert == NULL) {
3395         return NULL;
3396     }
3397     ssl_cert_free(ssl->cert);
3398     ssl->cert = new_cert;
3399
3400     /*
3401      * Program invariant: |sid_ctx| has fixed size (SSL_MAX_SID_CTX_LENGTH),
3402      * so setter APIs must prevent invalid lengths from entering the system.
3403      */
3404     OPENSSL_assert(ssl->sid_ctx_length <= sizeof(ssl->sid_ctx));
3405
3406     /*
3407      * If the session ID context matches that of the parent SSL_CTX,
3408      * inherit it from the new SSL_CTX as well. If however the context does
3409      * not match (i.e., it was set per-ssl with SSL_set_session_id_context),
3410      * leave it unchanged.
3411      */
3412     if ((ssl->ctx != NULL) &&
3413         (ssl->sid_ctx_length == ssl->ctx->sid_ctx_length) &&
3414         (memcmp(ssl->sid_ctx, ssl->ctx->sid_ctx, ssl->sid_ctx_length) == 0)) {
3415         ssl->sid_ctx_length = ctx->sid_ctx_length;
3416         memcpy(&ssl->sid_ctx, &ctx->sid_ctx, sizeof(ssl->sid_ctx));
3417     }
3418
3419     SSL_CTX_up_ref(ctx);
3420     SSL_CTX_free(ssl->ctx); /* decrement reference count */
3421     ssl->ctx = ctx;
3422
3423     return ssl->ctx;
3424 }
3425
3426 int SSL_CTX_set_default_verify_paths(SSL_CTX *ctx)
3427 {
3428     return (X509_STORE_set_default_paths(ctx->cert_store));
3429 }
3430
3431 int SSL_CTX_set_default_verify_dir(SSL_CTX *ctx)
3432 {
3433     X509_LOOKUP *lookup;
3434
3435     lookup = X509_STORE_add_lookup(ctx->cert_store, X509_LOOKUP_hash_dir());
3436     if (lookup == NULL)
3437         return 0;
3438     X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
3439
3440     /* Clear any errors if the default directory does not exist */
3441     ERR_clear_error();
3442
3443     return 1;
3444 }
3445
3446 int SSL_CTX_set_default_verify_file(SSL_CTX *ctx)
3447 {
3448     X509_LOOKUP *lookup;
3449
3450     lookup = X509_STORE_add_lookup(ctx->cert_store, X509_LOOKUP_file());
3451     if (lookup == NULL)
3452         return 0;
3453
3454     X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT);
3455
3456     /* Clear any errors if the default file does not exist */
3457     ERR_clear_error();
3458
3459     return 1;
3460 }
3461
3462 int SSL_CTX_load_verify_locations(SSL_CTX *ctx, const char *CAfile,
3463                                   const char *CApath)
3464 {
3465     return (X509_STORE_load_locations(ctx->cert_store, CAfile, CApath));
3466 }
3467
3468 void SSL_set_info_callback(SSL *ssl,
3469                            void (*cb) (const SSL *ssl, int type, int val))
3470 {
3471     ssl->info_callback = cb;
3472 }
3473
3474 /*
3475  * One compiler (Diab DCC) doesn't like argument names in returned function
3476  * pointer.
3477  */
3478 void (*SSL_get_info_callback(const SSL *ssl)) (const SSL * /* ssl */ ,
3479                                                int /* type */ ,
3480                                                int /* val */ ) {
3481     return ssl->info_callback;
3482 }
3483
3484 void SSL_set_verify_result(SSL *ssl, long arg)
3485 {
3486     ssl->verify_result = arg;
3487 }
3488
3489 long SSL_get_verify_result(const SSL *ssl)
3490 {
3491     return (ssl->verify_result);
3492 }
3493
3494 size_t SSL_get_client_random(const SSL *ssl, unsigned char *out, size_t outlen)
3495 {
3496     if (outlen == 0)
3497         return sizeof(ssl->s3->client_random);
3498     if (outlen > sizeof(ssl->s3->client_random))
3499         outlen = sizeof(ssl->s3->client_random);
3500     memcpy(out, ssl->s3->client_random, outlen);
3501     return outlen;
3502 }
3503
3504 size_t SSL_get_server_random(const SSL *ssl, unsigned char *out, size_t outlen)
3505 {
3506     if (outlen == 0)
3507         return sizeof(ssl->s3->server_random);
3508     if (outlen > sizeof(ssl->s3->server_random))
3509         outlen = sizeof(ssl->s3->server_random);
3510     memcpy(out, ssl->s3->server_random, outlen);
3511     return outlen;
3512 }
3513
3514 size_t SSL_SESSION_get_master_key(const SSL_SESSION *session,
3515                                unsigned char *out, size_t outlen)
3516 {
3517     if (session->master_key_length < 0) {
3518         /* Should never happen */
3519         return 0;
3520     }
3521     if (outlen == 0)
3522         return session->master_key_length;
3523     if (outlen > (size_t)session->master_key_length)
3524         outlen = session->master_key_length;
3525     memcpy(out, session->master_key, outlen);
3526     return outlen;
3527 }
3528
3529 int SSL_set_ex_data(SSL *s, int idx, void *arg)
3530 {
3531     return (CRYPTO_set_ex_data(&s->ex_data, idx, arg));
3532 }
3533
3534 void *SSL_get_ex_data(const SSL *s, int idx)
3535 {
3536     return (CRYPTO_get_ex_data(&s->ex_data, idx));
3537 }
3538
3539 int SSL_CTX_set_ex_data(SSL_CTX *s, int idx, void *arg)
3540 {
3541     return (CRYPTO_set_ex_data(&s->ex_data, idx, arg));
3542 }
3543
3544 void *SSL_CTX_get_ex_data(const SSL_CTX *s, int idx)
3545 {
3546     return (CRYPTO_get_ex_data(&s->ex_data, idx));
3547 }
3548
3549 int ssl_ok(SSL *s)
3550 {
3551     return (1);
3552 }
3553
3554 X509_STORE *SSL_CTX_get_cert_store(const SSL_CTX *ctx)
3555 {
3556     return (ctx->cert_store);
3557 }
3558
3559 void SSL_CTX_set_cert_store(SSL_CTX *ctx, X509_STORE *store)
3560 {
3561     X509_STORE_free(ctx->cert_store);
3562     ctx->cert_store = store;
3563 }
3564
3565 int SSL_want(const SSL *s)
3566 {
3567     return (s->rwstate);
3568 }
3569
3570 /**
3571  * \brief Set the callback for generating temporary DH keys.
3572  * \param ctx the SSL context.
3573  * \param dh the callback
3574  */
3575
3576 #ifndef OPENSSL_NO_DH
3577 void SSL_CTX_set_tmp_dh_callback(SSL_CTX *ctx,
3578                                  DH *(*dh) (SSL *ssl, int is_export,
3579                                             int keylength))
3580 {
3581     SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TMP_DH_CB, (void (*)(void))dh);
3582 }
3583
3584 void SSL_set_tmp_dh_callback(SSL *ssl, DH *(*dh) (SSL *ssl, int is_export,
3585                                                   int keylength))
3586 {
3587     SSL_callback_ctrl(ssl, SSL_CTRL_SET_TMP_DH_CB, (void (*)(void))dh);
3588 }
3589 #endif
3590
3591 #ifndef OPENSSL_NO_PSK
3592 int SSL_CTX_use_psk_identity_hint(SSL_CTX *ctx, const char *identity_hint)
3593 {
3594     if (identity_hint != NULL && strlen(identity_hint) > PSK_MAX_IDENTITY_LEN) {
3595         SSLerr(SSL_F_SSL_CTX_USE_PSK_IDENTITY_HINT,
3596                SSL_R_DATA_LENGTH_TOO_LONG);
3597         return 0;
3598     }
3599     OPENSSL_free(ctx->cert->psk_identity_hint);
3600     if (identity_hint != NULL) {
3601         ctx->cert->psk_identity_hint = OPENSSL_strdup(identity_hint);
3602         if (ctx->cert->psk_identity_hint == NULL)
3603             return 0;
3604     } else
3605         ctx->cert->psk_identity_hint = NULL;
3606     return 1;
3607 }
3608
3609 int SSL_use_psk_identity_hint(SSL *s, const char *identity_hint)
3610 {
3611     if (s == NULL)
3612         return 0;
3613
3614     if (identity_hint != NULL && strlen(identity_hint) > PSK_MAX_IDENTITY_LEN) {
3615         SSLerr(SSL_F_SSL_USE_PSK_IDENTITY_HINT, SSL_R_DATA_LENGTH_TOO_LONG);
3616         return 0;
3617     }
3618     OPENSSL_free(s->cert->psk_identity_hint);
3619     if (identity_hint != NULL) {
3620         s->cert->psk_identity_hint = OPENSSL_strdup(identity_hint);
3621         if (s->cert->psk_identity_hint == NULL)
3622             return 0;
3623     } else
3624         s->cert->psk_identity_hint = NULL;
3625     return 1;
3626 }
3627
3628 const char *SSL_get_psk_identity_hint(const SSL *s)
3629 {
3630     if (s == NULL || s->session == NULL)
3631         return NULL;
3632     return (s->session->psk_identity_hint);
3633 }
3634
3635 const char *SSL_get_psk_identity(const SSL *s)
3636 {
3637     if (s == NULL || s->session == NULL)
3638         return NULL;
3639     return (s->session->psk_identity);
3640 }
3641
3642 void SSL_set_psk_client_callback(SSL *s,
3643                                  unsigned int (*cb) (SSL *ssl,
3644                                                      const char *hint,
3645                                                      char *identity,
3646                                                      unsigned int
3647                                                      max_identity_len,
3648                                                      unsigned char *psk,
3649                                                      unsigned int
3650                                                      max_psk_len))
3651 {
3652     s->psk_client_callback = cb;
3653 }
3654
3655 void SSL_CTX_set_psk_client_callback(SSL_CTX *ctx,
3656                                      unsigned int (*cb) (SSL *ssl,
3657                                                          const char *hint,
3658                                                          char *identity,
3659                                                          unsigned int
3660                                                          max_identity_len,
3661                                                          unsigned char *psk,
3662                                                          unsigned int
3663                                                          max_psk_len))
3664 {
3665     ctx->psk_client_callback = cb;
3666 }
3667
3668 void SSL_set_psk_server_callback(SSL *s,
3669                                  unsigned int (*cb) (SSL *ssl,
3670                                                      const char *identity,
3671                                                      unsigned char *psk,
3672                                                      unsigned int
3673                                                      max_psk_len))
3674 {
3675     s->psk_server_callback = cb;
3676 }
3677
3678 void SSL_CTX_set_psk_server_callback(SSL_CTX *ctx,
3679                                      unsigned int (*cb) (SSL *ssl,
3680                                                          const char *identity,
3681                                                          unsigned char *psk,
3682                                                          unsigned int
3683                                                          max_psk_len))
3684 {
3685     ctx->psk_server_callback = cb;
3686 }
3687 #endif
3688
3689 void SSL_CTX_set_msg_callback(SSL_CTX *ctx,
3690                               void (*cb) (int write_p, int version,
3691                                           int content_type, const void *buf,
3692                                           size_t len, SSL *ssl, void *arg))
3693 {
3694     SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_MSG_CALLBACK, (void (*)(void))cb);
3695 }
3696
3697 void SSL_set_msg_callback(SSL *ssl,
3698                           void (*cb) (int write_p, int version,
3699                                       int content_type, const void *buf,
3700                                       size_t len, SSL *ssl, void *arg))
3701 {
3702     SSL_callback_ctrl(ssl, SSL_CTRL_SET_MSG_CALLBACK, (void (*)(void))cb);
3703 }
3704
3705 void SSL_CTX_set_not_resumable_session_callback(SSL_CTX *ctx,
3706                                                 int (*cb) (SSL *ssl,
3707                                                            int
3708                                                            is_forward_secure))
3709 {
3710     SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_NOT_RESUMABLE_SESS_CB,
3711                           (void (*)(void))cb);
3712 }
3713
3714 void SSL_set_not_resumable_session_callback(SSL *ssl,
3715                                             int (*cb) (SSL *ssl,
3716                                                        int is_forward_secure))
3717 {
3718     SSL_callback_ctrl(ssl, SSL_CTRL_SET_NOT_RESUMABLE_SESS_CB,
3719                       (void (*)(void))cb);
3720 }
3721
3722 /*
3723  * Allocates new EVP_MD_CTX and sets pointer to it into given pointer
3724  * vairable, freeing EVP_MD_CTX previously stored in that variable, if any.
3725  * If EVP_MD pointer is passed, initializes ctx with this md Returns newly
3726  * allocated ctx;
3727  */
3728
3729 EVP_MD_CTX *ssl_replace_hash(EVP_MD_CTX **hash, const EVP_MD *md)
3730 {
3731     ssl_clear_hash_ctx(hash);
3732     *hash = EVP_MD_CTX_new();
3733     if (*hash == NULL || (md && EVP_DigestInit_ex(*hash, md, NULL) <= 0)) {
3734         EVP_MD_CTX_free(*hash);
3735         *hash = NULL;
3736         return NULL;
3737     }
3738     return *hash;
3739 }
3740
3741 void ssl_clear_hash_ctx(EVP_MD_CTX **hash)
3742 {
3743
3744     if (*hash)
3745         EVP_MD_CTX_free(*hash);
3746     *hash = NULL;
3747 }
3748
3749 /* Retrieve handshake hashes */
3750 int ssl_handshake_hash(SSL *s, unsigned char *out, int outlen)
3751 {
3752     EVP_MD_CTX *ctx = NULL;
3753     EVP_MD_CTX *hdgst = s->s3->handshake_dgst;
3754     int ret = EVP_MD_CTX_size(hdgst);
3755     if (ret < 0 || ret > outlen) {
3756         ret = 0;
3757         goto err;
3758     }
3759     ctx = EVP_MD_CTX_new();
3760     if (ctx == NULL) {
3761         ret = 0;
3762         goto err;
3763     }
3764     if (!EVP_MD_CTX_copy_ex(ctx, hdgst)
3765         || EVP_DigestFinal_ex(ctx, out, NULL) <= 0)
3766         ret = 0;
3767  err:
3768     EVP_MD_CTX_free(ctx);
3769     return ret;
3770 }
3771
3772 int SSL_session_reused(SSL *s)
3773 {
3774     return s->hit;
3775 }
3776
3777 int SSL_is_server(SSL *s)
3778 {
3779     return s->server;
3780 }
3781
3782 #if OPENSSL_API_COMPAT < 0x10100000L
3783 void SSL_set_debug(SSL *s, int debug)
3784 {
3785     /* Old function was do-nothing anyway... */
3786     (void)s;
3787     (void)debug;
3788 }
3789 #endif
3790
3791
3792 void SSL_set_security_level(SSL *s, int level)
3793 {
3794     s->cert->sec_level = level;
3795 }
3796
3797 int SSL_get_security_level(const SSL *s)
3798 {
3799     return s->cert->sec_level;
3800 }
3801
3802 void SSL_set_security_callback(SSL *s,
3803                                int (*cb) (const SSL *s, const SSL_CTX *ctx, int op,
3804                                           int bits, int nid, void *other,
3805                                           void *ex))
3806 {
3807     s->cert->sec_cb = cb;
3808 }
3809
3810 int (*SSL_get_security_callback(const SSL *s)) (const SSL *s, const SSL_CTX *ctx, int op,
3811                                                 int bits, int nid,
3812                                                 void *other, void *ex) {
3813     return s->cert->sec_cb;
3814 }
3815
3816 void SSL_set0_security_ex_data(SSL *s, void *ex)
3817 {
3818     s->cert->sec_ex = ex;
3819 }
3820
3821 void *SSL_get0_security_ex_data(const SSL *s)
3822 {
3823     return s->cert->sec_ex;
3824 }
3825
3826 void SSL_CTX_set_security_level(SSL_CTX *ctx, int level)
3827 {
3828     ctx->cert->sec_level = level;
3829 }
3830
3831 int SSL_CTX_get_security_level(const SSL_CTX *ctx)
3832 {
3833     return ctx->cert->sec_level;
3834 }
3835
3836 void SSL_CTX_set_security_callback(SSL_CTX *ctx,
3837                                    int (*cb) (const SSL *s, const SSL_CTX *ctx, int op,
3838                                               int bits, int nid, void *other,
3839                                               void *ex))
3840 {
3841     ctx->cert->sec_cb = cb;
3842 }
3843
3844 int (*SSL_CTX_get_security_callback(const SSL_CTX *ctx)) (const SSL *s,
3845                                                           const SSL_CTX *ctx,
3846                                                           int op, int bits,
3847                                                           int nid,
3848                                                           void *other,
3849                                                           void *ex) {
3850     return ctx->cert->sec_cb;
3851 }
3852
3853 void SSL_CTX_set0_security_ex_data(SSL_CTX *ctx, void *ex)
3854 {
3855     ctx->cert->sec_ex = ex;
3856 }
3857
3858 void *SSL_CTX_get0_security_ex_data(const SSL_CTX *ctx)
3859 {
3860     return ctx->cert->sec_ex;
3861 }
3862
3863
3864 /*
3865  * Get/Set/Clear options in SSL_CTX or SSL, formerly macros, now functions that
3866  * can return unsigned long, instead of the generic long return value from the
3867  * control interface.
3868  */
3869 unsigned long SSL_CTX_get_options(const SSL_CTX *ctx)
3870 {
3871     return ctx->options;
3872 }
3873 unsigned long SSL_get_options(const SSL* s)
3874 {
3875     return s->options;
3876 }
3877 unsigned long SSL_CTX_set_options(SSL_CTX *ctx, unsigned long op)
3878 {
3879     return ctx->options |= op;
3880 }
3881 unsigned long SSL_set_options(SSL *s, unsigned long op)
3882 {
3883     return s->options |= op;
3884 }
3885 unsigned long SSL_CTX_clear_options(SSL_CTX *ctx, unsigned long op)
3886 {
3887     return ctx->options &= ~op;
3888 }
3889 unsigned long SSL_clear_options(SSL *s, unsigned long op)
3890 {
3891     return s->options &= ~op;
3892 }
3893
3894 STACK_OF(X509) *SSL_get0_verified_chain(const SSL *s)
3895 {
3896     return s->verified_chain;
3897 }
3898
3899 IMPLEMENT_OBJ_BSEARCH_GLOBAL_CMP_FN(SSL_CIPHER, SSL_CIPHER, ssl_cipher_id);
3900
3901 #ifndef OPENSSL_NO_CT
3902
3903 /*
3904  * Moves SCTs from the |src| stack to the |dst| stack.
3905  * The source of each SCT will be set to |origin|.
3906  * If |dst| points to a NULL pointer, a new stack will be created and owned by
3907  * the caller.
3908  * Returns the number of SCTs moved, or a negative integer if an error occurs.
3909  */
3910 static int ct_move_scts(STACK_OF(SCT) **dst, STACK_OF(SCT) *src, sct_source_t origin)
3911 {
3912     int scts_moved = 0;
3913     SCT *sct = NULL;
3914
3915     if (*dst == NULL) {
3916         *dst = sk_SCT_new_null();
3917         if (*dst == NULL) {
3918             SSLerr(SSL_F_CT_MOVE_SCTS, ERR_R_MALLOC_FAILURE);
3919             goto err;
3920         }
3921     }
3922
3923     while ((sct = sk_SCT_pop(src)) != NULL) {
3924         if (SCT_set_source(sct, origin) != 1)
3925             goto err;
3926
3927         if (sk_SCT_push(*dst, sct) <= 0)
3928             goto err;
3929         scts_moved += 1;
3930     }
3931
3932     return scts_moved;
3933 err:
3934     if (sct != NULL)
3935         sk_SCT_push(src, sct); /* Put the SCT back */
3936     return scts_moved;
3937 }
3938
3939 /*
3940 * Look for data collected during ServerHello and parse if found.
3941 * Return 1 on success, 0 on failure.
3942 */
3943 static int ct_extract_tls_extension_scts(SSL *s)
3944 {
3945     int scts_extracted = 0;
3946
3947     if (s->tlsext_scts != NULL) {
3948         const unsigned char *p = s->tlsext_scts;
3949         STACK_OF(SCT) *scts = o2i_SCT_LIST(NULL, &p, s->tlsext_scts_len);
3950
3951         scts_extracted = ct_move_scts(&s->scts, scts, SCT_SOURCE_TLS_EXTENSION);
3952
3953         SCT_LIST_free(scts);
3954     }
3955
3956     return scts_extracted;
3957 }
3958
3959 /*
3960  * Checks for an OCSP response and then attempts to extract any SCTs found if it
3961  * contains an SCT X509 extension. They will be stored in |s->scts|.
3962  * Returns:
3963  * - The number of SCTs extracted, assuming an OCSP response exists.
3964  * - 0 if no OCSP response exists or it contains no SCTs.
3965  * - A negative integer if an error occurs.
3966  */
3967 static int ct_extract_ocsp_response_scts(SSL *s)
3968 {
3969 #ifndef OPENSSL_NO_OCSP
3970     int scts_extracted = 0;
3971     const unsigned char *p;
3972     OCSP_BASICRESP *br = NULL;
3973     OCSP_RESPONSE *rsp = NULL;
3974     STACK_OF(SCT) *scts = NULL;
3975     int i;
3976
3977     if (s->tlsext_ocsp_resp == NULL || s->tlsext_ocsp_resplen == 0)
3978         goto err;
3979
3980     p = s->tlsext_ocsp_resp;
3981     rsp = d2i_OCSP_RESPONSE(NULL, &p, s->tlsext_ocsp_resplen);
3982     if (rsp == NULL)
3983         goto err;
3984
3985     br = OCSP_response_get1_basic(rsp);
3986     if (br == NULL)
3987         goto err;
3988
3989     for (i = 0; i < OCSP_resp_count(br); ++i) {
3990         OCSP_SINGLERESP *single = OCSP_resp_get0(br, i);
3991
3992         if (single == NULL)
3993             continue;
3994
3995         scts = OCSP_SINGLERESP_get1_ext_d2i(single, NID_ct_cert_scts, NULL, NULL);
3996         scts_extracted = ct_move_scts(&s->scts, scts,
3997                                       SCT_SOURCE_OCSP_STAPLED_RESPONSE);
3998         if (scts_extracted < 0)
3999             goto err;
4000     }
4001 err:
4002     SCT_LIST_free(scts);
4003     OCSP_BASICRESP_free(br);
4004     OCSP_RESPONSE_free(rsp);
4005     return scts_extracted;
4006 #else
4007     /* Behave as if no OCSP response exists */
4008     return 0;
4009 #endif
4010 }
4011
4012 /*
4013  * Attempts to extract SCTs from the peer certificate.
4014  * Return the number of SCTs extracted, or a negative integer if an error
4015  * occurs.
4016  */
4017 static int ct_extract_x509v3_extension_scts(SSL *s)
4018 {
4019     int scts_extracted = 0;
4020     X509 *cert = s->session != NULL ? s->session->peer : NULL;
4021
4022     if (cert != NULL) {
4023         STACK_OF(SCT) *scts =
4024             X509_get_ext_d2i(cert, NID_ct_precert_scts, NULL, NULL);
4025
4026         scts_extracted =
4027             ct_move_scts(&s->scts, scts, SCT_SOURCE_X509V3_EXTENSION);
4028
4029         SCT_LIST_free(scts);
4030     }
4031
4032     return scts_extracted;
4033 }
4034
4035 /*
4036  * Attempts to find all received SCTs by checking TLS extensions, the OCSP
4037  * response (if it exists) and X509v3 extensions in the certificate.
4038  * Returns NULL if an error occurs.
4039  */
4040 const STACK_OF(SCT) *SSL_get0_peer_scts(SSL *s)
4041 {
4042     if (!s->scts_parsed) {
4043         if (ct_extract_tls_extension_scts(s) < 0 ||
4044             ct_extract_ocsp_response_scts(s) < 0 ||
4045             ct_extract_x509v3_extension_scts(s) < 0)
4046             goto err;
4047
4048         s->scts_parsed = 1;
4049     }
4050     return s->scts;
4051 err:
4052     return NULL;
4053 }
4054
4055 static int ct_permissive(const CT_POLICY_EVAL_CTX *ctx,
4056                          const STACK_OF(SCT) *scts, void *unused_arg)
4057 {
4058     return 1;
4059 }
4060
4061 static int ct_strict(const CT_POLICY_EVAL_CTX *ctx,
4062                      const STACK_OF(SCT) *scts, void *unused_arg)
4063 {
4064     int count = scts != NULL ? sk_SCT_num(scts) : 0;
4065     int i;
4066
4067     for (i = 0; i < count; ++i) {
4068         SCT *sct = sk_SCT_value(scts, i);
4069         int status = SCT_get_validation_status(sct);
4070
4071         if (status == SCT_VALIDATION_STATUS_VALID)
4072             return 1;
4073     }
4074     SSLerr(SSL_F_CT_STRICT, SSL_R_NO_VALID_SCTS);
4075     return 0;
4076 }
4077
4078 int SSL_set_ct_validation_callback(SSL *s, ssl_ct_validation_cb callback,
4079                                    void *arg)
4080 {
4081     /*
4082      * Since code exists that uses the custom extension handler for CT, look
4083      * for this and throw an error if they have already registered to use CT.
4084      */
4085     if (callback != NULL && SSL_CTX_has_client_custom_ext(s->ctx,
4086             TLSEXT_TYPE_signed_certificate_timestamp)) {
4087         SSLerr(SSL_F_SSL_SET_CT_VALIDATION_CALLBACK,
4088                SSL_R_CUSTOM_EXT_HANDLER_ALREADY_INSTALLED);
4089         return 0;
4090     }
4091
4092     if (callback != NULL) {
4093         /* If we are validating CT, then we MUST accept SCTs served via OCSP */
4094         if (!SSL_set_tlsext_status_type(s, TLSEXT_STATUSTYPE_ocsp))
4095             return 0;
4096     }
4097
4098     s->ct_validation_callback = callback;
4099     s->ct_validation_callback_arg = arg;
4100
4101     return 1;
4102 }
4103
4104 int SSL_CTX_set_ct_validation_callback(SSL_CTX *ctx,
4105                                        ssl_ct_validation_cb callback,
4106                                        void *arg)
4107 {
4108     /*
4109      * Since code exists that uses the custom extension handler for CT, look for
4110      * this and throw an error if they have already registered to use CT.
4111      */
4112     if (callback != NULL && SSL_CTX_has_client_custom_ext(ctx,
4113             TLSEXT_TYPE_signed_certificate_timestamp)) {
4114         SSLerr(SSL_F_SSL_CTX_SET_CT_VALIDATION_CALLBACK,
4115                SSL_R_CUSTOM_EXT_HANDLER_ALREADY_INSTALLED);
4116         return 0;
4117     }
4118
4119     ctx->ct_validation_callback = callback;
4120     ctx->ct_validation_callback_arg = arg;
4121     return 1;
4122 }
4123
4124 int SSL_ct_is_enabled(const SSL *s)
4125 {
4126     return s->ct_validation_callback != NULL;
4127 }
4128
4129 int SSL_CTX_ct_is_enabled(const SSL_CTX *ctx)
4130 {
4131     return ctx->ct_validation_callback != NULL;
4132 }
4133
4134 int ssl_validate_ct(SSL *s)
4135 {
4136     int ret = 0;
4137     X509 *cert = s->session != NULL ? s->session->peer : NULL;
4138     X509 *issuer;
4139     SSL_DANE *dane = &s->dane;
4140     CT_POLICY_EVAL_CTX *ctx = NULL;
4141     const STACK_OF(SCT) *scts;
4142
4143     /*
4144      * If no callback is set, the peer is anonymous, or its chain is invalid,
4145      * skip SCT validation - just return success.  Applications that continue
4146      * handshakes without certificates, with unverified chains, or pinned leaf
4147      * certificates are outside the scope of the WebPKI and CT.
4148      *
4149      * The above exclusions notwithstanding the vast majority of peers will
4150      * have rather ordinary certificate chains validated by typical
4151      * applications that perform certificate verification and therefore will
4152      * process SCTs when enabled.
4153      */
4154     if (s->ct_validation_callback == NULL || cert == NULL ||
4155         s->verify_result != X509_V_OK ||
4156         s->verified_chain == NULL ||
4157         sk_X509_num(s->verified_chain) <= 1)
4158         return 1;
4159
4160     /*
4161      * CT not applicable for chains validated via DANE-TA(2) or DANE-EE(3)
4162      * trust-anchors.  See https://tools.ietf.org/html/rfc7671#section-4.2
4163      */
4164     if (DANETLS_ENABLED(dane) && dane->mtlsa != NULL) {
4165         switch (dane->mtlsa->usage) {
4166         case DANETLS_USAGE_DANE_TA:
4167         case DANETLS_USAGE_DANE_EE:
4168             return 1;
4169         }
4170     }
4171
4172     ctx = CT_POLICY_EVAL_CTX_new();
4173     if (ctx == NULL) {
4174         SSLerr(SSL_F_SSL_VALIDATE_CT, ERR_R_MALLOC_FAILURE);
4175         goto end;
4176     }
4177
4178     issuer = sk_X509_value(s->verified_chain, 1);
4179     CT_POLICY_EVAL_CTX_set0_cert(ctx, cert);
4180     CT_POLICY_EVAL_CTX_set0_issuer(ctx, issuer);
4181     CT_POLICY_EVAL_CTX_set0_log_store(ctx, s->ctx->ctlog_store);
4182
4183     scts = SSL_get0_peer_scts(s);
4184
4185     /*
4186      * This function returns success (> 0) only when all the SCTs are valid, 0
4187      * when some are invalid, and < 0 on various internal errors (out of
4188      * memory, etc.).  Having some, or even all, invalid SCTs is not sufficient
4189      * reason to abort the handshake, that decision is up to the callback.
4190      * Therefore, we error out only in the unexpected case that the return
4191      * value is negative.
4192      *
4193      * XXX: One might well argue that the return value of this function is an
4194      * unforunate design choice.  Its job is only to determine the validation
4195      * status of each of the provided SCTs.  So long as it correctly separates
4196      * the wheat from the chaff it should return success.  Failure in this case
4197      * ought to correspond to an inability to carry out its duties.
4198      */
4199     if (SCT_LIST_validate(scts, ctx) < 0) {
4200         SSLerr(SSL_F_SSL_VALIDATE_CT, SSL_R_SCT_VERIFICATION_FAILED);
4201         goto end;
4202     }
4203
4204     ret = s->ct_validation_callback(ctx, scts, s->ct_validation_callback_arg);
4205     if (ret < 0)
4206         ret = 0; /* This function returns 0 on failure */
4207
4208 end:
4209     CT_POLICY_EVAL_CTX_free(ctx);
4210     return ret;
4211 }
4212
4213 int SSL_CTX_enable_ct(SSL_CTX *ctx, int validation_mode)
4214 {
4215     switch (validation_mode) {
4216     default:
4217         SSLerr(SSL_F_SSL_CTX_ENABLE_CT, SSL_R_INVALID_CT_VALIDATION_TYPE);
4218         return 0;
4219     case SSL_CT_VALIDATION_PERMISSIVE:
4220         return SSL_CTX_set_ct_validation_callback(ctx, ct_permissive, NULL);
4221     case SSL_CT_VALIDATION_STRICT:
4222         return SSL_CTX_set_ct_validation_callback(ctx, ct_strict, NULL);
4223     }
4224 }
4225
4226 int SSL_enable_ct(SSL *s, int validation_mode)
4227 {
4228     switch (validation_mode) {
4229     default:
4230         SSLerr(SSL_F_SSL_ENABLE_CT, SSL_R_INVALID_CT_VALIDATION_TYPE);
4231         return 0;
4232     case SSL_CT_VALIDATION_PERMISSIVE:
4233         return SSL_set_ct_validation_callback(s, ct_permissive, NULL);
4234     case SSL_CT_VALIDATION_STRICT:
4235         return SSL_set_ct_validation_callback(s, ct_strict, NULL);
4236     }
4237 }
4238
4239 int SSL_CTX_set_default_ctlog_list_file(SSL_CTX *ctx)
4240 {
4241     return CTLOG_STORE_load_default_file(ctx->ctlog_store);
4242 }
4243
4244 int SSL_CTX_set_ctlog_list_file(SSL_CTX *ctx, const char *path)
4245 {
4246     return CTLOG_STORE_load_file(ctx->ctlog_store, path);
4247 }
4248
4249 void SSL_CTX_set0_ctlog_store(SSL_CTX *ctx, CTLOG_STORE *logs)
4250 {
4251     CTLOG_STORE_free(ctx->ctlog_store);
4252     ctx->ctlog_store = logs;
4253 }
4254
4255 const CTLOG_STORE *SSL_CTX_get0_ctlog_store(const SSL_CTX *ctx)
4256 {
4257     return ctx->ctlog_store;
4258 }
4259
4260 #endif