Remove support for SSL_{CTX_}set_tmp_ecdh_callback().
[openssl.git] / ssl / ssl_cert.c
1 /*
2  * ! \file ssl/ssl_cert.c
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 #include <stdio.h>
120
121 #include "e_os.h"
122 #ifndef NO_SYS_TYPES_H
123 # include <sys/types.h>
124 #endif
125
126 #include "internal/o_dir.h"
127 #include <openssl/objects.h>
128 #include <openssl/bio.h>
129 #include <openssl/pem.h>
130 #include <openssl/x509v3.h>
131 #ifndef OPENSSL_NO_DH
132 # include <openssl/dh.h>
133 #endif
134 #include <openssl/bn.h>
135 #include "ssl_locl.h"
136
137 static int ssl_security_default_callback(SSL *s, SSL_CTX *ctx, int op,
138                                          int bits, int nid, void *other,
139                                          void *ex);
140
141 int SSL_get_ex_data_X509_STORE_CTX_idx(void)
142 {
143     static volatile int ssl_x509_store_ctx_idx = -1;
144     int got_write_lock = 0;
145
146     CRYPTO_r_lock(CRYPTO_LOCK_SSL_CTX);
147
148     if (ssl_x509_store_ctx_idx < 0) {
149         CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX);
150         CRYPTO_w_lock(CRYPTO_LOCK_SSL_CTX);
151         got_write_lock = 1;
152
153         if (ssl_x509_store_ctx_idx < 0) {
154             ssl_x509_store_ctx_idx =
155                 X509_STORE_CTX_get_ex_new_index(0, "SSL for verify callback",
156                                                 NULL, NULL, NULL);
157         }
158     }
159
160     if (got_write_lock)
161         CRYPTO_w_unlock(CRYPTO_LOCK_SSL_CTX);
162     else
163         CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX);
164
165     return ssl_x509_store_ctx_idx;
166 }
167
168 CERT *ssl_cert_new(void)
169 {
170     CERT *ret = OPENSSL_zalloc(sizeof(*ret));
171
172     if (ret == NULL) {
173         SSLerr(SSL_F_SSL_CERT_NEW, ERR_R_MALLOC_FAILURE);
174         return (NULL);
175     }
176
177     ret->key = &(ret->pkeys[SSL_PKEY_RSA_ENC]);
178     ret->references = 1;
179     ret->sec_cb = ssl_security_default_callback;
180     ret->sec_level = OPENSSL_TLS_SECURITY_LEVEL;
181     ret->sec_ex = NULL;
182     return (ret);
183 }
184
185 CERT *ssl_cert_dup(CERT *cert)
186 {
187     CERT *ret = OPENSSL_zalloc(sizeof(*ret));
188     int i;
189
190     if (ret == NULL) {
191         SSLerr(SSL_F_SSL_CERT_DUP, ERR_R_MALLOC_FAILURE);
192         return (NULL);
193     }
194
195     ret->references = 1;
196     ret->key = &ret->pkeys[cert->key - cert->pkeys];
197
198 #ifndef OPENSSL_NO_RSA
199     if (cert->rsa_tmp != NULL) {
200         RSA_up_ref(cert->rsa_tmp);
201         ret->rsa_tmp = cert->rsa_tmp;
202     }
203     ret->rsa_tmp_cb = cert->rsa_tmp_cb;
204 #endif
205
206 #ifndef OPENSSL_NO_DH
207     if (cert->dh_tmp != NULL) {
208         ret->dh_tmp = DHparams_dup(cert->dh_tmp);
209         if (ret->dh_tmp == NULL) {
210             SSLerr(SSL_F_SSL_CERT_DUP, ERR_R_DH_LIB);
211             goto err;
212         }
213         if (cert->dh_tmp->priv_key) {
214             BIGNUM *b = BN_dup(cert->dh_tmp->priv_key);
215             if (!b) {
216                 SSLerr(SSL_F_SSL_CERT_DUP, ERR_R_BN_LIB);
217                 goto err;
218             }
219             ret->dh_tmp->priv_key = b;
220         }
221         if (cert->dh_tmp->pub_key) {
222             BIGNUM *b = BN_dup(cert->dh_tmp->pub_key);
223             if (!b) {
224                 SSLerr(SSL_F_SSL_CERT_DUP, ERR_R_BN_LIB);
225                 goto err;
226             }
227             ret->dh_tmp->pub_key = b;
228         }
229     }
230     ret->dh_tmp_cb = cert->dh_tmp_cb;
231     ret->dh_tmp_auto = cert->dh_tmp_auto;
232 #endif
233
234 #ifndef OPENSSL_NO_EC
235     if (cert->ecdh_tmp) {
236         ret->ecdh_tmp = EC_KEY_dup(cert->ecdh_tmp);
237         if (ret->ecdh_tmp == NULL) {
238             SSLerr(SSL_F_SSL_CERT_DUP, ERR_R_EC_LIB);
239             goto err;
240         }
241     }
242     ret->ecdh_tmp_auto = cert->ecdh_tmp_auto;
243 #endif
244
245     for (i = 0; i < SSL_PKEY_NUM; i++) {
246         CERT_PKEY *cpk = cert->pkeys + i;
247         CERT_PKEY *rpk = ret->pkeys + i;
248         if (cpk->x509 != NULL) {
249             rpk->x509 = cpk->x509;
250             X509_up_ref(rpk->x509);
251         }
252
253         if (cpk->privatekey != NULL) {
254             rpk->privatekey = cpk->privatekey;
255             CRYPTO_add(&cpk->privatekey->references, 1, CRYPTO_LOCK_EVP_PKEY);
256         }
257
258         if (cpk->chain) {
259             rpk->chain = X509_chain_up_ref(cpk->chain);
260             if (!rpk->chain) {
261                 SSLerr(SSL_F_SSL_CERT_DUP, ERR_R_MALLOC_FAILURE);
262                 goto err;
263             }
264         }
265         if (cert->pkeys[i].serverinfo != NULL) {
266             /* Just copy everything. */
267             ret->pkeys[i].serverinfo =
268                 OPENSSL_malloc(cert->pkeys[i].serverinfo_length);
269             if (ret->pkeys[i].serverinfo == NULL) {
270                 SSLerr(SSL_F_SSL_CERT_DUP, ERR_R_MALLOC_FAILURE);
271                 goto err;
272             }
273             ret->pkeys[i].serverinfo_length =
274                 cert->pkeys[i].serverinfo_length;
275             memcpy(ret->pkeys[i].serverinfo,
276                    cert->pkeys[i].serverinfo,
277                    cert->pkeys[i].serverinfo_length);
278         }
279     }
280
281     /* Configured sigalgs copied across */
282     if (cert->conf_sigalgs) {
283         ret->conf_sigalgs = OPENSSL_malloc(cert->conf_sigalgslen);
284         if (ret->conf_sigalgs == NULL)
285             goto err;
286         memcpy(ret->conf_sigalgs, cert->conf_sigalgs, cert->conf_sigalgslen);
287         ret->conf_sigalgslen = cert->conf_sigalgslen;
288     } else
289         ret->conf_sigalgs = NULL;
290
291     if (cert->client_sigalgs) {
292         ret->client_sigalgs = OPENSSL_malloc(cert->client_sigalgslen);
293         if (ret->client_sigalgs == NULL)
294             goto err;
295         memcpy(ret->client_sigalgs, cert->client_sigalgs,
296                cert->client_sigalgslen);
297         ret->client_sigalgslen = cert->client_sigalgslen;
298     } else
299         ret->client_sigalgs = NULL;
300     /* Shared sigalgs also NULL */
301     ret->shared_sigalgs = NULL;
302     /* Copy any custom client certificate types */
303     if (cert->ctypes) {
304         ret->ctypes = OPENSSL_malloc(cert->ctype_num);
305         if (ret->ctypes == NULL)
306             goto err;
307         memcpy(ret->ctypes, cert->ctypes, cert->ctype_num);
308         ret->ctype_num = cert->ctype_num;
309     }
310
311     ret->cert_flags = cert->cert_flags;
312
313     ret->cert_cb = cert->cert_cb;
314     ret->cert_cb_arg = cert->cert_cb_arg;
315
316     if (cert->verify_store) {
317         CRYPTO_add(&cert->verify_store->references, 1,
318                    CRYPTO_LOCK_X509_STORE);
319         ret->verify_store = cert->verify_store;
320     }
321
322     if (cert->chain_store) {
323         CRYPTO_add(&cert->chain_store->references, 1, CRYPTO_LOCK_X509_STORE);
324         ret->chain_store = cert->chain_store;
325     }
326
327     ret->sec_cb = cert->sec_cb;
328     ret->sec_level = cert->sec_level;
329     ret->sec_ex = cert->sec_ex;
330
331     if (!custom_exts_copy(&ret->cli_ext, &cert->cli_ext))
332         goto err;
333     if (!custom_exts_copy(&ret->srv_ext, &cert->srv_ext))
334         goto err;
335 #ifndef OPENSSL_NO_PSK
336     if (cert->psk_identity_hint) {
337         ret->psk_identity_hint = BUF_strdup(cert->psk_identity_hint);
338         if (ret->psk_identity_hint == NULL)
339             goto err;
340     }
341 #endif
342     return (ret);
343
344  err:
345     ssl_cert_free(ret);
346
347     return NULL;
348 }
349
350 /* Free up and clear all certificates and chains */
351
352 void ssl_cert_clear_certs(CERT *c)
353 {
354     int i;
355     if (c == NULL)
356         return;
357     for (i = 0; i < SSL_PKEY_NUM; i++) {
358         CERT_PKEY *cpk = c->pkeys + i;
359         X509_free(cpk->x509);
360         cpk->x509 = NULL;
361         EVP_PKEY_free(cpk->privatekey);
362         cpk->privatekey = NULL;
363         sk_X509_pop_free(cpk->chain, X509_free);
364         cpk->chain = NULL;
365         OPENSSL_free(cpk->serverinfo);
366         cpk->serverinfo = NULL;
367         cpk->serverinfo_length = 0;
368     }
369 }
370
371 void ssl_cert_free(CERT *c)
372 {
373     int i;
374
375     if (c == NULL)
376         return;
377
378     i = CRYPTO_add(&c->references, -1, CRYPTO_LOCK_SSL_CERT);
379 #ifdef REF_PRINT
380     REF_PRINT("CERT", c);
381 #endif
382     if (i > 0)
383         return;
384 #ifdef REF_CHECK
385     if (i < 0) {
386         fprintf(stderr, "ssl_cert_free, bad reference count\n");
387         abort();                /* ok */
388     }
389 #endif
390
391 #ifndef OPENSSL_NO_RSA
392     RSA_free(c->rsa_tmp);
393 #endif
394 #ifndef OPENSSL_NO_DH
395     DH_free(c->dh_tmp);
396 #endif
397 #ifndef OPENSSL_NO_EC
398     EC_KEY_free(c->ecdh_tmp);
399 #endif
400
401     ssl_cert_clear_certs(c);
402     OPENSSL_free(c->conf_sigalgs);
403     OPENSSL_free(c->client_sigalgs);
404     OPENSSL_free(c->shared_sigalgs);
405     OPENSSL_free(c->ctypes);
406     X509_STORE_free(c->verify_store);
407     X509_STORE_free(c->chain_store);
408     custom_exts_free(&c->cli_ext);
409     custom_exts_free(&c->srv_ext);
410 #ifndef OPENSSL_NO_PSK
411     OPENSSL_free(c->psk_identity_hint);
412 #endif
413     OPENSSL_free(c);
414 }
415
416 int ssl_cert_set0_chain(SSL *s, SSL_CTX *ctx, STACK_OF(X509) *chain)
417 {
418     int i, r;
419     CERT_PKEY *cpk = s ? s->cert->key : ctx->cert->key;
420     if (!cpk)
421         return 0;
422     sk_X509_pop_free(cpk->chain, X509_free);
423     for (i = 0; i < sk_X509_num(chain); i++) {
424         r = ssl_security_cert(s, ctx, sk_X509_value(chain, i), 0, 0);
425         if (r != 1) {
426             SSLerr(SSL_F_SSL_CERT_SET0_CHAIN, r);
427             return 0;
428         }
429     }
430     cpk->chain = chain;
431     return 1;
432 }
433
434 int ssl_cert_set1_chain(SSL *s, SSL_CTX *ctx, STACK_OF(X509) *chain)
435 {
436     STACK_OF(X509) *dchain;
437     if (!chain)
438         return ssl_cert_set0_chain(s, ctx, NULL);
439     dchain = X509_chain_up_ref(chain);
440     if (!dchain)
441         return 0;
442     if (!ssl_cert_set0_chain(s, ctx, dchain)) {
443         sk_X509_pop_free(dchain, X509_free);
444         return 0;
445     }
446     return 1;
447 }
448
449 int ssl_cert_add0_chain_cert(SSL *s, SSL_CTX *ctx, X509 *x)
450 {
451     int r;
452     CERT_PKEY *cpk = s ? s->cert->key : ctx->cert->key;
453     if (!cpk)
454         return 0;
455     r = ssl_security_cert(s, ctx, x, 0, 0);
456     if (r != 1) {
457         SSLerr(SSL_F_SSL_CERT_ADD0_CHAIN_CERT, r);
458         return 0;
459     }
460     if (!cpk->chain)
461         cpk->chain = sk_X509_new_null();
462     if (!cpk->chain || !sk_X509_push(cpk->chain, x))
463         return 0;
464     return 1;
465 }
466
467 int ssl_cert_add1_chain_cert(SSL *s, SSL_CTX *ctx, X509 *x)
468 {
469     if (!ssl_cert_add0_chain_cert(s, ctx, x))
470         return 0;
471     X509_up_ref(x);
472     return 1;
473 }
474
475 int ssl_cert_select_current(CERT *c, X509 *x)
476 {
477     int i;
478     if (x == NULL)
479         return 0;
480     for (i = 0; i < SSL_PKEY_NUM; i++) {
481         CERT_PKEY *cpk = c->pkeys + i;
482         if (cpk->x509 == x && cpk->privatekey) {
483             c->key = cpk;
484             return 1;
485         }
486     }
487
488     for (i = 0; i < SSL_PKEY_NUM; i++) {
489         CERT_PKEY *cpk = c->pkeys + i;
490         if (cpk->privatekey && cpk->x509 && !X509_cmp(cpk->x509, x)) {
491             c->key = cpk;
492             return 1;
493         }
494     }
495     return 0;
496 }
497
498 int ssl_cert_set_current(CERT *c, long op)
499 {
500     int i, idx;
501     if (!c)
502         return 0;
503     if (op == SSL_CERT_SET_FIRST)
504         idx = 0;
505     else if (op == SSL_CERT_SET_NEXT) {
506         idx = (int)(c->key - c->pkeys + 1);
507         if (idx >= SSL_PKEY_NUM)
508             return 0;
509     } else
510         return 0;
511     for (i = idx; i < SSL_PKEY_NUM; i++) {
512         CERT_PKEY *cpk = c->pkeys + i;
513         if (cpk->x509 && cpk->privatekey) {
514             c->key = cpk;
515             return 1;
516         }
517     }
518     return 0;
519 }
520
521 void ssl_cert_set_cert_cb(CERT *c, int (*cb) (SSL *ssl, void *arg), void *arg)
522 {
523     c->cert_cb = cb;
524     c->cert_cb_arg = arg;
525 }
526
527 int ssl_verify_cert_chain(SSL *s, STACK_OF(X509) *sk)
528 {
529     X509 *x;
530     int i;
531     X509_STORE *verify_store;
532     X509_STORE_CTX ctx;
533
534     if (s->cert->verify_store)
535         verify_store = s->cert->verify_store;
536     else
537         verify_store = s->ctx->cert_store;
538
539     if ((sk == NULL) || (sk_X509_num(sk) == 0))
540         return (0);
541
542     x = sk_X509_value(sk, 0);
543     if (!X509_STORE_CTX_init(&ctx, verify_store, x, sk)) {
544         SSLerr(SSL_F_SSL_VERIFY_CERT_CHAIN, ERR_R_X509_LIB);
545         return (0);
546     }
547     /* Set suite B flags if needed */
548     X509_STORE_CTX_set_flags(&ctx, tls1_suiteb(s));
549     X509_STORE_CTX_set_ex_data(&ctx, SSL_get_ex_data_X509_STORE_CTX_idx(), s);
550
551     /*
552      * We need to inherit the verify parameters. These can be determined by
553      * the context: if its a server it will verify SSL client certificates or
554      * vice versa.
555      */
556
557     X509_STORE_CTX_set_default(&ctx, s->server ? "ssl_client" : "ssl_server");
558     /*
559      * Anything non-default in "param" should overwrite anything in the ctx.
560      */
561     X509_VERIFY_PARAM_set1(X509_STORE_CTX_get0_param(&ctx), s->param);
562
563     if (s->verify_callback)
564         X509_STORE_CTX_set_verify_cb(&ctx, s->verify_callback);
565
566     if (s->ctx->app_verify_callback != NULL)
567         i = s->ctx->app_verify_callback(&ctx, s->ctx->app_verify_arg);
568     else {
569         i = X509_verify_cert(&ctx);
570 # if 0
571         /* Dummy error calls so mkerr generates them */
572         SSLerr(SSL_F_SSL_VERIFY_CERT_CHAIN, SSL_R_EE_KEY_TOO_SMALL);
573         SSLerr(SSL_F_SSL_VERIFY_CERT_CHAIN, SSL_R_CA_KEY_TOO_SMALL);
574         SSLerr(SSL_F_SSL_VERIFY_CERT_CHAIN, SSL_R_CA_MD_TOO_WEAK);
575 # endif
576         if (i > 0)
577             i = ssl_security_cert_chain(s, ctx.chain, NULL, 1);
578     }
579
580     s->verify_result = ctx.error;
581     X509_STORE_CTX_cleanup(&ctx);
582
583     return (i);
584 }
585
586 static void set_client_CA_list(STACK_OF(X509_NAME) **ca_list,
587                                STACK_OF(X509_NAME) *name_list)
588 {
589     sk_X509_NAME_pop_free(*ca_list, X509_NAME_free);
590     *ca_list = name_list;
591 }
592
593 STACK_OF(X509_NAME) *SSL_dup_CA_list(STACK_OF(X509_NAME) *sk)
594 {
595     int i;
596     STACK_OF(X509_NAME) *ret;
597     X509_NAME *name;
598
599     ret = sk_X509_NAME_new_null();
600     for (i = 0; i < sk_X509_NAME_num(sk); i++) {
601         name = X509_NAME_dup(sk_X509_NAME_value(sk, i));
602         if ((name == NULL) || !sk_X509_NAME_push(ret, name)) {
603             sk_X509_NAME_pop_free(ret, X509_NAME_free);
604             return (NULL);
605         }
606     }
607     return (ret);
608 }
609
610 void SSL_set_client_CA_list(SSL *s, STACK_OF(X509_NAME) *name_list)
611 {
612     set_client_CA_list(&(s->client_CA), name_list);
613 }
614
615 void SSL_CTX_set_client_CA_list(SSL_CTX *ctx, STACK_OF(X509_NAME) *name_list)
616 {
617     set_client_CA_list(&(ctx->client_CA), name_list);
618 }
619
620 STACK_OF(X509_NAME) *SSL_CTX_get_client_CA_list(const SSL_CTX *ctx)
621 {
622     return (ctx->client_CA);
623 }
624
625 STACK_OF(X509_NAME) *SSL_get_client_CA_list(const SSL *s)
626 {
627     if (!s->server) { /* we are in the client */
628         if (((s->version >> 8) == SSL3_VERSION_MAJOR) && (s->s3 != NULL))
629             return (s->s3->tmp.ca_names);
630         else
631             return (NULL);
632     } else {
633         if (s->client_CA != NULL)
634             return (s->client_CA);
635         else
636             return (s->ctx->client_CA);
637     }
638 }
639
640 static int add_client_CA(STACK_OF(X509_NAME) **sk, X509 *x)
641 {
642     X509_NAME *name;
643
644     if (x == NULL)
645         return (0);
646     if ((*sk == NULL) && ((*sk = sk_X509_NAME_new_null()) == NULL))
647         return (0);
648
649     if ((name = X509_NAME_dup(X509_get_subject_name(x))) == NULL)
650         return (0);
651
652     if (!sk_X509_NAME_push(*sk, name)) {
653         X509_NAME_free(name);
654         return (0);
655     }
656     return (1);
657 }
658
659 int SSL_add_client_CA(SSL *ssl, X509 *x)
660 {
661     return (add_client_CA(&(ssl->client_CA), x));
662 }
663
664 int SSL_CTX_add_client_CA(SSL_CTX *ctx, X509 *x)
665 {
666     return (add_client_CA(&(ctx->client_CA), x));
667 }
668
669 static int xname_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
670 {
671     return (X509_NAME_cmp(*a, *b));
672 }
673
674 /**
675  * Load CA certs from a file into a ::STACK. Note that it is somewhat misnamed;
676  * it doesn't really have anything to do with clients (except that a common use
677  * for a stack of CAs is to send it to the client). Actually, it doesn't have
678  * much to do with CAs, either, since it will load any old cert.
679  * \param file the file containing one or more certs.
680  * \return a ::STACK containing the certs.
681  */
682 STACK_OF(X509_NAME) *SSL_load_client_CA_file(const char *file)
683 {
684     BIO *in;
685     X509 *x = NULL;
686     X509_NAME *xn = NULL;
687     STACK_OF(X509_NAME) *ret = NULL, *sk;
688
689     sk = sk_X509_NAME_new(xname_cmp);
690
691     in = BIO_new(BIO_s_file());
692
693     if ((sk == NULL) || (in == NULL)) {
694         SSLerr(SSL_F_SSL_LOAD_CLIENT_CA_FILE, ERR_R_MALLOC_FAILURE);
695         goto err;
696     }
697
698     if (!BIO_read_filename(in, file))
699         goto err;
700
701     for (;;) {
702         if (PEM_read_bio_X509(in, &x, NULL, NULL) == NULL)
703             break;
704         if (ret == NULL) {
705             ret = sk_X509_NAME_new_null();
706             if (ret == NULL) {
707                 SSLerr(SSL_F_SSL_LOAD_CLIENT_CA_FILE, ERR_R_MALLOC_FAILURE);
708                 goto err;
709             }
710         }
711         if ((xn = X509_get_subject_name(x)) == NULL)
712             goto err;
713         /* check for duplicates */
714         xn = X509_NAME_dup(xn);
715         if (xn == NULL)
716             goto err;
717         if (sk_X509_NAME_find(sk, xn) >= 0)
718             X509_NAME_free(xn);
719         else {
720             sk_X509_NAME_push(sk, xn);
721             sk_X509_NAME_push(ret, xn);
722         }
723     }
724     goto done;
725
726  err:
727     sk_X509_NAME_pop_free(ret, X509_NAME_free);
728     ret = NULL;
729  done:
730     sk_X509_NAME_free(sk);
731     BIO_free(in);
732     X509_free(x);
733     if (ret != NULL)
734         ERR_clear_error();
735     return (ret);
736 }
737
738 /**
739  * Add a file of certs to a stack.
740  * \param stack the stack to add to.
741  * \param file the file to add from. All certs in this file that are not
742  * already in the stack will be added.
743  * \return 1 for success, 0 for failure. Note that in the case of failure some
744  * certs may have been added to \c stack.
745  */
746
747 int SSL_add_file_cert_subjects_to_stack(STACK_OF(X509_NAME) *stack,
748                                         const char *file)
749 {
750     BIO *in;
751     X509 *x = NULL;
752     X509_NAME *xn = NULL;
753     int ret = 1;
754     int (*oldcmp) (const X509_NAME *const *a, const X509_NAME *const *b);
755
756     oldcmp = sk_X509_NAME_set_cmp_func(stack, xname_cmp);
757
758     in = BIO_new(BIO_s_file());
759
760     if (in == NULL) {
761         SSLerr(SSL_F_SSL_ADD_FILE_CERT_SUBJECTS_TO_STACK,
762                ERR_R_MALLOC_FAILURE);
763         goto err;
764     }
765
766     if (!BIO_read_filename(in, file))
767         goto err;
768
769     for (;;) {
770         if (PEM_read_bio_X509(in, &x, NULL, NULL) == NULL)
771             break;
772         if ((xn = X509_get_subject_name(x)) == NULL)
773             goto err;
774         xn = X509_NAME_dup(xn);
775         if (xn == NULL)
776             goto err;
777         if (sk_X509_NAME_find(stack, xn) >= 0)
778             X509_NAME_free(xn);
779         else
780             sk_X509_NAME_push(stack, xn);
781     }
782
783     ERR_clear_error();
784     goto done;
785
786  err:
787         ret = 0;
788  done:
789     BIO_free(in);
790     X509_free(x);
791     (void)sk_X509_NAME_set_cmp_func(stack, oldcmp);
792     return ret;
793 }
794
795 /**
796  * Add a directory of certs to a stack.
797  * \param stack the stack to append to.
798  * \param dir the directory to append from. All files in this directory will be
799  * examined as potential certs. Any that are acceptable to
800  * SSL_add_dir_cert_subjects_to_stack() that are not already in the stack will be
801  * included.
802  * \return 1 for success, 0 for failure. Note that in the case of failure some
803  * certs may have been added to \c stack.
804  */
805
806 int SSL_add_dir_cert_subjects_to_stack(STACK_OF(X509_NAME) *stack,
807                                        const char *dir)
808 {
809     OPENSSL_DIR_CTX *d = NULL;
810     const char *filename;
811     int ret = 0;
812
813     CRYPTO_w_lock(CRYPTO_LOCK_READDIR);
814
815     /* Note that a side effect is that the CAs will be sorted by name */
816
817     while ((filename = OPENSSL_DIR_read(&d, dir))) {
818         char buf[1024];
819         int r;
820
821         if (strlen(dir) + strlen(filename) + 2 > sizeof buf) {
822             SSLerr(SSL_F_SSL_ADD_DIR_CERT_SUBJECTS_TO_STACK,
823                    SSL_R_PATH_TOO_LONG);
824             goto err;
825         }
826 #ifdef OPENSSL_SYS_VMS
827         r = BIO_snprintf(buf, sizeof buf, "%s%s", dir, filename);
828 #else
829         r = BIO_snprintf(buf, sizeof buf, "%s/%s", dir, filename);
830 #endif
831         if (r <= 0 || r >= (int)sizeof(buf))
832             goto err;
833         if (!SSL_add_file_cert_subjects_to_stack(stack, buf))
834             goto err;
835     }
836
837     if (errno) {
838         SYSerr(SYS_F_OPENDIR, get_last_sys_error());
839         ERR_add_error_data(3, "OPENSSL_DIR_read(&ctx, '", dir, "')");
840         SSLerr(SSL_F_SSL_ADD_DIR_CERT_SUBJECTS_TO_STACK, ERR_R_SYS_LIB);
841         goto err;
842     }
843
844     ret = 1;
845
846  err:
847     if (d)
848         OPENSSL_DIR_end(&d);
849     CRYPTO_w_unlock(CRYPTO_LOCK_READDIR);
850     return ret;
851 }
852
853 /* Add a certificate to a BUF_MEM structure */
854
855 static int ssl_add_cert_to_buf(BUF_MEM *buf, unsigned long *l, X509 *x)
856 {
857     int n;
858     unsigned char *p;
859
860     n = i2d_X509(x, NULL);
861     if (!BUF_MEM_grow_clean(buf, (int)(n + (*l) + 3))) {
862         SSLerr(SSL_F_SSL_ADD_CERT_TO_BUF, ERR_R_BUF_LIB);
863         return 0;
864     }
865     p = (unsigned char *)&(buf->data[*l]);
866     l2n3(n, p);
867     i2d_X509(x, &p);
868     *l += n + 3;
869
870     return 1;
871 }
872
873 /* Add certificate chain to internal SSL BUF_MEM strcuture */
874 int ssl_add_cert_chain(SSL *s, CERT_PKEY *cpk, unsigned long *l)
875 {
876     BUF_MEM *buf = s->init_buf;
877     int i;
878
879     X509 *x;
880     STACK_OF(X509) *extra_certs;
881     X509_STORE *chain_store;
882
883     /* TLSv1 sends a chain with nothing in it, instead of an alert */
884     if (!BUF_MEM_grow_clean(buf, 10)) {
885         SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, ERR_R_BUF_LIB);
886         return 0;
887     }
888
889     if (!cpk || !cpk->x509)
890         return 1;
891
892     x = cpk->x509;
893
894     /*
895      * If we have a certificate specific chain use it, else use parent ctx.
896      */
897     if (cpk->chain)
898         extra_certs = cpk->chain;
899     else
900         extra_certs = s->ctx->extra_certs;
901
902     if ((s->mode & SSL_MODE_NO_AUTO_CHAIN) || extra_certs)
903         chain_store = NULL;
904     else if (s->cert->chain_store)
905         chain_store = s->cert->chain_store;
906     else
907         chain_store = s->ctx->cert_store;
908
909     if (chain_store) {
910         X509_STORE_CTX xs_ctx;
911
912         if (!X509_STORE_CTX_init(&xs_ctx, chain_store, x, NULL)) {
913             SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, ERR_R_X509_LIB);
914             return (0);
915         }
916         /*
917          * It is valid for the chain not to be complete (because normally we
918          * don't include the root cert in the chain). Therefore we deliberately
919          * ignore the error return from this call. We're not actually verifying
920          * the cert - we're just building as much of the chain as we can
921          */
922         X509_verify_cert(&xs_ctx);
923         /* Don't leave errors in the queue */
924         ERR_clear_error();
925         i = ssl_security_cert_chain(s, xs_ctx.chain, NULL, 0);
926         if (i != 1) {
927             X509_STORE_CTX_cleanup(&xs_ctx);
928             SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, i);
929             return 0;
930         }
931         for (i = 0; i < sk_X509_num(xs_ctx.chain); i++) {
932             x = sk_X509_value(xs_ctx.chain, i);
933
934             if (!ssl_add_cert_to_buf(buf, l, x)) {
935                 X509_STORE_CTX_cleanup(&xs_ctx);
936                 return 0;
937             }
938         }
939         X509_STORE_CTX_cleanup(&xs_ctx);
940     } else {
941         i = ssl_security_cert_chain(s, extra_certs, x, 0);
942         if (i != 1) {
943             SSLerr(SSL_F_SSL_ADD_CERT_CHAIN, i);
944             return 0;
945         }
946         if (!ssl_add_cert_to_buf(buf, l, x))
947             return 0;
948         for (i = 0; i < sk_X509_num(extra_certs); i++) {
949             x = sk_X509_value(extra_certs, i);
950             if (!ssl_add_cert_to_buf(buf, l, x))
951                 return 0;
952         }
953     }
954     return 1;
955 }
956
957 /* Build a certificate chain for current certificate */
958 int ssl_build_cert_chain(SSL *s, SSL_CTX *ctx, int flags)
959 {
960     CERT *c = s ? s->cert : ctx->cert;
961     CERT_PKEY *cpk = c->key;
962     X509_STORE *chain_store = NULL;
963     X509_STORE_CTX xs_ctx;
964     STACK_OF(X509) *chain = NULL, *untrusted = NULL;
965     X509 *x;
966     int i, rv = 0;
967     unsigned long error;
968
969     if (!cpk->x509) {
970         SSLerr(SSL_F_SSL_BUILD_CERT_CHAIN, SSL_R_NO_CERTIFICATE_SET);
971         goto err;
972     }
973     /* Rearranging and check the chain: add everything to a store */
974     if (flags & SSL_BUILD_CHAIN_FLAG_CHECK) {
975         chain_store = X509_STORE_new();
976         if (chain_store == NULL)
977             goto err;
978         for (i = 0; i < sk_X509_num(cpk->chain); i++) {
979             x = sk_X509_value(cpk->chain, i);
980             if (!X509_STORE_add_cert(chain_store, x)) {
981                 error = ERR_peek_last_error();
982                 if (ERR_GET_LIB(error) != ERR_LIB_X509 ||
983                     ERR_GET_REASON(error) !=
984                     X509_R_CERT_ALREADY_IN_HASH_TABLE)
985                     goto err;
986                 ERR_clear_error();
987             }
988         }
989         /* Add EE cert too: it might be self signed */
990         if (!X509_STORE_add_cert(chain_store, cpk->x509)) {
991             error = ERR_peek_last_error();
992             if (ERR_GET_LIB(error) != ERR_LIB_X509 ||
993                 ERR_GET_REASON(error) != X509_R_CERT_ALREADY_IN_HASH_TABLE)
994                 goto err;
995             ERR_clear_error();
996         }
997     } else {
998         if (c->chain_store)
999             chain_store = c->chain_store;
1000         else if (s)
1001             chain_store = s->ctx->cert_store;
1002         else
1003             chain_store = ctx->cert_store;
1004
1005         if (flags & SSL_BUILD_CHAIN_FLAG_UNTRUSTED)
1006             untrusted = cpk->chain;
1007     }
1008
1009     if (!X509_STORE_CTX_init(&xs_ctx, chain_store, cpk->x509, untrusted)) {
1010         SSLerr(SSL_F_SSL_BUILD_CERT_CHAIN, ERR_R_X509_LIB);
1011         goto err;
1012     }
1013     /* Set suite B flags if needed */
1014     X509_STORE_CTX_set_flags(&xs_ctx,
1015                              c->cert_flags & SSL_CERT_FLAG_SUITEB_128_LOS);
1016
1017     i = X509_verify_cert(&xs_ctx);
1018     if (i <= 0 && flags & SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR) {
1019         if (flags & SSL_BUILD_CHAIN_FLAG_CLEAR_ERROR)
1020             ERR_clear_error();
1021         i = 1;
1022         rv = 2;
1023     }
1024     if (i > 0)
1025         chain = X509_STORE_CTX_get1_chain(&xs_ctx);
1026     if (i <= 0) {
1027         SSLerr(SSL_F_SSL_BUILD_CERT_CHAIN, SSL_R_CERTIFICATE_VERIFY_FAILED);
1028         i = X509_STORE_CTX_get_error(&xs_ctx);
1029         ERR_add_error_data(2, "Verify error:",
1030                            X509_verify_cert_error_string(i));
1031
1032         X509_STORE_CTX_cleanup(&xs_ctx);
1033         goto err;
1034     }
1035     X509_STORE_CTX_cleanup(&xs_ctx);
1036     /* Remove EE certificate from chain */
1037     x = sk_X509_shift(chain);
1038     X509_free(x);
1039     if (flags & SSL_BUILD_CHAIN_FLAG_NO_ROOT) {
1040         if (sk_X509_num(chain) > 0) {
1041             /* See if last cert is self signed */
1042             x = sk_X509_value(chain, sk_X509_num(chain) - 1);
1043             if (X509_get_extension_flags(x) & EXFLAG_SS) {
1044                 x = sk_X509_pop(chain);
1045                 X509_free(x);
1046             }
1047         }
1048     }
1049     /*
1050      * Check security level of all CA certificates: EE will have been checked
1051      * already.
1052      */
1053     for (i = 0; i < sk_X509_num(chain); i++) {
1054         x = sk_X509_value(chain, i);
1055         rv = ssl_security_cert(s, ctx, x, 0, 0);
1056         if (rv != 1) {
1057             SSLerr(SSL_F_SSL_BUILD_CERT_CHAIN, rv);
1058             sk_X509_pop_free(chain, X509_free);
1059             rv = 0;
1060             goto err;
1061         }
1062     }
1063     sk_X509_pop_free(cpk->chain, X509_free);
1064     cpk->chain = chain;
1065     if (rv == 0)
1066         rv = 1;
1067  err:
1068     if (flags & SSL_BUILD_CHAIN_FLAG_CHECK)
1069         X509_STORE_free(chain_store);
1070
1071     return rv;
1072 }
1073
1074 int ssl_cert_set_cert_store(CERT *c, X509_STORE *store, int chain, int ref)
1075 {
1076     X509_STORE **pstore;
1077     if (chain)
1078         pstore = &c->chain_store;
1079     else
1080         pstore = &c->verify_store;
1081     X509_STORE_free(*pstore);
1082     *pstore = store;
1083     if (ref && store)
1084         CRYPTO_add(&store->references, 1, CRYPTO_LOCK_X509_STORE);
1085     return 1;
1086 }
1087
1088 static int ssl_security_default_callback(SSL *s, SSL_CTX *ctx, int op,
1089                                          int bits, int nid, void *other,
1090                                          void *ex)
1091 {
1092     int level, minbits;
1093     static const int minbits_table[5] = { 80, 112, 128, 192, 256 };
1094     if (ctx)
1095         level = SSL_CTX_get_security_level(ctx);
1096     else
1097         level = SSL_get_security_level(s);
1098     /* Level 0: anything goes */
1099     if (level <= 0)
1100         return 1;
1101     if (level > 5)
1102         level = 5;
1103     minbits = minbits_table[level - 1];
1104     switch (op) {
1105     case SSL_SECOP_CIPHER_SUPPORTED:
1106     case SSL_SECOP_CIPHER_SHARED:
1107     case SSL_SECOP_CIPHER_CHECK:
1108         {
1109             const SSL_CIPHER *c = other;
1110             /* No ciphers below security level */
1111             if (bits < minbits)
1112                 return 0;
1113             /* No unauthenticated ciphersuites */
1114             if (c->algorithm_auth & SSL_aNULL)
1115                 return 0;
1116             /* No MD5 mac ciphersuites */
1117             if (c->algorithm_mac & SSL_MD5)
1118                 return 0;
1119             /* SHA1 HMAC is 160 bits of security */
1120             if (minbits > 160 && c->algorithm_mac & SSL_SHA1)
1121                 return 0;
1122             /* Level 2: no RC4 */
1123             if (level >= 2 && c->algorithm_enc == SSL_RC4)
1124                 return 0;
1125             /* Level 3: forward secure ciphersuites only */
1126             if (level >= 3 && !(c->algorithm_mkey & (SSL_kEDH | SSL_kEECDH)))
1127                 return 0;
1128             break;
1129         }
1130     case SSL_SECOP_VERSION:
1131         /* SSLv3 not allowed on level 2 */
1132         if (nid <= SSL3_VERSION && level >= 2)
1133             return 0;
1134         /* TLS v1.1 and above only for level 3 */
1135         if (nid <= TLS1_VERSION && level >= 3)
1136             return 0;
1137         /* TLS v1.2 only for level 4 and above */
1138         if (nid <= TLS1_1_VERSION && level >= 4)
1139             return 0;
1140         break;
1141
1142     case SSL_SECOP_COMPRESSION:
1143         if (level >= 2)
1144             return 0;
1145         break;
1146     case SSL_SECOP_TICKET:
1147         if (level >= 3)
1148             return 0;
1149         break;
1150     default:
1151         if (bits < minbits)
1152             return 0;
1153     }
1154     return 1;
1155 }
1156
1157 int ssl_security(SSL *s, int op, int bits, int nid, void *other)
1158 {
1159     return s->cert->sec_cb(s, NULL, op, bits, nid, other, s->cert->sec_ex);
1160 }
1161
1162 int ssl_ctx_security(SSL_CTX *ctx, int op, int bits, int nid, void *other)
1163 {
1164     return ctx->cert->sec_cb(NULL, ctx, op, bits, nid, other,
1165                              ctx->cert->sec_ex);
1166 }