1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young (eay@cryptsoft.com).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young (eay@cryptsoft.com)"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.]
56  */
57 /* ====================================================================
58  * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
59  *
60  * Redistribution and use in source and binary forms, with or without
61  * modification, are permitted provided that the following conditions
62  * are met:
63  *
64  * 1. Redistributions of source code must retain the above copyright
65  *    notice, this list of conditions and the following disclaimer.
66  *
67  * 2. Redistributions in binary form must reproduce the above copyright
68  *    notice, this list of conditions and the following disclaimer in
69  *    the documentation and/or other materials provided with the
70  *    distribution.
71  *
72  * 3. All advertising materials mentioning features or use of this
73  *    software must display the following acknowledgment:
74  *    "This product includes software developed by the OpenSSL Project
75  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
76  *
77  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78  *    endorse or promote products derived from this software without
79  *    prior written permission. For written permission, please contact
80  *    openssl-core@openssl.org.
81  *
82  * 5. Products derived from this software may not be called "OpenSSL"
83  *    nor may "OpenSSL" appear in their names without prior written
84  *    permission of the OpenSSL Project.
85  *
86  * 6. Redistributions of any form whatsoever must retain the following
87  *    acknowledgment:
88  *    "This product includes software developed by the OpenSSL Project
89  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
90  *
91  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
95  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102  * OF THE POSSIBILITY OF SUCH DAMAGE.
103  * ====================================================================
104  *
105  * This product includes cryptographic software written by Eric Young
106  * (eay@cryptsoft.com).  This product includes software written by Tim
107  * Hudson (tjh@cryptsoft.com).
108  *
109  */
110 /* ====================================================================
111  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
112  * ECC cipher suite support in OpenSSL originally developed by
113  * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project. */
114 
115 #include <errno.h>
116 #include <stdio.h>
117 #include <string.h>
118 
119 #include <openssl/bio.h>
120 #include <openssl/bn.h>
121 #include <openssl/buf.h>
122 #include <openssl/dh.h>
123 #include <openssl/err.h>
124 #include <openssl/mem.h>
125 #include <openssl/obj.h>
126 #include <openssl/pem.h>
127 #include <openssl/x509v3.h>
128 
129 #include "../crypto/dh/internal.h"
130 #include "../crypto/directory.h"
131 #include "../crypto/internal.h"
132 #include "internal.h"
133 
134 
135 static CRYPTO_once_t g_x509_store_ex_data_index_once;
136 static int g_x509_store_ex_data_index;
137 
ssl_x509_store_ex_data_index_init(void)138 static void ssl_x509_store_ex_data_index_init(void) {
139   g_x509_store_ex_data_index = X509_STORE_CTX_get_ex_new_index(
140       0, "SSL for verify callback", NULL, NULL, NULL);
141 }
142 
SSL_get_ex_data_X509_STORE_CTX_idx(void)143 int SSL_get_ex_data_X509_STORE_CTX_idx(void) {
144   CRYPTO_once(&g_x509_store_ex_data_index_once,
145               ssl_x509_store_ex_data_index_init);
146   return g_x509_store_ex_data_index;
147 }
148 
ssl_cert_new(void)149 CERT *ssl_cert_new(void) {
150   CERT *ret;
151 
152   ret = (CERT *)OPENSSL_malloc(sizeof(CERT));
153   if (ret == NULL) {
154     OPENSSL_PUT_ERROR(SSL, ssl_cert_new, ERR_R_MALLOC_FAILURE);
155     return NULL;
156   }
157   memset(ret, 0, sizeof(CERT));
158 
159   ret->key = &ret->pkeys[SSL_PKEY_RSA_ENC];
160   return ret;
161 }
162 
ssl_cert_dup(CERT * cert)163 CERT *ssl_cert_dup(CERT *cert) {
164   CERT *ret;
165   int i;
166 
167   ret = (CERT *)OPENSSL_malloc(sizeof(CERT));
168   if (ret == NULL) {
169     OPENSSL_PUT_ERROR(SSL, ssl_cert_dup, ERR_R_MALLOC_FAILURE);
170     return NULL;
171   }
172   memset(ret, 0, sizeof(CERT));
173 
174   ret->key = &ret->pkeys[cert->key - &cert->pkeys[0]];
175   /* or ret->key = ret->pkeys + (cert->key - cert->pkeys), if you find that
176    * more readable */
177 
178   ret->mask_k = cert->mask_k;
179   ret->mask_a = cert->mask_a;
180 
181   if (cert->dh_tmp != NULL) {
182     ret->dh_tmp = DHparams_dup(cert->dh_tmp);
183     if (ret->dh_tmp == NULL) {
184       OPENSSL_PUT_ERROR(SSL, ssl_cert_dup, ERR_R_DH_LIB);
185       goto err;
186     }
187     if (cert->dh_tmp->priv_key) {
188       BIGNUM *b = BN_dup(cert->dh_tmp->priv_key);
189       if (!b) {
190         OPENSSL_PUT_ERROR(SSL, ssl_cert_dup, ERR_R_BN_LIB);
191         goto err;
192       }
193       ret->dh_tmp->priv_key = b;
194     }
195     if (cert->dh_tmp->pub_key) {
196       BIGNUM *b = BN_dup(cert->dh_tmp->pub_key);
197       if (!b) {
198         OPENSSL_PUT_ERROR(SSL, ssl_cert_dup, ERR_R_BN_LIB);
199         goto err;
200       }
201       ret->dh_tmp->pub_key = b;
202     }
203   }
204   ret->dh_tmp_cb = cert->dh_tmp_cb;
205 
206   ret->ecdh_nid = cert->ecdh_nid;
207   ret->ecdh_tmp_cb = cert->ecdh_tmp_cb;
208 
209   for (i = 0; i < SSL_PKEY_NUM; i++) {
210     CERT_PKEY *cpk = cert->pkeys + i;
211     CERT_PKEY *rpk = ret->pkeys + i;
212     if (cpk->x509 != NULL) {
213       rpk->x509 = X509_up_ref(cpk->x509);
214     }
215 
216     if (cpk->privatekey != NULL) {
217       rpk->privatekey = EVP_PKEY_up_ref(cpk->privatekey);
218     }
219 
220     if (cpk->chain) {
221       rpk->chain = X509_chain_up_ref(cpk->chain);
222       if (!rpk->chain) {
223         OPENSSL_PUT_ERROR(SSL, ssl_cert_dup, ERR_R_MALLOC_FAILURE);
224         goto err;
225       }
226     }
227   }
228 
229   /* Copy over signature algorithm configuration. */
230   if (cert->conf_sigalgs) {
231     ret->conf_sigalgs = BUF_memdup(cert->conf_sigalgs, cert->conf_sigalgslen);
232     if (!ret->conf_sigalgs) {
233       goto err;
234     }
235     ret->conf_sigalgslen = cert->conf_sigalgslen;
236   }
237 
238   if (cert->client_sigalgs) {
239     ret->client_sigalgs = BUF_memdup(cert->client_sigalgs,
240                                      cert->client_sigalgslen);
241     if (!ret->client_sigalgs) {
242       goto err;
243     }
244     ret->client_sigalgslen = cert->client_sigalgslen;
245   }
246 
247   /* Copy any custom client certificate types */
248   if (cert->client_certificate_types) {
249     ret->client_certificate_types = BUF_memdup(
250         cert->client_certificate_types, cert->num_client_certificate_types);
251     if (!ret->client_certificate_types) {
252       goto err;
253     }
254     ret->num_client_certificate_types = cert->num_client_certificate_types;
255   }
256 
257   ret->cert_cb = cert->cert_cb;
258   ret->cert_cb_arg = cert->cert_cb_arg;
259 
260   if (cert->verify_store) {
261     CRYPTO_refcount_inc(&cert->verify_store->references);
262     ret->verify_store = cert->verify_store;
263   }
264 
265   if (cert->chain_store) {
266     CRYPTO_refcount_inc(&cert->chain_store->references);
267     ret->chain_store = cert->chain_store;
268   }
269 
270   return ret;
271 
272 err:
273   ssl_cert_free(ret);
274   return NULL;
275 }
276 
277 /* Free up and clear all certificates and chains */
ssl_cert_clear_certs(CERT * c)278 void ssl_cert_clear_certs(CERT *c) {
279   int i;
280   if (c == NULL) {
281     return;
282   }
283 
284   for (i = 0; i < SSL_PKEY_NUM; i++) {
285     CERT_PKEY *cpk = c->pkeys + i;
286     if (cpk->x509) {
287       X509_free(cpk->x509);
288       cpk->x509 = NULL;
289     }
290     if (cpk->privatekey) {
291       EVP_PKEY_free(cpk->privatekey);
292       cpk->privatekey = NULL;
293     }
294     if (cpk->chain) {
295       sk_X509_pop_free(cpk->chain, X509_free);
296       cpk->chain = NULL;
297     }
298   }
299 }
300 
ssl_cert_free(CERT * c)301 void ssl_cert_free(CERT *c) {
302   if (c == NULL) {
303     return;
304   }
305 
306   DH_free(c->dh_tmp);
307 
308   ssl_cert_clear_certs(c);
309   OPENSSL_free(c->peer_sigalgs);
310   OPENSSL_free(c->conf_sigalgs);
311   OPENSSL_free(c->client_sigalgs);
312   OPENSSL_free(c->shared_sigalgs);
313   OPENSSL_free(c->client_certificate_types);
314   X509_STORE_free(c->verify_store);
315   X509_STORE_free(c->chain_store);
316 
317   OPENSSL_free(c);
318 }
319 
ssl_cert_set0_chain(CERT * c,STACK_OF (X509)* chain)320 int ssl_cert_set0_chain(CERT *c, STACK_OF(X509) *chain) {
321   CERT_PKEY *cpk = c->key;
322   if (!cpk) {
323     return 0;
324   }
325   sk_X509_pop_free(cpk->chain, X509_free);
326   cpk->chain = chain;
327   return 1;
328 }
329 
ssl_cert_set1_chain(CERT * c,STACK_OF (X509)* chain)330 int ssl_cert_set1_chain(CERT *c, STACK_OF(X509) *chain) {
331   STACK_OF(X509) *dchain;
332   if (!chain) {
333     return ssl_cert_set0_chain(c, NULL);
334   }
335 
336   dchain = X509_chain_up_ref(chain);
337   if (!dchain) {
338     return 0;
339   }
340 
341   if (!ssl_cert_set0_chain(c, dchain)) {
342     sk_X509_pop_free(dchain, X509_free);
343     return 0;
344   }
345 
346   return 1;
347 }
348 
ssl_cert_add0_chain_cert(CERT * c,X509 * x)349 int ssl_cert_add0_chain_cert(CERT *c, X509 *x) {
350   CERT_PKEY *cpk = c->key;
351   if (!cpk) {
352     return 0;
353   }
354 
355   if (!cpk->chain) {
356     cpk->chain = sk_X509_new_null();
357   }
358   if (!cpk->chain || !sk_X509_push(cpk->chain, x)) {
359     return 0;
360   }
361 
362   return 1;
363 }
364 
ssl_cert_add1_chain_cert(CERT * c,X509 * x)365 int ssl_cert_add1_chain_cert(CERT *c, X509 *x) {
366   if (!ssl_cert_add0_chain_cert(c, x)) {
367     return 0;
368   }
369 
370   X509_up_ref(x);
371   return 1;
372 }
373 
ssl_cert_select_current(CERT * c,X509 * x)374 int ssl_cert_select_current(CERT *c, X509 *x) {
375   int i;
376   if (x == NULL) {
377     return 0;
378   }
379 
380   for (i = 0; i < SSL_PKEY_NUM; i++) {
381     if (c->pkeys[i].x509 == x) {
382       c->key = &c->pkeys[i];
383       return 1;
384     }
385   }
386 
387   for (i = 0; i < SSL_PKEY_NUM; i++) {
388     if (c->pkeys[i].x509 && !X509_cmp(c->pkeys[i].x509, x)) {
389       c->key = &c->pkeys[i];
390       return 1;
391     }
392   }
393 
394   return 0;
395 }
396 
ssl_cert_set_cert_cb(CERT * c,int (* cb)(SSL * ssl,void * arg),void * arg)397 void ssl_cert_set_cert_cb(CERT *c, int (*cb)(SSL *ssl, void *arg), void *arg) {
398   c->cert_cb = cb;
399   c->cert_cb_arg = arg;
400 }
401 
ssl_sess_cert_new(void)402 SESS_CERT *ssl_sess_cert_new(void) {
403   SESS_CERT *ret;
404 
405   ret = OPENSSL_malloc(sizeof *ret);
406   if (ret == NULL) {
407     OPENSSL_PUT_ERROR(SSL, ssl_sess_cert_new, ERR_R_MALLOC_FAILURE);
408     return NULL;
409   }
410 
411   memset(ret, 0, sizeof *ret);
412   ret->peer_key = &(ret->peer_pkeys[SSL_PKEY_RSA_ENC]);
413 
414   return ret;
415 }
416 
ssl_sess_cert_free(SESS_CERT * sc)417 void ssl_sess_cert_free(SESS_CERT *sc) {
418   int i;
419 
420   if (sc == NULL) {
421     return;
422   }
423 
424   sk_X509_pop_free(sc->cert_chain, X509_free);
425 
426   for (i = 0; i < SSL_PKEY_NUM; i++) {
427     X509_free(sc->peer_pkeys[i].x509);
428   }
429 
430   DH_free(sc->peer_dh_tmp);
431   EC_KEY_free(sc->peer_ecdh_tmp);
432 
433   OPENSSL_free(sc);
434 }
435 
ssl_set_peer_cert_type(SESS_CERT * sc,int type)436 int ssl_set_peer_cert_type(SESS_CERT *sc, int type) {
437   sc->peer_cert_type = type;
438   return 1;
439 }
440 
ssl_verify_cert_chain(SSL * s,STACK_OF (X509)* sk)441 int ssl_verify_cert_chain(SSL *s, STACK_OF(X509) *sk) {
442   X509 *x;
443   int i;
444   X509_STORE *verify_store;
445   X509_STORE_CTX ctx;
446 
447   if (s->cert->verify_store) {
448     verify_store = s->cert->verify_store;
449   } else {
450     verify_store = s->ctx->cert_store;
451   }
452 
453   if (sk == NULL || sk_X509_num(sk) == 0) {
454     return 0;
455   }
456 
457   x = sk_X509_value(sk, 0);
458   if (!X509_STORE_CTX_init(&ctx, verify_store, x, sk)) {
459     OPENSSL_PUT_ERROR(SSL, ssl_verify_cert_chain, ERR_R_X509_LIB);
460     return 0;
461   }
462   X509_STORE_CTX_set_ex_data(&ctx, SSL_get_ex_data_X509_STORE_CTX_idx(), s);
463 
464   /* We need to inherit the verify parameters. These can be determined by the
465    * context: if its a server it will verify SSL client certificates or vice
466    * versa. */
467   X509_STORE_CTX_set_default(&ctx, s->server ? "ssl_client" : "ssl_server");
468 
469   /* Anything non-default in "param" should overwrite anything in the ctx. */
470   X509_VERIFY_PARAM_set1(X509_STORE_CTX_get0_param(&ctx), s->param);
471 
472   if (s->verify_callback) {
473     X509_STORE_CTX_set_verify_cb(&ctx, s->verify_callback);
474   }
475 
476   if (s->ctx->app_verify_callback != NULL) {
477     i = s->ctx->app_verify_callback(&ctx, s->ctx->app_verify_arg);
478   } else {
479     i = X509_verify_cert(&ctx);
480   }
481 
482   s->verify_result = ctx.error;
483   X509_STORE_CTX_cleanup(&ctx);
484 
485   return i;
486 }
487 
set_client_CA_list(STACK_OF (X509_NAME)** ca_list,STACK_OF (X509_NAME)* name_list)488 static void set_client_CA_list(STACK_OF(X509_NAME) **ca_list,
489                                STACK_OF(X509_NAME) *name_list) {
490   sk_X509_NAME_pop_free(*ca_list, X509_NAME_free);
491   *ca_list = name_list;
492 }
493 
STACK_OF(X509_NAME)494 STACK_OF(X509_NAME) *SSL_dup_CA_list(STACK_OF(X509_NAME) *sk) {
495   size_t i;
496   STACK_OF(X509_NAME) *ret;
497   X509_NAME *name;
498 
499   ret = sk_X509_NAME_new_null();
500   for (i = 0; i < sk_X509_NAME_num(sk); i++) {
501     name = X509_NAME_dup(sk_X509_NAME_value(sk, i));
502     if (name == NULL || !sk_X509_NAME_push(ret, name)) {
503       sk_X509_NAME_pop_free(ret, X509_NAME_free);
504       return NULL;
505     }
506   }
507 
508   return ret;
509 }
510 
SSL_set_client_CA_list(SSL * s,STACK_OF (X509_NAME)* name_list)511 void SSL_set_client_CA_list(SSL *s, STACK_OF(X509_NAME) *name_list) {
512   set_client_CA_list(&(s->client_CA), name_list);
513 }
514 
SSL_CTX_set_client_CA_list(SSL_CTX * ctx,STACK_OF (X509_NAME)* name_list)515 void SSL_CTX_set_client_CA_list(SSL_CTX *ctx, STACK_OF(X509_NAME) *name_list) {
516   set_client_CA_list(&(ctx->client_CA), name_list);
517 }
518 
STACK_OF(X509_NAME)519 STACK_OF(X509_NAME) *SSL_CTX_get_client_CA_list(const SSL_CTX *ctx) {
520   return ctx->client_CA;
521 }
522 
STACK_OF(X509_NAME)523 STACK_OF(X509_NAME) *SSL_get_client_CA_list(const SSL *s) {
524   if (s->server) {
525     if (s->client_CA != NULL) {
526       return s->client_CA;
527     } else {
528       return s->ctx->client_CA;
529     }
530   } else {
531     if ((s->version >> 8) == SSL3_VERSION_MAJOR && s->s3 != NULL) {
532       return s->s3->tmp.ca_names;
533     } else {
534       return NULL;
535     }
536   }
537 }
538 
add_client_CA(STACK_OF (X509_NAME)** sk,X509 * x)539 static int add_client_CA(STACK_OF(X509_NAME) **sk, X509 *x) {
540   X509_NAME *name;
541 
542   if (x == NULL) {
543     return 0;
544   }
545   if (*sk == NULL) {
546     *sk = sk_X509_NAME_new_null();
547     if (*sk == NULL) {
548       return 0;
549     }
550   }
551 
552   name = X509_NAME_dup(X509_get_subject_name(x));
553   if (name == NULL) {
554     return 0;
555   }
556 
557   if (!sk_X509_NAME_push(*sk, name)) {
558     X509_NAME_free(name);
559     return 0;
560   }
561 
562   return 1;
563 }
564 
SSL_add_client_CA(SSL * ssl,X509 * x)565 int SSL_add_client_CA(SSL *ssl, X509 *x) {
566   return add_client_CA(&(ssl->client_CA), x);
567 }
568 
SSL_CTX_add_client_CA(SSL_CTX * ctx,X509 * x)569 int SSL_CTX_add_client_CA(SSL_CTX *ctx, X509 *x) {
570   return add_client_CA(&(ctx->client_CA), x);
571 }
572 
xname_cmp(const X509_NAME ** a,const X509_NAME ** b)573 static int xname_cmp(const X509_NAME **a, const X509_NAME **b) {
574   return X509_NAME_cmp(*a, *b);
575 }
576 
577 /* Load CA certs from a file into a STACK. Note that it is somewhat misnamed;
578  * it doesn't really have anything to do with clients (except that a common use
579  * for a stack of CAs is to send it to the client). Actually, it doesn't have
580  * much to do with CAs, either, since it will load any old cert.
581  *
582  * \param file the file containing one or more certs.
583  * \return a ::STACK containing the certs. */
STACK_OF(X509_NAME)584 STACK_OF(X509_NAME) *SSL_load_client_CA_file(const char *file) {
585   BIO *in;
586   X509 *x = NULL;
587   X509_NAME *xn = NULL;
588   STACK_OF(X509_NAME) *ret = NULL, *sk;
589 
590   sk = sk_X509_NAME_new(xname_cmp);
591   in = BIO_new(BIO_s_file());
592 
593   if (sk == NULL || in == NULL) {
594     OPENSSL_PUT_ERROR(SSL, SSL_load_client_CA_file, ERR_R_MALLOC_FAILURE);
595     goto err;
596   }
597 
598   if (!BIO_read_filename(in, file)) {
599     goto err;
600   }
601 
602   for (;;) {
603     if (PEM_read_bio_X509(in, &x, NULL, NULL) == NULL) {
604       break;
605     }
606     if (ret == NULL) {
607       ret = sk_X509_NAME_new_null();
608       if (ret == NULL) {
609         OPENSSL_PUT_ERROR(SSL, SSL_load_client_CA_file, ERR_R_MALLOC_FAILURE);
610         goto err;
611       }
612     }
613     xn = X509_get_subject_name(x);
614     if (xn == NULL) {
615       goto err;
616     }
617 
618     /* check for duplicates */
619     xn = X509_NAME_dup(xn);
620     if (xn == NULL) {
621       goto err;
622     }
623     if (sk_X509_NAME_find(sk, NULL, xn)) {
624       X509_NAME_free(xn);
625     } else {
626       sk_X509_NAME_push(sk, xn);
627       sk_X509_NAME_push(ret, xn);
628     }
629   }
630 
631   if (0) {
632   err:
633     sk_X509_NAME_pop_free(ret, X509_NAME_free);
634     ret = NULL;
635   }
636 
637   sk_X509_NAME_free(sk);
638   BIO_free(in);
639   X509_free(x);
640   if (ret != NULL) {
641     ERR_clear_error();
642   }
643   return ret;
644 }
645 
646 /* Add a file of certs to a stack.
647  *
648  * \param stack the stack to add to.
649  * \param file the file to add from. All certs in this file that are not
650  *     already in the stack will be added.
651  * \return 1 for success, 0 for failure. Note that in the case of failure some
652  *     certs may have been added to \c stack. */
SSL_add_file_cert_subjects_to_stack(STACK_OF (X509_NAME)* stack,const char * file)653 int SSL_add_file_cert_subjects_to_stack(STACK_OF(X509_NAME) *stack,
654                                         const char *file) {
655   BIO *in;
656   X509 *x = NULL;
657   X509_NAME *xn = NULL;
658   int ret = 1;
659   int (*oldcmp)(const X509_NAME **a, const X509_NAME **b);
660 
661   oldcmp = sk_X509_NAME_set_cmp_func(stack, xname_cmp);
662   in = BIO_new(BIO_s_file());
663 
664   if (in == NULL) {
665     OPENSSL_PUT_ERROR(SSL, SSL_add_file_cert_subjects_to_stack,
666                       ERR_R_MALLOC_FAILURE);
667     goto err;
668   }
669 
670   if (!BIO_read_filename(in, file)) {
671     goto err;
672   }
673 
674   for (;;) {
675     if (PEM_read_bio_X509(in, &x, NULL, NULL) == NULL) {
676       break;
677     }
678     xn = X509_get_subject_name(x);
679     if (xn == NULL) {
680       goto err;
681     }
682     xn = X509_NAME_dup(xn);
683     if (xn == NULL) {
684       goto err;
685     }
686     if (sk_X509_NAME_find(stack, NULL, xn)) {
687       X509_NAME_free(xn);
688     } else {
689       sk_X509_NAME_push(stack, xn);
690     }
691   }
692 
693   ERR_clear_error();
694 
695   if (0) {
696   err:
697     ret = 0;
698   }
699 
700   BIO_free(in);
701   X509_free(x);
702 
703   (void) sk_X509_NAME_set_cmp_func(stack, oldcmp);
704 
705   return ret;
706 }
707 
708 /* Add a directory of certs to a stack.
709  *
710  * \param stack the stack to append to.
711  * \param dir the directory to append from. All files in this directory will be
712  *     examined as potential certs. Any that are acceptable to
713  *     SSL_add_dir_cert_subjects_to_stack() that are not already in the stack will
714  *     be included.
715  * \return 1 for success, 0 for failure. Note that in the case of failure some
716  *     certs may have been added to \c stack. */
SSL_add_dir_cert_subjects_to_stack(STACK_OF (X509_NAME)* stack,const char * dir)717 int SSL_add_dir_cert_subjects_to_stack(STACK_OF(X509_NAME) *stack,
718                                        const char *dir) {
719   OPENSSL_DIR_CTX *d = NULL;
720   const char *filename;
721   int ret = 0;
722 
723   /* Note that a side effect is that the CAs will be sorted by name */
724   while ((filename = OPENSSL_DIR_read(&d, dir))) {
725     char buf[1024];
726     int r;
727 
728     if (strlen(dir) + strlen(filename) + 2 > sizeof(buf)) {
729       OPENSSL_PUT_ERROR(SSL, SSL_add_dir_cert_subjects_to_stack,
730                         SSL_R_PATH_TOO_LONG);
731       goto err;
732     }
733 
734     r = BIO_snprintf(buf, sizeof buf, "%s/%s", dir, filename);
735     if (r <= 0 || r >= (int)sizeof(buf) ||
736         !SSL_add_file_cert_subjects_to_stack(stack, buf)) {
737       goto err;
738     }
739   }
740 
741   if (errno) {
742     OPENSSL_PUT_ERROR(SSL, SSL_add_dir_cert_subjects_to_stack, ERR_R_SYS_LIB);
743     ERR_add_error_data(3, "OPENSSL_DIR_read(&ctx, '", dir, "')");
744     goto err;
745   }
746 
747   ret = 1;
748 
749 err:
750   if (d) {
751     OPENSSL_DIR_end(&d);
752   }
753   return ret;
754 }
755 
756 /* Add a certificate to a BUF_MEM structure */
ssl_add_cert_to_buf(BUF_MEM * buf,unsigned long * l,X509 * x)757 static int ssl_add_cert_to_buf(BUF_MEM *buf, unsigned long *l, X509 *x) {
758   int n;
759   uint8_t *p;
760 
761   n = i2d_X509(x, NULL);
762   if (!BUF_MEM_grow_clean(buf, (int)(n + (*l) + 3))) {
763     OPENSSL_PUT_ERROR(SSL, ssl_add_cert_to_buf, ERR_R_BUF_LIB);
764     return 0;
765   }
766   p = (uint8_t *)&(buf->data[*l]);
767   l2n3(n, p);
768   i2d_X509(x, &p);
769   *l += n + 3;
770 
771   return 1;
772 }
773 
774 /* Add certificate chain to internal SSL BUF_MEM structure. */
ssl_add_cert_chain(SSL * s,CERT_PKEY * cpk,unsigned long * l)775 int ssl_add_cert_chain(SSL *s, CERT_PKEY *cpk, unsigned long *l) {
776   BUF_MEM *buf = s->init_buf;
777   int no_chain = 0;
778   size_t i;
779 
780   X509 *x = cpk->x509;
781   STACK_OF(X509) *extra_certs;
782   X509_STORE *chain_store;
783 
784   if (x == NULL) {
785     OPENSSL_PUT_ERROR(SSL, ssl_add_cert_chain, SSL_R_NO_CERTIFICATE_SET);
786     return 0;
787   }
788 
789   if (s->cert->chain_store) {
790     chain_store = s->cert->chain_store;
791   } else {
792     chain_store = s->ctx->cert_store;
793   }
794 
795   /* If we have a certificate specific chain use it, else use parent ctx. */
796   if (cpk && cpk->chain) {
797     extra_certs = cpk->chain;
798   } else {
799     extra_certs = s->ctx->extra_certs;
800   }
801 
802   if ((s->mode & SSL_MODE_NO_AUTO_CHAIN) || extra_certs) {
803     no_chain = 1;
804   }
805 
806   if (no_chain) {
807     if (!ssl_add_cert_to_buf(buf, l, x)) {
808       return 0;
809     }
810 
811     for (i = 0; i < sk_X509_num(extra_certs); i++) {
812       x = sk_X509_value(extra_certs, i);
813       if (!ssl_add_cert_to_buf(buf, l, x)) {
814         return 0;
815       }
816     }
817   } else {
818     X509_STORE_CTX xs_ctx;
819 
820     if (!X509_STORE_CTX_init(&xs_ctx, chain_store, x, NULL)) {
821       OPENSSL_PUT_ERROR(SSL, ssl_add_cert_chain, ERR_R_X509_LIB);
822       return 0;
823     }
824     X509_verify_cert(&xs_ctx);
825     /* Don't leave errors in the queue */
826     ERR_clear_error();
827     for (i = 0; i < sk_X509_num(xs_ctx.chain); i++) {
828       x = sk_X509_value(xs_ctx.chain, i);
829 
830       if (!ssl_add_cert_to_buf(buf, l, x)) {
831         X509_STORE_CTX_cleanup(&xs_ctx);
832         return 0;
833       }
834     }
835     X509_STORE_CTX_cleanup(&xs_ctx);
836   }
837 
838   return 1;
839 }
840 
841 /* Build a certificate chain for current certificate */
ssl_build_cert_chain(CERT * c,X509_STORE * chain_store,int flags)842 int ssl_build_cert_chain(CERT *c, X509_STORE *chain_store, int flags) {
843   CERT_PKEY *cpk = c->key;
844   X509_STORE_CTX xs_ctx;
845   STACK_OF(X509) *chain = NULL, *untrusted = NULL;
846   X509 *x;
847   int i, rv = 0;
848   uint32_t error;
849 
850   if (!cpk->x509) {
851     OPENSSL_PUT_ERROR(SSL, ssl_build_cert_chain, SSL_R_NO_CERTIFICATE_SET);
852     goto err;
853   }
854 
855   /* Rearranging and check the chain: add everything to a store */
856   if (flags & SSL_BUILD_CHAIN_FLAG_CHECK) {
857     size_t j;
858     chain_store = X509_STORE_new();
859     if (!chain_store) {
860       goto err;
861     }
862 
863     for (j = 0; j < sk_X509_num(cpk->chain); j++) {
864       x = sk_X509_value(cpk->chain, j);
865       if (!X509_STORE_add_cert(chain_store, x)) {
866         error = ERR_peek_last_error();
867         if (ERR_GET_LIB(error) != ERR_LIB_X509 ||
868             ERR_GET_REASON(error) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
869           goto err;
870         }
871         ERR_clear_error();
872       }
873     }
874 
875     /* Add EE cert too: it might be self signed */
876     if (!X509_STORE_add_cert(chain_store, cpk->x509)) {
877       error = ERR_peek_last_error();
878       if (ERR_GET_LIB(error) != ERR_LIB_X509 ||
879           ERR_GET_REASON(error) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
880         goto err;
881       }
882       ERR_clear_error();
883     }
884   } else {
885     if (c->chain_store) {
886       chain_store = c->chain_store;
887     }
888 
889     if (flags & SSL_BUILD_CHAIN_FLAG_UNTRUSTED) {
890       untrusted = cpk->chain;
891     }
892   }
893 
894   if (!X509_STORE_CTX_init(&xs_ctx, chain_store, cpk->x509, untrusted)) {
895     OPENSSL_PUT_ERROR(SSL, ssl_build_cert_chain, ERR_R_X509_LIB);
896     goto err;
897   }
898 
899   i = X509_verify_cert(&xs_ctx);
900   if (i <= 0 && flags & SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR) {
901     if (flags & SSL_BUILD_CHAIN_FLAG_CLEAR_ERROR) {
902       ERR_clear_error();
903     }
904     i = 1;
905     rv = 2;
906   }
907 
908   if (i > 0) {
909     chain = X509_STORE_CTX_get1_chain(&xs_ctx);
910   }
911   if (i <= 0) {
912     OPENSSL_PUT_ERROR(SSL, ssl_build_cert_chain,
913                       SSL_R_CERTIFICATE_VERIFY_FAILED);
914     i = X509_STORE_CTX_get_error(&xs_ctx);
915     ERR_add_error_data(2, "Verify error:", X509_verify_cert_error_string(i));
916 
917     X509_STORE_CTX_cleanup(&xs_ctx);
918     goto err;
919   }
920 
921   X509_STORE_CTX_cleanup(&xs_ctx);
922   if (cpk->chain) {
923     sk_X509_pop_free(cpk->chain, X509_free);
924   }
925 
926   /* Remove EE certificate from chain */
927   x = sk_X509_shift(chain);
928   X509_free(x);
929   if (flags & SSL_BUILD_CHAIN_FLAG_NO_ROOT) {
930     if (sk_X509_num(chain) > 0) {
931       /* See if last cert is self signed */
932       x = sk_X509_value(chain, sk_X509_num(chain) - 1);
933       X509_check_purpose(x, -1, 0);
934       if (x->ex_flags & EXFLAG_SS) {
935         x = sk_X509_pop(chain);
936         X509_free(x);
937       }
938     }
939   }
940 
941   cpk->chain = chain;
942   if (rv == 0) {
943     rv = 1;
944   }
945 
946 err:
947   if (flags & SSL_BUILD_CHAIN_FLAG_CHECK) {
948     X509_STORE_free(chain_store);
949   }
950 
951   return rv;
952 }
953 
ssl_cert_set_cert_store(CERT * c,X509_STORE * store,int chain,int ref)954 int ssl_cert_set_cert_store(CERT *c, X509_STORE *store, int chain, int ref) {
955   X509_STORE **pstore;
956   if (chain) {
957     pstore = &c->chain_store;
958   } else {
959     pstore = &c->verify_store;
960   }
961 
962   X509_STORE_free(*pstore);
963   *pstore = store;
964 
965   if (ref && store) {
966     CRYPTO_refcount_inc(&store->references);
967   }
968   return 1;
969 }
970