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