xref: /freebsd/crypto/openssl/ssl/ssl_cert.c (revision 1323ec571215a77ddd21294f0871979d5ad6b992)
1 /*
2  * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
4  *
5  * Licensed under the OpenSSL license (the "License").  You may not use
6  * this file except in compliance with the License.  You can obtain a copy
7  * in the file LICENSE in the source distribution or at
8  * https://www.openssl.org/source/license.html
9  */
10 
11 #include <stdio.h>
12 #include <sys/types.h>
13 
14 #include "internal/nelem.h"
15 #include "internal/o_dir.h"
16 #include <openssl/bio.h>
17 #include <openssl/pem.h>
18 #include <openssl/x509v3.h>
19 #include <openssl/dh.h>
20 #include <openssl/bn.h>
21 #include <openssl/crypto.h>
22 #include "internal/refcount.h"
23 #include "ssl_local.h"
24 #include "ssl_cert_table.h"
25 #include "internal/thread_once.h"
26 
27 static int ssl_security_default_callback(const SSL *s, const SSL_CTX *ctx,
28                                          int op, int bits, int nid, void *other,
29                                          void *ex);
30 
31 static CRYPTO_ONCE ssl_x509_store_ctx_once = CRYPTO_ONCE_STATIC_INIT;
32 static volatile int ssl_x509_store_ctx_idx = -1;
33 
34 DEFINE_RUN_ONCE_STATIC(ssl_x509_store_ctx_init)
35 {
36     ssl_x509_store_ctx_idx = X509_STORE_CTX_get_ex_new_index(0,
37                                                              "SSL for verify callback",
38                                                              NULL, NULL, NULL);
39     return ssl_x509_store_ctx_idx >= 0;
40 }
41 
42 int SSL_get_ex_data_X509_STORE_CTX_idx(void)
43 {
44 
45     if (!RUN_ONCE(&ssl_x509_store_ctx_once, ssl_x509_store_ctx_init))
46         return -1;
47     return ssl_x509_store_ctx_idx;
48 }
49 
50 CERT *ssl_cert_new(void)
51 {
52     CERT *ret = OPENSSL_zalloc(sizeof(*ret));
53 
54     if (ret == NULL) {
55         SSLerr(SSL_F_SSL_CERT_NEW, ERR_R_MALLOC_FAILURE);
56         return NULL;
57     }
58 
59     ret->key = &(ret->pkeys[SSL_PKEY_RSA]);
60     ret->references = 1;
61     ret->sec_cb = ssl_security_default_callback;
62     ret->sec_level = OPENSSL_TLS_SECURITY_LEVEL;
63     ret->sec_ex = NULL;
64     ret->lock = CRYPTO_THREAD_lock_new();
65     if (ret->lock == NULL) {
66         SSLerr(SSL_F_SSL_CERT_NEW, ERR_R_MALLOC_FAILURE);
67         OPENSSL_free(ret);
68         return NULL;
69     }
70 
71     return ret;
72 }
73 
74 CERT *ssl_cert_dup(CERT *cert)
75 {
76     CERT *ret = OPENSSL_zalloc(sizeof(*ret));
77     int i;
78 
79     if (ret == NULL) {
80         SSLerr(SSL_F_SSL_CERT_DUP, ERR_R_MALLOC_FAILURE);
81         return NULL;
82     }
83 
84     ret->references = 1;
85     ret->key = &ret->pkeys[cert->key - cert->pkeys];
86     ret->lock = CRYPTO_THREAD_lock_new();
87     if (ret->lock == NULL) {
88         SSLerr(SSL_F_SSL_CERT_DUP, ERR_R_MALLOC_FAILURE);
89         OPENSSL_free(ret);
90         return NULL;
91     }
92 #ifndef OPENSSL_NO_DH
93     if (cert->dh_tmp != NULL) {
94         ret->dh_tmp = cert->dh_tmp;
95         EVP_PKEY_up_ref(ret->dh_tmp);
96     }
97     ret->dh_tmp_cb = cert->dh_tmp_cb;
98     ret->dh_tmp_auto = cert->dh_tmp_auto;
99 #endif
100 
101     for (i = 0; i < SSL_PKEY_NUM; i++) {
102         CERT_PKEY *cpk = cert->pkeys + i;
103         CERT_PKEY *rpk = ret->pkeys + i;
104         if (cpk->x509 != NULL) {
105             rpk->x509 = cpk->x509;
106             X509_up_ref(rpk->x509);
107         }
108 
109         if (cpk->privatekey != NULL) {
110             rpk->privatekey = cpk->privatekey;
111             EVP_PKEY_up_ref(cpk->privatekey);
112         }
113 
114         if (cpk->chain) {
115             rpk->chain = X509_chain_up_ref(cpk->chain);
116             if (!rpk->chain) {
117                 SSLerr(SSL_F_SSL_CERT_DUP, ERR_R_MALLOC_FAILURE);
118                 goto err;
119             }
120         }
121         if (cert->pkeys[i].serverinfo != NULL) {
122             /* Just copy everything. */
123             ret->pkeys[i].serverinfo =
124                 OPENSSL_malloc(cert->pkeys[i].serverinfo_length);
125             if (ret->pkeys[i].serverinfo == NULL) {
126                 SSLerr(SSL_F_SSL_CERT_DUP, ERR_R_MALLOC_FAILURE);
127                 goto err;
128             }
129             ret->pkeys[i].serverinfo_length = cert->pkeys[i].serverinfo_length;
130             memcpy(ret->pkeys[i].serverinfo,
131                    cert->pkeys[i].serverinfo, cert->pkeys[i].serverinfo_length);
132         }
133     }
134 
135     /* Configured sigalgs copied across */
136     if (cert->conf_sigalgs) {
137         ret->conf_sigalgs = OPENSSL_malloc(cert->conf_sigalgslen
138                                            * sizeof(*cert->conf_sigalgs));
139         if (ret->conf_sigalgs == NULL)
140             goto err;
141         memcpy(ret->conf_sigalgs, cert->conf_sigalgs,
142                cert->conf_sigalgslen * sizeof(*cert->conf_sigalgs));
143         ret->conf_sigalgslen = cert->conf_sigalgslen;
144     } else
145         ret->conf_sigalgs = NULL;
146 
147     if (cert->client_sigalgs) {
148         ret->client_sigalgs = OPENSSL_malloc(cert->client_sigalgslen
149                                              * sizeof(*cert->client_sigalgs));
150         if (ret->client_sigalgs == NULL)
151             goto err;
152         memcpy(ret->client_sigalgs, cert->client_sigalgs,
153                cert->client_sigalgslen * sizeof(*cert->client_sigalgs));
154         ret->client_sigalgslen = cert->client_sigalgslen;
155     } else
156         ret->client_sigalgs = NULL;
157     /* Copy any custom client certificate types */
158     if (cert->ctype) {
159         ret->ctype = OPENSSL_memdup(cert->ctype, cert->ctype_len);
160         if (ret->ctype == NULL)
161             goto err;
162         ret->ctype_len = cert->ctype_len;
163     }
164 
165     ret->cert_flags = cert->cert_flags;
166 
167     ret->cert_cb = cert->cert_cb;
168     ret->cert_cb_arg = cert->cert_cb_arg;
169 
170     if (cert->verify_store) {
171         X509_STORE_up_ref(cert->verify_store);
172         ret->verify_store = cert->verify_store;
173     }
174 
175     if (cert->chain_store) {
176         X509_STORE_up_ref(cert->chain_store);
177         ret->chain_store = cert->chain_store;
178     }
179 
180     ret->sec_cb = cert->sec_cb;
181     ret->sec_level = cert->sec_level;
182     ret->sec_ex = cert->sec_ex;
183 
184     if (!custom_exts_copy(&ret->custext, &cert->custext))
185         goto err;
186 #ifndef OPENSSL_NO_PSK
187     if (cert->psk_identity_hint) {
188         ret->psk_identity_hint = OPENSSL_strdup(cert->psk_identity_hint);
189         if (ret->psk_identity_hint == NULL)
190             goto err;
191     }
192 #endif
193     return ret;
194 
195  err:
196     ssl_cert_free(ret);
197 
198     return NULL;
199 }
200 
201 /* Free up and clear all certificates and chains */
202 
203 void ssl_cert_clear_certs(CERT *c)
204 {
205     int i;
206     if (c == NULL)
207         return;
208     for (i = 0; i < SSL_PKEY_NUM; i++) {
209         CERT_PKEY *cpk = c->pkeys + i;
210         X509_free(cpk->x509);
211         cpk->x509 = NULL;
212         EVP_PKEY_free(cpk->privatekey);
213         cpk->privatekey = NULL;
214         sk_X509_pop_free(cpk->chain, X509_free);
215         cpk->chain = NULL;
216         OPENSSL_free(cpk->serverinfo);
217         cpk->serverinfo = NULL;
218         cpk->serverinfo_length = 0;
219     }
220 }
221 
222 void ssl_cert_free(CERT *c)
223 {
224     int i;
225 
226     if (c == NULL)
227         return;
228     CRYPTO_DOWN_REF(&c->references, &i, c->lock);
229     REF_PRINT_COUNT("CERT", c);
230     if (i > 0)
231         return;
232     REF_ASSERT_ISNT(i < 0);
233 
234 #ifndef OPENSSL_NO_DH
235     EVP_PKEY_free(c->dh_tmp);
236 #endif
237 
238     ssl_cert_clear_certs(c);
239     OPENSSL_free(c->conf_sigalgs);
240     OPENSSL_free(c->client_sigalgs);
241     OPENSSL_free(c->ctype);
242     X509_STORE_free(c->verify_store);
243     X509_STORE_free(c->chain_store);
244     custom_exts_free(&c->custext);
245 #ifndef OPENSSL_NO_PSK
246     OPENSSL_free(c->psk_identity_hint);
247 #endif
248     CRYPTO_THREAD_lock_free(c->lock);
249     OPENSSL_free(c);
250 }
251 
252 int ssl_cert_set0_chain(SSL *s, SSL_CTX *ctx, STACK_OF(X509) *chain)
253 {
254     int i, r;
255     CERT_PKEY *cpk = s ? s->cert->key : ctx->cert->key;
256     if (!cpk)
257         return 0;
258     for (i = 0; i < sk_X509_num(chain); i++) {
259         r = ssl_security_cert(s, ctx, sk_X509_value(chain, i), 0, 0);
260         if (r != 1) {
261             SSLerr(SSL_F_SSL_CERT_SET0_CHAIN, r);
262             return 0;
263         }
264     }
265     sk_X509_pop_free(cpk->chain, X509_free);
266     cpk->chain = chain;
267     return 1;
268 }
269 
270 int ssl_cert_set1_chain(SSL *s, SSL_CTX *ctx, STACK_OF(X509) *chain)
271 {
272     STACK_OF(X509) *dchain;
273     if (!chain)
274         return ssl_cert_set0_chain(s, ctx, NULL);
275     dchain = X509_chain_up_ref(chain);
276     if (!dchain)
277         return 0;
278     if (!ssl_cert_set0_chain(s, ctx, dchain)) {
279         sk_X509_pop_free(dchain, X509_free);
280         return 0;
281     }
282     return 1;
283 }
284 
285 int ssl_cert_add0_chain_cert(SSL *s, SSL_CTX *ctx, X509 *x)
286 {
287     int r;
288     CERT_PKEY *cpk = s ? s->cert->key : ctx->cert->key;
289     if (!cpk)
290         return 0;
291     r = ssl_security_cert(s, ctx, x, 0, 0);
292     if (r != 1) {
293         SSLerr(SSL_F_SSL_CERT_ADD0_CHAIN_CERT, r);
294         return 0;
295     }
296     if (!cpk->chain)
297         cpk->chain = sk_X509_new_null();
298     if (!cpk->chain || !sk_X509_push(cpk->chain, x))
299         return 0;
300     return 1;
301 }
302 
303 int ssl_cert_add1_chain_cert(SSL *s, SSL_CTX *ctx, X509 *x)
304 {
305     if (!ssl_cert_add0_chain_cert(s, ctx, x))
306         return 0;
307     X509_up_ref(x);
308     return 1;
309 }
310 
311 int ssl_cert_select_current(CERT *c, X509 *x)
312 {
313     int i;
314     if (x == NULL)
315         return 0;
316     for (i = 0; i < SSL_PKEY_NUM; i++) {
317         CERT_PKEY *cpk = c->pkeys + i;
318         if (cpk->x509 == x && cpk->privatekey) {
319             c->key = cpk;
320             return 1;
321         }
322     }
323 
324     for (i = 0; i < SSL_PKEY_NUM; i++) {
325         CERT_PKEY *cpk = c->pkeys + i;
326         if (cpk->privatekey && cpk->x509 && !X509_cmp(cpk->x509, x)) {
327             c->key = cpk;
328             return 1;
329         }
330     }
331     return 0;
332 }
333 
334 int ssl_cert_set_current(CERT *c, long op)
335 {
336     int i, idx;
337     if (!c)
338         return 0;
339     if (op == SSL_CERT_SET_FIRST)
340         idx = 0;
341     else if (op == SSL_CERT_SET_NEXT) {
342         idx = (int)(c->key - c->pkeys + 1);
343         if (idx >= SSL_PKEY_NUM)
344             return 0;
345     } else
346         return 0;
347     for (i = idx; i < SSL_PKEY_NUM; i++) {
348         CERT_PKEY *cpk = c->pkeys + i;
349         if (cpk->x509 && cpk->privatekey) {
350             c->key = cpk;
351             return 1;
352         }
353     }
354     return 0;
355 }
356 
357 void ssl_cert_set_cert_cb(CERT *c, int (*cb) (SSL *ssl, void *arg), void *arg)
358 {
359     c->cert_cb = cb;
360     c->cert_cb_arg = arg;
361 }
362 
363 int ssl_verify_cert_chain(SSL *s, STACK_OF(X509) *sk)
364 {
365     X509 *x;
366     int i = 0;
367     X509_STORE *verify_store;
368     X509_STORE_CTX *ctx = NULL;
369     X509_VERIFY_PARAM *param;
370 
371     if ((sk == NULL) || (sk_X509_num(sk) == 0))
372         return 0;
373 
374     if (s->cert->verify_store)
375         verify_store = s->cert->verify_store;
376     else
377         verify_store = s->ctx->cert_store;
378 
379     ctx = X509_STORE_CTX_new();
380     if (ctx == NULL) {
381         SSLerr(SSL_F_SSL_VERIFY_CERT_CHAIN, ERR_R_MALLOC_FAILURE);
382         return 0;
383     }
384 
385     x = sk_X509_value(sk, 0);
386     if (!X509_STORE_CTX_init(ctx, verify_store, x, sk)) {
387         SSLerr(SSL_F_SSL_VERIFY_CERT_CHAIN, ERR_R_X509_LIB);
388         goto end;
389     }
390     param = X509_STORE_CTX_get0_param(ctx);
391     /*
392      * XXX: Separate @AUTHSECLEVEL and @TLSSECLEVEL would be useful at some
393      * point, for now a single @SECLEVEL sets the same policy for TLS crypto
394      * and PKI authentication.
395      */
396     X509_VERIFY_PARAM_set_auth_level(param, SSL_get_security_level(s));
397 
398     /* Set suite B flags if needed */
399     X509_STORE_CTX_set_flags(ctx, tls1_suiteb(s));
400     if (!X509_STORE_CTX_set_ex_data
401         (ctx, SSL_get_ex_data_X509_STORE_CTX_idx(), s)) {
402         goto end;
403     }
404 
405     /* Verify via DANE if enabled */
406     if (DANETLS_ENABLED(&s->dane))
407         X509_STORE_CTX_set0_dane(ctx, &s->dane);
408 
409     /*
410      * We need to inherit the verify parameters. These can be determined by
411      * the context: if its a server it will verify SSL client certificates or
412      * vice versa.
413      */
414 
415     X509_STORE_CTX_set_default(ctx, s->server ? "ssl_client" : "ssl_server");
416     /*
417      * Anything non-default in "s->param" should overwrite anything in the ctx.
418      */
419     X509_VERIFY_PARAM_set1(param, s->param);
420 
421     if (s->verify_callback)
422         X509_STORE_CTX_set_verify_cb(ctx, s->verify_callback);
423 
424     if (s->ctx->app_verify_callback != NULL)
425         i = s->ctx->app_verify_callback(ctx, s->ctx->app_verify_arg);
426     else
427         i = X509_verify_cert(ctx);
428 
429     s->verify_result = X509_STORE_CTX_get_error(ctx);
430     sk_X509_pop_free(s->verified_chain, X509_free);
431     s->verified_chain = NULL;
432     if (X509_STORE_CTX_get0_chain(ctx) != NULL) {
433         s->verified_chain = X509_STORE_CTX_get1_chain(ctx);
434         if (s->verified_chain == NULL) {
435             SSLerr(SSL_F_SSL_VERIFY_CERT_CHAIN, ERR_R_MALLOC_FAILURE);
436             i = 0;
437         }
438     }
439 
440     /* Move peername from the store context params to the SSL handle's */
441     X509_VERIFY_PARAM_move_peername(s->param, param);
442 
443  end:
444     X509_STORE_CTX_free(ctx);
445     return i;
446 }
447 
448 static void set0_CA_list(STACK_OF(X509_NAME) **ca_list,
449                         STACK_OF(X509_NAME) *name_list)
450 {
451     sk_X509_NAME_pop_free(*ca_list, X509_NAME_free);
452     *ca_list = name_list;
453 }
454 
455 STACK_OF(X509_NAME) *SSL_dup_CA_list(const STACK_OF(X509_NAME) *sk)
456 {
457     int i;
458     const int num = sk_X509_NAME_num(sk);
459     STACK_OF(X509_NAME) *ret;
460     X509_NAME *name;
461 
462     ret = sk_X509_NAME_new_reserve(NULL, num);
463     if (ret == NULL) {
464         SSLerr(SSL_F_SSL_DUP_CA_LIST, ERR_R_MALLOC_FAILURE);
465         return NULL;
466     }
467     for (i = 0; i < num; i++) {
468         name = X509_NAME_dup(sk_X509_NAME_value(sk, i));
469         if (name == NULL) {
470             SSLerr(SSL_F_SSL_DUP_CA_LIST, ERR_R_MALLOC_FAILURE);
471             sk_X509_NAME_pop_free(ret, X509_NAME_free);
472             return NULL;
473         }
474         sk_X509_NAME_push(ret, name);   /* Cannot fail after reserve call */
475     }
476     return ret;
477 }
478 
479 void SSL_set0_CA_list(SSL *s, STACK_OF(X509_NAME) *name_list)
480 {
481     set0_CA_list(&s->ca_names, name_list);
482 }
483 
484 void SSL_CTX_set0_CA_list(SSL_CTX *ctx, STACK_OF(X509_NAME) *name_list)
485 {
486     set0_CA_list(&ctx->ca_names, name_list);
487 }
488 
489 const STACK_OF(X509_NAME) *SSL_CTX_get0_CA_list(const SSL_CTX *ctx)
490 {
491     return ctx->ca_names;
492 }
493 
494 const STACK_OF(X509_NAME) *SSL_get0_CA_list(const SSL *s)
495 {
496     return s->ca_names != NULL ? s->ca_names : s->ctx->ca_names;
497 }
498 
499 void SSL_CTX_set_client_CA_list(SSL_CTX *ctx, STACK_OF(X509_NAME) *name_list)
500 {
501     set0_CA_list(&ctx->client_ca_names, name_list);
502 }
503 
504 STACK_OF(X509_NAME) *SSL_CTX_get_client_CA_list(const SSL_CTX *ctx)
505 {
506     return ctx->client_ca_names;
507 }
508 
509 void SSL_set_client_CA_list(SSL *s, STACK_OF(X509_NAME) *name_list)
510 {
511     set0_CA_list(&s->client_ca_names, name_list);
512 }
513 
514 const STACK_OF(X509_NAME) *SSL_get0_peer_CA_list(const SSL *s)
515 {
516     return s->s3 != NULL ? s->s3->tmp.peer_ca_names : NULL;
517 }
518 
519 STACK_OF(X509_NAME) *SSL_get_client_CA_list(const SSL *s)
520 {
521     if (!s->server)
522         return s->s3 != NULL ?  s->s3->tmp.peer_ca_names : NULL;
523     return s->client_ca_names != NULL ?  s->client_ca_names
524                                       : s->ctx->client_ca_names;
525 }
526 
527 static int add_ca_name(STACK_OF(X509_NAME) **sk, const X509 *x)
528 {
529     X509_NAME *name;
530 
531     if (x == NULL)
532         return 0;
533     if (*sk == NULL && ((*sk = sk_X509_NAME_new_null()) == NULL))
534         return 0;
535 
536     if ((name = X509_NAME_dup(X509_get_subject_name(x))) == NULL)
537         return 0;
538 
539     if (!sk_X509_NAME_push(*sk, name)) {
540         X509_NAME_free(name);
541         return 0;
542     }
543     return 1;
544 }
545 
546 int SSL_add1_to_CA_list(SSL *ssl, const X509 *x)
547 {
548     return add_ca_name(&ssl->ca_names, x);
549 }
550 
551 int SSL_CTX_add1_to_CA_list(SSL_CTX *ctx, const X509 *x)
552 {
553     return add_ca_name(&ctx->ca_names, x);
554 }
555 
556 /*
557  * The following two are older names are to be replaced with
558  * SSL(_CTX)_add1_to_CA_list
559  */
560 int SSL_add_client_CA(SSL *ssl, X509 *x)
561 {
562     return add_ca_name(&ssl->client_ca_names, x);
563 }
564 
565 int SSL_CTX_add_client_CA(SSL_CTX *ctx, X509 *x)
566 {
567     return add_ca_name(&ctx->client_ca_names, x);
568 }
569 
570 static int xname_cmp(const X509_NAME *a, const X509_NAME *b)
571 {
572     unsigned char *abuf = NULL, *bbuf = NULL;
573     int alen, blen, ret;
574 
575     /* X509_NAME_cmp() itself casts away constness in this way, so
576      * assume it's safe:
577      */
578     alen = i2d_X509_NAME((X509_NAME *)a, &abuf);
579     blen = i2d_X509_NAME((X509_NAME *)b, &bbuf);
580 
581     if (alen < 0 || blen < 0)
582         ret = -2;
583     else if (alen != blen)
584         ret = alen - blen;
585     else /* alen == blen */
586         ret = memcmp(abuf, bbuf, alen);
587 
588     OPENSSL_free(abuf);
589     OPENSSL_free(bbuf);
590 
591     return ret;
592 }
593 
594 static int xname_sk_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
595 {
596     return xname_cmp(*a, *b);
597 }
598 
599 static unsigned long xname_hash(const X509_NAME *a)
600 {
601     return X509_NAME_hash((X509_NAME *)a);
602 }
603 
604 STACK_OF(X509_NAME) *SSL_load_client_CA_file(const char *file)
605 {
606     BIO *in = BIO_new(BIO_s_file());
607     X509 *x = NULL;
608     X509_NAME *xn = NULL;
609     STACK_OF(X509_NAME) *ret = NULL;
610     LHASH_OF(X509_NAME) *name_hash = lh_X509_NAME_new(xname_hash, xname_cmp);
611 
612     if ((name_hash == NULL) || (in == NULL)) {
613         SSLerr(SSL_F_SSL_LOAD_CLIENT_CA_FILE, ERR_R_MALLOC_FAILURE);
614         goto err;
615     }
616 
617     if (!BIO_read_filename(in, file))
618         goto err;
619 
620     for (;;) {
621         if (PEM_read_bio_X509(in, &x, NULL, NULL) == NULL)
622             break;
623         if (ret == NULL) {
624             ret = sk_X509_NAME_new_null();
625             if (ret == NULL) {
626                 SSLerr(SSL_F_SSL_LOAD_CLIENT_CA_FILE, ERR_R_MALLOC_FAILURE);
627                 goto err;
628             }
629         }
630         if ((xn = X509_get_subject_name(x)) == NULL)
631             goto err;
632         /* check for duplicates */
633         xn = X509_NAME_dup(xn);
634         if (xn == NULL)
635             goto err;
636         if (lh_X509_NAME_retrieve(name_hash, xn) != NULL) {
637             /* Duplicate. */
638             X509_NAME_free(xn);
639             xn = NULL;
640         } else {
641             lh_X509_NAME_insert(name_hash, xn);
642             if (!sk_X509_NAME_push(ret, xn))
643                 goto err;
644         }
645     }
646     goto done;
647 
648  err:
649     X509_NAME_free(xn);
650     sk_X509_NAME_pop_free(ret, X509_NAME_free);
651     ret = NULL;
652  done:
653     BIO_free(in);
654     X509_free(x);
655     lh_X509_NAME_free(name_hash);
656     if (ret != NULL)
657         ERR_clear_error();
658     return ret;
659 }
660 
661 int SSL_add_file_cert_subjects_to_stack(STACK_OF(X509_NAME) *stack,
662                                         const char *file)
663 {
664     BIO *in;
665     X509 *x = NULL;
666     X509_NAME *xn = NULL;
667     int ret = 1;
668     int (*oldcmp) (const X509_NAME *const *a, const X509_NAME *const *b);
669 
670     oldcmp = sk_X509_NAME_set_cmp_func(stack, xname_sk_cmp);
671 
672     in = BIO_new(BIO_s_file());
673 
674     if (in == NULL) {
675         SSLerr(SSL_F_SSL_ADD_FILE_CERT_SUBJECTS_TO_STACK, ERR_R_MALLOC_FAILURE);
676         goto err;
677     }
678 
679     if (!BIO_read_filename(in, file))
680         goto err;
681 
682     for (;;) {
683         if (PEM_read_bio_X509(in, &x, NULL, NULL) == NULL)
684             break;
685         if ((xn = X509_get_subject_name(x)) == NULL)
686             goto err;
687         xn = X509_NAME_dup(xn);
688         if (xn == NULL)
689             goto err;
690         if (sk_X509_NAME_find(stack, xn) >= 0) {
691             /* Duplicate. */
692             X509_NAME_free(xn);
693         } else if (!sk_X509_NAME_push(stack, xn)) {
694             X509_NAME_free(xn);
695             goto err;
696         }
697     }
698 
699     ERR_clear_error();
700     goto done;
701 
702  err:
703     ret = 0;
704  done:
705     BIO_free(in);
706     X509_free(x);
707     (void)sk_X509_NAME_set_cmp_func(stack, oldcmp);
708     return ret;
709 }
710 
711 int SSL_add_dir_cert_subjects_to_stack(STACK_OF(X509_NAME) *stack,
712                                        const char *dir)
713 {
714     OPENSSL_DIR_CTX *d = NULL;
715     const char *filename;
716     int ret = 0;
717 
718     /* Note that a side effect is that the CAs will be sorted by name */
719 
720     while ((filename = OPENSSL_DIR_read(&d, dir))) {
721         char buf[1024];
722         int r;
723 
724         if (strlen(dir) + strlen(filename) + 2 > sizeof(buf)) {
725             SSLerr(SSL_F_SSL_ADD_DIR_CERT_SUBJECTS_TO_STACK,
726                    SSL_R_PATH_TOO_LONG);
727             goto err;
728         }
729 #ifdef OPENSSL_SYS_VMS
730         r = BIO_snprintf(buf, sizeof(buf), "%s%s", dir, filename);
731 #else
732         r = BIO_snprintf(buf, sizeof(buf), "%s/%s", dir, filename);
733 #endif
734         if (r <= 0 || r >= (int)sizeof(buf))
735             goto err;
736         if (!SSL_add_file_cert_subjects_to_stack(stack, buf))
737             goto err;
738     }
739 
740     if (errno) {
741         SYSerr(SYS_F_OPENDIR, get_last_sys_error());
742         ERR_add_error_data(3, "OPENSSL_DIR_read(&ctx, '", dir, "')");
743         SSLerr(SSL_F_SSL_ADD_DIR_CERT_SUBJECTS_TO_STACK, ERR_R_SYS_LIB);
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 /* Build a certificate chain for current certificate */
757 int ssl_build_cert_chain(SSL *s, SSL_CTX *ctx, int flags)
758 {
759     CERT *c = s ? s->cert : ctx->cert;
760     CERT_PKEY *cpk = c->key;
761     X509_STORE *chain_store = NULL;
762     X509_STORE_CTX *xs_ctx = NULL;
763     STACK_OF(X509) *chain = NULL, *untrusted = NULL;
764     X509 *x;
765     int i, rv = 0;
766 
767     if (!cpk->x509) {
768         SSLerr(SSL_F_SSL_BUILD_CERT_CHAIN, SSL_R_NO_CERTIFICATE_SET);
769         goto err;
770     }
771     /* Rearranging and check the chain: add everything to a store */
772     if (flags & SSL_BUILD_CHAIN_FLAG_CHECK) {
773         chain_store = X509_STORE_new();
774         if (chain_store == NULL)
775             goto err;
776         for (i = 0; i < sk_X509_num(cpk->chain); i++) {
777             x = sk_X509_value(cpk->chain, i);
778             if (!X509_STORE_add_cert(chain_store, x))
779                 goto err;
780         }
781         /* Add EE cert too: it might be self signed */
782         if (!X509_STORE_add_cert(chain_store, cpk->x509))
783             goto err;
784     } else {
785         if (c->chain_store)
786             chain_store = c->chain_store;
787         else if (s)
788             chain_store = s->ctx->cert_store;
789         else
790             chain_store = ctx->cert_store;
791 
792         if (flags & SSL_BUILD_CHAIN_FLAG_UNTRUSTED)
793             untrusted = cpk->chain;
794     }
795 
796     xs_ctx = X509_STORE_CTX_new();
797     if (xs_ctx == NULL) {
798         SSLerr(SSL_F_SSL_BUILD_CERT_CHAIN, ERR_R_MALLOC_FAILURE);
799         goto err;
800     }
801     if (!X509_STORE_CTX_init(xs_ctx, chain_store, cpk->x509, untrusted)) {
802         SSLerr(SSL_F_SSL_BUILD_CERT_CHAIN, ERR_R_X509_LIB);
803         goto err;
804     }
805     /* Set suite B flags if needed */
806     X509_STORE_CTX_set_flags(xs_ctx,
807                              c->cert_flags & SSL_CERT_FLAG_SUITEB_128_LOS);
808 
809     i = X509_verify_cert(xs_ctx);
810     if (i <= 0 && flags & SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR) {
811         if (flags & SSL_BUILD_CHAIN_FLAG_CLEAR_ERROR)
812             ERR_clear_error();
813         i = 1;
814         rv = 2;
815     }
816     if (i > 0)
817         chain = X509_STORE_CTX_get1_chain(xs_ctx);
818     if (i <= 0) {
819         SSLerr(SSL_F_SSL_BUILD_CERT_CHAIN, SSL_R_CERTIFICATE_VERIFY_FAILED);
820         i = X509_STORE_CTX_get_error(xs_ctx);
821         ERR_add_error_data(2, "Verify error:",
822                            X509_verify_cert_error_string(i));
823 
824         goto err;
825     }
826     /* Remove EE certificate from chain */
827     x = sk_X509_shift(chain);
828     X509_free(x);
829     if (flags & SSL_BUILD_CHAIN_FLAG_NO_ROOT) {
830         if (sk_X509_num(chain) > 0) {
831             /* See if last cert is self signed */
832             x = sk_X509_value(chain, sk_X509_num(chain) - 1);
833             if (X509_get_extension_flags(x) & EXFLAG_SS) {
834                 x = sk_X509_pop(chain);
835                 X509_free(x);
836             }
837         }
838     }
839     /*
840      * Check security level of all CA certificates: EE will have been checked
841      * already.
842      */
843     for (i = 0; i < sk_X509_num(chain); i++) {
844         x = sk_X509_value(chain, i);
845         rv = ssl_security_cert(s, ctx, x, 0, 0);
846         if (rv != 1) {
847             SSLerr(SSL_F_SSL_BUILD_CERT_CHAIN, rv);
848             sk_X509_pop_free(chain, X509_free);
849             rv = 0;
850             goto err;
851         }
852     }
853     sk_X509_pop_free(cpk->chain, X509_free);
854     cpk->chain = chain;
855     if (rv == 0)
856         rv = 1;
857  err:
858     if (flags & SSL_BUILD_CHAIN_FLAG_CHECK)
859         X509_STORE_free(chain_store);
860     X509_STORE_CTX_free(xs_ctx);
861 
862     return rv;
863 }
864 
865 int ssl_cert_set_cert_store(CERT *c, X509_STORE *store, int chain, int ref)
866 {
867     X509_STORE **pstore;
868     if (chain)
869         pstore = &c->chain_store;
870     else
871         pstore = &c->verify_store;
872     X509_STORE_free(*pstore);
873     *pstore = store;
874     if (ref && store)
875         X509_STORE_up_ref(store);
876     return 1;
877 }
878 
879 int ssl_get_security_level_bits(const SSL *s, const SSL_CTX *ctx, int *levelp)
880 {
881     int level;
882     static const int minbits_table[5 + 1] = { 0, 80, 112, 128, 192, 256 };
883 
884     if (ctx != NULL)
885         level = SSL_CTX_get_security_level(ctx);
886     else
887         level = SSL_get_security_level(s);
888 
889     if (level > 5)
890         level = 5;
891     else if (level < 0)
892         level = 0;
893 
894     if (levelp != NULL)
895         *levelp = level;
896 
897     return minbits_table[level];
898 }
899 
900 static int ssl_security_default_callback(const SSL *s, const SSL_CTX *ctx,
901                                          int op, int bits, int nid, void *other,
902                                          void *ex)
903 {
904     int level, minbits, pfs_mask;
905 
906     minbits = ssl_get_security_level_bits(s, ctx, &level);
907 
908     if (level == 0) {
909         /*
910          * No EDH keys weaker than 1024-bits even at level 0, otherwise,
911          * anything goes.
912          */
913         if (op == SSL_SECOP_TMP_DH && bits < 80)
914             return 0;
915         return 1;
916     }
917     switch (op) {
918     case SSL_SECOP_CIPHER_SUPPORTED:
919     case SSL_SECOP_CIPHER_SHARED:
920     case SSL_SECOP_CIPHER_CHECK:
921         {
922             const SSL_CIPHER *c = other;
923             /* No ciphers below security level */
924             if (bits < minbits)
925                 return 0;
926             /* No unauthenticated ciphersuites */
927             if (c->algorithm_auth & SSL_aNULL)
928                 return 0;
929             /* No MD5 mac ciphersuites */
930             if (c->algorithm_mac & SSL_MD5)
931                 return 0;
932             /* SHA1 HMAC is 160 bits of security */
933             if (minbits > 160 && c->algorithm_mac & SSL_SHA1)
934                 return 0;
935             /* Level 2: no RC4 */
936             if (level >= 2 && c->algorithm_enc == SSL_RC4)
937                 return 0;
938             /* Level 3: forward secure ciphersuites only */
939             pfs_mask = SSL_kDHE | SSL_kECDHE | SSL_kDHEPSK | SSL_kECDHEPSK;
940             if (level >= 3 && c->min_tls != TLS1_3_VERSION &&
941                                !(c->algorithm_mkey & pfs_mask))
942                 return 0;
943             break;
944         }
945     case SSL_SECOP_VERSION:
946         if (!SSL_IS_DTLS(s)) {
947             /* SSLv3 not allowed at level 2 */
948             if (nid <= SSL3_VERSION && level >= 2)
949                 return 0;
950             /* TLS v1.1 and above only for level 3 */
951             if (nid <= TLS1_VERSION && level >= 3)
952                 return 0;
953             /* TLS v1.2 only for level 4 and above */
954             if (nid <= TLS1_1_VERSION && level >= 4)
955                 return 0;
956         } else {
957             /* DTLS v1.2 only for level 4 and above */
958             if (DTLS_VERSION_LT(nid, DTLS1_2_VERSION) && level >= 4)
959                 return 0;
960         }
961         break;
962 
963     case SSL_SECOP_COMPRESSION:
964         if (level >= 2)
965             return 0;
966         break;
967     case SSL_SECOP_TICKET:
968         if (level >= 3)
969             return 0;
970         break;
971     default:
972         if (bits < minbits)
973             return 0;
974     }
975     return 1;
976 }
977 
978 int ssl_security(const SSL *s, int op, int bits, int nid, void *other)
979 {
980     return s->cert->sec_cb(s, NULL, op, bits, nid, other, s->cert->sec_ex);
981 }
982 
983 int ssl_ctx_security(const SSL_CTX *ctx, int op, int bits, int nid, void *other)
984 {
985     return ctx->cert->sec_cb(NULL, ctx, op, bits, nid, other,
986                              ctx->cert->sec_ex);
987 }
988 
989 int ssl_cert_lookup_by_nid(int nid, size_t *pidx)
990 {
991     size_t i;
992 
993     for (i = 0; i < OSSL_NELEM(ssl_cert_info); i++) {
994         if (ssl_cert_info[i].nid == nid) {
995             *pidx = i;
996             return 1;
997         }
998     }
999 
1000     return 0;
1001 }
1002 
1003 const SSL_CERT_LOOKUP *ssl_cert_lookup_by_pkey(const EVP_PKEY *pk, size_t *pidx)
1004 {
1005     int nid = EVP_PKEY_id(pk);
1006     size_t tmpidx;
1007 
1008     if (nid == NID_undef)
1009         return NULL;
1010 
1011     if (!ssl_cert_lookup_by_nid(nid, &tmpidx))
1012         return NULL;
1013 
1014     if (pidx != NULL)
1015         *pidx = tmpidx;
1016 
1017     return &ssl_cert_info[tmpidx];
1018 }
1019 
1020 const SSL_CERT_LOOKUP *ssl_cert_lookup_by_idx(size_t idx)
1021 {
1022     if (idx >= OSSL_NELEM(ssl_cert_info))
1023         return NULL;
1024     return &ssl_cert_info[idx];
1025 }
1026