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