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