ssl/statem: Replace size_t with int and add the checks
[openssl.git] / crypto / x509 / v3_purp.c
1 /*
2  * Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <stdio.h>
11 #include "internal/cryptlib.h"
12 #include "internal/numbers.h"
13 #include <openssl/x509v3.h>
14 #include <openssl/x509_vfy.h>
15 #include "crypto/x509.h"
16 #include "internal/tsan_assist.h"
17 #include "x509_local.h"
18
19 static int check_ssl_ca(const X509 *x);
20 static int check_purpose_ssl_client(const X509_PURPOSE *xp, const X509 *x,
21                                     int require_ca);
22 static int check_purpose_ssl_server(const X509_PURPOSE *xp, const X509 *x,
23                                     int require_ca);
24 static int check_purpose_ns_ssl_server(const X509_PURPOSE *xp, const X509 *x,
25                                        int require_ca);
26 static int purpose_smime(const X509 *x, int require_ca);
27 static int check_purpose_smime_sign(const X509_PURPOSE *xp, const X509 *x,
28                                     int require_ca);
29 static int check_purpose_smime_encrypt(const X509_PURPOSE *xp, const X509 *x,
30                                        int require_ca);
31 static int check_purpose_crl_sign(const X509_PURPOSE *xp, const X509 *x,
32                                   int require_ca);
33 static int check_purpose_timestamp_sign(const X509_PURPOSE *xp, const X509 *x,
34                                         int require_ca);
35 static int check_purpose_code_sign(const X509_PURPOSE *xp, const X509 *x,
36                                         int require_ca);
37 static int no_check_purpose(const X509_PURPOSE *xp, const X509 *x,
38                             int require_ca);
39 static int check_purpose_ocsp_helper(const X509_PURPOSE *xp, const X509 *x,
40                                      int require_ca);
41
42 static int xp_cmp(const X509_PURPOSE *const *a, const X509_PURPOSE *const *b);
43 static void xptable_free(X509_PURPOSE *p);
44
45 static X509_PURPOSE xstandard[] = {
46     {X509_PURPOSE_SSL_CLIENT, X509_TRUST_SSL_CLIENT, 0,
47      check_purpose_ssl_client, "SSL client", "sslclient", NULL},
48     {X509_PURPOSE_SSL_SERVER, X509_TRUST_SSL_SERVER, 0,
49      check_purpose_ssl_server, "SSL server", "sslserver", NULL},
50     {X509_PURPOSE_NS_SSL_SERVER, X509_TRUST_SSL_SERVER, 0,
51      check_purpose_ns_ssl_server, "Netscape SSL server", "nssslserver", NULL},
52     {X509_PURPOSE_SMIME_SIGN, X509_TRUST_EMAIL, 0, check_purpose_smime_sign,
53      "S/MIME signing", "smimesign", NULL},
54     {X509_PURPOSE_SMIME_ENCRYPT, X509_TRUST_EMAIL, 0,
55      check_purpose_smime_encrypt, "S/MIME encryption", "smimeencrypt", NULL},
56     {X509_PURPOSE_CRL_SIGN, X509_TRUST_COMPAT, 0, check_purpose_crl_sign,
57      "CRL signing", "crlsign", NULL},
58     {X509_PURPOSE_ANY, X509_TRUST_DEFAULT, 0, no_check_purpose,
59      "Any Purpose", "any",
60      NULL},
61     {X509_PURPOSE_OCSP_HELPER, X509_TRUST_COMPAT, 0, check_purpose_ocsp_helper,
62      "OCSP helper", "ocsphelper", NULL},
63     {X509_PURPOSE_TIMESTAMP_SIGN, X509_TRUST_TSA, 0,
64      check_purpose_timestamp_sign, "Time Stamp signing", "timestampsign",
65      NULL},
66     {X509_PURPOSE_CODE_SIGN, X509_TRUST_OBJECT_SIGN, 0,
67      check_purpose_code_sign, "Code signing", "codesign",
68      NULL},
69 };
70
71 #define X509_PURPOSE_COUNT OSSL_NELEM(xstandard)
72
73 static STACK_OF(X509_PURPOSE) *xptable = NULL;
74
75 static int xp_cmp(const X509_PURPOSE *const *a, const X509_PURPOSE *const *b)
76 {
77     return (*a)->purpose - (*b)->purpose;
78 }
79
80 /*
81  * As much as I'd like to make X509_check_purpose use a "const" X509* I really
82  * can't because it does recalculate hashes and do other non-const things.
83  * If id == -1 it just calls x509v3_cache_extensions() for its side-effect.
84  * Returns 1 on success, 0 if x does not allow purpose, -1 on (internal) error.
85  */
86 int X509_check_purpose(X509 *x, int id, int require_ca)
87 {
88     int idx;
89     const X509_PURPOSE *pt;
90
91     if (!ossl_x509v3_cache_extensions(x))
92         return -1;
93     if (id == -1)
94         return 1;
95
96     idx = X509_PURPOSE_get_by_id(id);
97     if (idx == -1)
98         return -1;
99     pt = X509_PURPOSE_get0(idx);
100     return pt->check_purpose(pt, x, require_ca);
101 }
102
103 int X509_PURPOSE_set(int *p, int purpose)
104 {
105     if (X509_PURPOSE_get_by_id(purpose) == -1) {
106         ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_PURPOSE);
107         return 0;
108     }
109     *p = purpose;
110     return 1;
111 }
112
113 int X509_PURPOSE_get_count(void)
114 {
115     if (!xptable)
116         return X509_PURPOSE_COUNT;
117     return sk_X509_PURPOSE_num(xptable) + X509_PURPOSE_COUNT;
118 }
119
120 X509_PURPOSE *X509_PURPOSE_get0(int idx)
121 {
122     if (idx < 0)
123         return NULL;
124     if (idx < (int)X509_PURPOSE_COUNT)
125         return xstandard + idx;
126     return sk_X509_PURPOSE_value(xptable, idx - X509_PURPOSE_COUNT);
127 }
128
129 int X509_PURPOSE_get_by_sname(const char *sname)
130 {
131     int i;
132     X509_PURPOSE *xptmp;
133
134     for (i = 0; i < X509_PURPOSE_get_count(); i++) {
135         xptmp = X509_PURPOSE_get0(i);
136         if (strcmp(xptmp->sname, sname) == 0)
137             return i;
138     }
139     return -1;
140 }
141
142 /* Returns -1 on error, else an index => 0 in standard/extended purpose table */
143 int X509_PURPOSE_get_by_id(int purpose)
144 {
145     X509_PURPOSE tmp;
146     int idx;
147
148     if (purpose >= X509_PURPOSE_MIN && purpose <= X509_PURPOSE_MAX)
149         return purpose - X509_PURPOSE_MIN;
150     if (xptable == NULL)
151         return -1;
152     tmp.purpose = purpose;
153     idx = sk_X509_PURPOSE_find(xptable, &tmp);
154     if (idx < 0)
155         return -1;
156     return idx + X509_PURPOSE_COUNT;
157 }
158
159 int X509_PURPOSE_add(int id, int trust, int flags,
160                      int (*ck) (const X509_PURPOSE *, const X509 *, int),
161                      const char *name, const char *sname, void *arg)
162 {
163     int idx;
164     X509_PURPOSE *ptmp;
165
166     /* This is set according to what we change: application can't set it */
167     flags &= ~X509_PURPOSE_DYNAMIC;
168     /* This will always be set for application modified trust entries */
169     flags |= X509_PURPOSE_DYNAMIC_NAME;
170     /* Get existing entry if any */
171     idx = X509_PURPOSE_get_by_id(id);
172     /* Need a new entry */
173     if (idx == -1) {
174         if ((ptmp = OPENSSL_malloc(sizeof(*ptmp))) == NULL) {
175             ERR_raise(ERR_LIB_X509V3, ERR_R_MALLOC_FAILURE);
176             return 0;
177         }
178         ptmp->flags = X509_PURPOSE_DYNAMIC;
179     } else {
180         ptmp = X509_PURPOSE_get0(idx);
181     }
182
183     /* OPENSSL_free existing name if dynamic */
184     if ((ptmp->flags & X509_PURPOSE_DYNAMIC_NAME) != 0) {
185         OPENSSL_free(ptmp->name);
186         OPENSSL_free(ptmp->sname);
187     }
188     /* Dup supplied name */
189     ptmp->name = OPENSSL_strdup(name);
190     ptmp->sname = OPENSSL_strdup(sname);
191     if (ptmp->name == NULL || ptmp->sname == NULL) {
192         ERR_raise(ERR_LIB_X509V3, ERR_R_MALLOC_FAILURE);
193         goto err;
194     }
195     /* Keep the dynamic flag of existing entry */
196     ptmp->flags &= X509_PURPOSE_DYNAMIC;
197     /* Set all other flags */
198     ptmp->flags |= flags;
199
200     ptmp->purpose = id;
201     ptmp->trust = trust;
202     ptmp->check_purpose = ck;
203     ptmp->usr_data = arg;
204
205     /* If its a new entry manage the dynamic table */
206     if (idx == -1) {
207         if (xptable == NULL
208             && (xptable = sk_X509_PURPOSE_new(xp_cmp)) == NULL) {
209             ERR_raise(ERR_LIB_X509V3, ERR_R_MALLOC_FAILURE);
210             goto err;
211         }
212         if (!sk_X509_PURPOSE_push(xptable, ptmp)) {
213             ERR_raise(ERR_LIB_X509V3, ERR_R_MALLOC_FAILURE);
214             goto err;
215         }
216     }
217     return 1;
218  err:
219     if (idx == -1) {
220         OPENSSL_free(ptmp->name);
221         OPENSSL_free(ptmp->sname);
222         OPENSSL_free(ptmp);
223     }
224     return 0;
225 }
226
227 static void xptable_free(X509_PURPOSE *p)
228 {
229     if (p == NULL)
230         return;
231     if ((p->flags & X509_PURPOSE_DYNAMIC) != 0) {
232         if ((p->flags & X509_PURPOSE_DYNAMIC_NAME) != 0) {
233             OPENSSL_free(p->name);
234             OPENSSL_free(p->sname);
235         }
236         OPENSSL_free(p);
237     }
238 }
239
240 void X509_PURPOSE_cleanup(void)
241 {
242     sk_X509_PURPOSE_pop_free(xptable, xptable_free);
243     xptable = NULL;
244 }
245
246 int X509_PURPOSE_get_id(const X509_PURPOSE *xp)
247 {
248     return xp->purpose;
249 }
250
251 char *X509_PURPOSE_get0_name(const X509_PURPOSE *xp)
252 {
253     return xp->name;
254 }
255
256 char *X509_PURPOSE_get0_sname(const X509_PURPOSE *xp)
257 {
258     return xp->sname;
259 }
260
261 int X509_PURPOSE_get_trust(const X509_PURPOSE *xp)
262 {
263     return xp->trust;
264 }
265
266 static int nid_cmp(const int *a, const int *b)
267 {
268     return *a - *b;
269 }
270
271 DECLARE_OBJ_BSEARCH_CMP_FN(int, int, nid);
272 IMPLEMENT_OBJ_BSEARCH_CMP_FN(int, int, nid);
273
274 int X509_supported_extension(X509_EXTENSION *ex)
275 {
276     /*
277      * This table is a list of the NIDs of supported extensions: that is
278      * those which are used by the verify process. If an extension is
279      * critical and doesn't appear in this list then the verify process will
280      * normally reject the certificate. The list must be kept in numerical
281      * order because it will be searched using bsearch.
282      */
283     static const int supported_nids[] = {
284         NID_netscape_cert_type, /* 71 */
285         NID_key_usage,          /* 83 */
286         NID_subject_alt_name,   /* 85 */
287         NID_basic_constraints,  /* 87 */
288         NID_certificate_policies, /* 89 */
289         NID_crl_distribution_points, /* 103 */
290         NID_ext_key_usage,      /* 126 */
291 #ifndef OPENSSL_NO_RFC3779
292         NID_sbgp_ipAddrBlock,   /* 290 */
293         NID_sbgp_autonomousSysNum, /* 291 */
294 #endif
295         NID_id_pkix_OCSP_noCheck, /* 369 */
296         NID_policy_constraints, /* 401 */
297         NID_proxyCertInfo,      /* 663 */
298         NID_name_constraints,   /* 666 */
299         NID_policy_mappings,    /* 747 */
300         NID_inhibit_any_policy  /* 748 */
301     };
302
303     int ex_nid = OBJ_obj2nid(X509_EXTENSION_get_object(ex));
304
305     if (ex_nid == NID_undef)
306         return 0;
307
308     if (OBJ_bsearch_nid(&ex_nid, supported_nids, OSSL_NELEM(supported_nids)))
309         return 1;
310     return 0;
311 }
312
313 /* Returns 1 on success, 0 if x is invalid, -1 on (internal) error. */
314 static int setup_dp(const X509 *x, DIST_POINT *dp)
315 {
316     const X509_NAME *iname = NULL;
317     int i;
318
319     if (dp->distpoint == NULL && sk_GENERAL_NAME_num(dp->CRLissuer) <= 0) {
320         ERR_raise(ERR_LIB_X509, X509_R_INVALID_DISTPOINT);
321         return 0;
322     }
323     if (dp->reasons != NULL) {
324         if (dp->reasons->length > 0)
325             dp->dp_reasons = dp->reasons->data[0];
326         if (dp->reasons->length > 1)
327             dp->dp_reasons |= (dp->reasons->data[1] << 8);
328         dp->dp_reasons &= CRLDP_ALL_REASONS;
329     } else {
330         dp->dp_reasons = CRLDP_ALL_REASONS;
331     }
332     if (dp->distpoint == NULL || dp->distpoint->type != 1)
333         return 1;
334
335     /* Handle name fragment given by nameRelativeToCRLIssuer */
336     /*
337      * Note that the below way of determining iname is not really compliant
338      * with https://tools.ietf.org/html/rfc5280#section-4.2.1.13
339      * According to it, sk_GENERAL_NAME_num(dp->CRLissuer) MUST be <= 1
340      * and any CRLissuer could be of type different to GEN_DIRNAME.
341      */
342     for (i = 0; i < sk_GENERAL_NAME_num(dp->CRLissuer); i++) {
343         GENERAL_NAME *gen = sk_GENERAL_NAME_value(dp->CRLissuer, i);
344
345         if (gen->type == GEN_DIRNAME) {
346             iname = gen->d.directoryName;
347             break;
348         }
349     }
350     if (iname == NULL)
351         iname = X509_get_issuer_name(x);
352     return DIST_POINT_set_dpname(dp->distpoint, iname) ? 1 : -1;
353 }
354
355 /* Return 1 on success, 0 if x is invalid, -1 on (internal) error. */
356 static int setup_crldp(X509 *x)
357 {
358     int i;
359
360     x->crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, &i, NULL);
361     if (x->crldp == NULL && i != -1)
362         return 0;
363
364     for (i = 0; i < sk_DIST_POINT_num(x->crldp); i++) {
365         int res = setup_dp(x, sk_DIST_POINT_value(x->crldp, i));
366
367         if (res < 1)
368             return res;
369     }
370     return 1;
371 }
372
373 /* Check that issuer public key algorithm matches subject signature algorithm */
374 static int check_sig_alg_match(const EVP_PKEY *issuer_key, const X509 *subject)
375 {
376     int subj_sig_nid;
377
378     if (issuer_key == NULL)
379         return X509_V_ERR_NO_ISSUER_PUBLIC_KEY;
380     if (OBJ_find_sigid_algs(OBJ_obj2nid(subject->cert_info.signature.algorithm),
381                             NULL, &subj_sig_nid) == 0)
382         return X509_V_ERR_UNSUPPORTED_SIGNATURE_ALGORITHM;
383     if (EVP_PKEY_is_a(issuer_key, OBJ_nid2sn(subj_sig_nid))
384         || (EVP_PKEY_is_a(issuer_key, "RSA") && subj_sig_nid == NID_rsassaPss))
385         return X509_V_OK;
386     return X509_V_ERR_SIGNATURE_ALGORITHM_MISMATCH;
387 }
388
389 #define V1_ROOT (EXFLAG_V1 | EXFLAG_SS)
390 #define ku_reject(x, usage) \
391     (((x)->ex_flags & EXFLAG_KUSAGE) != 0 && ((x)->ex_kusage & (usage)) == 0)
392 #define xku_reject(x, usage) \
393     (((x)->ex_flags & EXFLAG_XKUSAGE) != 0 && ((x)->ex_xkusage & (usage)) == 0)
394 #define ns_reject(x, usage) \
395     (((x)->ex_flags & EXFLAG_NSCERT) != 0 && ((x)->ex_nscert & (usage)) == 0)
396
397 /*
398  * Cache info on various X.509v3 extensions and further derived information,
399  * e.g., if cert 'x' is self-issued, in x->ex_flags and other internal fields.
400  * x->sha1_hash is filled in, or else EXFLAG_NO_FINGERPRINT is set in x->flags.
401  * X509_SIG_INFO_VALID is set in x->flags if x->siginf was filled successfully.
402  * Set EXFLAG_INVALID and return 0 in case the certificate is invalid.
403  */
404 int ossl_x509v3_cache_extensions(X509 *x)
405 {
406     BASIC_CONSTRAINTS *bs;
407     PROXY_CERT_INFO_EXTENSION *pci;
408     ASN1_BIT_STRING *usage;
409     ASN1_BIT_STRING *ns;
410     EXTENDED_KEY_USAGE *extusage;
411     int i;
412     int res;
413
414 #ifdef tsan_ld_acq
415     /* Fast lock-free check, see end of the function for details. */
416     if (tsan_ld_acq((TSAN_QUALIFIER int *)&x->ex_cached))
417         return (x->ex_flags & EXFLAG_INVALID) == 0;
418 #endif
419
420     if (!CRYPTO_THREAD_write_lock(x->lock))
421         return 0;
422     if ((x->ex_flags & EXFLAG_SET) != 0) { /* Cert has already been processed */
423         CRYPTO_THREAD_unlock(x->lock);
424         return (x->ex_flags & EXFLAG_INVALID) == 0;
425     }
426
427     ERR_set_mark();
428
429     /* Cache the SHA1 digest of the cert */
430     if (!X509_digest(x, EVP_sha1(), x->sha1_hash, NULL))
431         x->ex_flags |= EXFLAG_NO_FINGERPRINT;
432
433     /* V1 should mean no extensions ... */
434     if (X509_get_version(x) == X509_VERSION_1)
435         x->ex_flags |= EXFLAG_V1;
436
437     /* Handle basic constraints */
438     x->ex_pathlen = -1;
439     if ((bs = X509_get_ext_d2i(x, NID_basic_constraints, &i, NULL)) != NULL) {
440         if (bs->ca)
441             x->ex_flags |= EXFLAG_CA;
442         if (bs->pathlen != NULL) {
443             /*
444              * The error case !bs->ca is checked by check_chain()
445              * in case ctx->param->flags & X509_V_FLAG_X509_STRICT
446              */
447             if (bs->pathlen->type == V_ASN1_NEG_INTEGER) {
448                 ERR_raise(ERR_LIB_X509, X509V3_R_NEGATIVE_PATHLEN);
449                 x->ex_flags |= EXFLAG_INVALID;
450             } else {
451                 x->ex_pathlen = ASN1_INTEGER_get(bs->pathlen);
452             }
453         }
454         BASIC_CONSTRAINTS_free(bs);
455         x->ex_flags |= EXFLAG_BCONS;
456     } else if (i != -1) {
457         x->ex_flags |= EXFLAG_INVALID;
458     }
459
460     /* Handle proxy certificates */
461     if ((pci = X509_get_ext_d2i(x, NID_proxyCertInfo, &i, NULL)) != NULL) {
462         if ((x->ex_flags & EXFLAG_CA) != 0
463             || X509_get_ext_by_NID(x, NID_subject_alt_name, -1) >= 0
464             || X509_get_ext_by_NID(x, NID_issuer_alt_name, -1) >= 0) {
465             x->ex_flags |= EXFLAG_INVALID;
466         }
467         if (pci->pcPathLengthConstraint != NULL)
468             x->ex_pcpathlen = ASN1_INTEGER_get(pci->pcPathLengthConstraint);
469         else
470             x->ex_pcpathlen = -1;
471         PROXY_CERT_INFO_EXTENSION_free(pci);
472         x->ex_flags |= EXFLAG_PROXY;
473     } else if (i != -1) {
474         x->ex_flags |= EXFLAG_INVALID;
475     }
476
477     /* Handle (basic) key usage */
478     if ((usage = X509_get_ext_d2i(x, NID_key_usage, &i, NULL)) != NULL) {
479         x->ex_kusage = 0;
480         if (usage->length > 0) {
481             x->ex_kusage = usage->data[0];
482             if (usage->length > 1)
483                 x->ex_kusage |= usage->data[1] << 8;
484         }
485         x->ex_flags |= EXFLAG_KUSAGE;
486         ASN1_BIT_STRING_free(usage);
487         /* Check for empty key usage according to RFC 5280 section 4.2.1.3 */
488         if (x->ex_kusage == 0) {
489             ERR_raise(ERR_LIB_X509, X509V3_R_EMPTY_KEY_USAGE);
490             x->ex_flags |= EXFLAG_INVALID;
491         }
492     } else if (i != -1) {
493         x->ex_flags |= EXFLAG_INVALID;
494     }
495
496     /* Handle extended key usage */
497     x->ex_xkusage = 0;
498     if ((extusage = X509_get_ext_d2i(x, NID_ext_key_usage, &i, NULL)) != NULL) {
499         x->ex_flags |= EXFLAG_XKUSAGE;
500         for (i = 0; i < sk_ASN1_OBJECT_num(extusage); i++) {
501             switch (OBJ_obj2nid(sk_ASN1_OBJECT_value(extusage, i))) {
502             case NID_server_auth:
503                 x->ex_xkusage |= XKU_SSL_SERVER;
504                 break;
505             case NID_client_auth:
506                 x->ex_xkusage |= XKU_SSL_CLIENT;
507                 break;
508             case NID_email_protect:
509                 x->ex_xkusage |= XKU_SMIME;
510                 break;
511             case NID_code_sign:
512                 x->ex_xkusage |= XKU_CODE_SIGN;
513                 break;
514             case NID_ms_sgc:
515             case NID_ns_sgc:
516                 x->ex_xkusage |= XKU_SGC;
517                 break;
518             case NID_OCSP_sign:
519                 x->ex_xkusage |= XKU_OCSP_SIGN;
520                 break;
521             case NID_time_stamp:
522                 x->ex_xkusage |= XKU_TIMESTAMP;
523                 break;
524             case NID_dvcs:
525                 x->ex_xkusage |= XKU_DVCS;
526                 break;
527             case NID_anyExtendedKeyUsage:
528                 x->ex_xkusage |= XKU_ANYEKU;
529                 break;
530             default:
531                 /* Ignore unknown extended key usage */
532                 break;
533             }
534         }
535         sk_ASN1_OBJECT_pop_free(extusage, ASN1_OBJECT_free);
536     } else if (i != -1) {
537         x->ex_flags |= EXFLAG_INVALID;
538     }
539
540     /* Handle legacy Netscape extension */
541     if ((ns = X509_get_ext_d2i(x, NID_netscape_cert_type, &i, NULL)) != NULL) {
542         if (ns->length > 0)
543             x->ex_nscert = ns->data[0];
544         else
545             x->ex_nscert = 0;
546         x->ex_flags |= EXFLAG_NSCERT;
547         ASN1_BIT_STRING_free(ns);
548     } else if (i != -1) {
549         x->ex_flags |= EXFLAG_INVALID;
550     }
551
552     /* Handle subject key identifier and issuer/authority key identifier */
553     x->skid = X509_get_ext_d2i(x, NID_subject_key_identifier, &i, NULL);
554     if (x->skid == NULL && i != -1)
555         x->ex_flags |= EXFLAG_INVALID;
556
557     x->akid = X509_get_ext_d2i(x, NID_authority_key_identifier, &i, NULL);
558     if (x->akid == NULL && i != -1)
559         x->ex_flags |= EXFLAG_INVALID;
560
561     /* Check if subject name matches issuer */
562     if (X509_NAME_cmp(X509_get_subject_name(x), X509_get_issuer_name(x)) == 0) {
563         x->ex_flags |= EXFLAG_SI; /* Cert is self-issued */
564         if (X509_check_akid(x, x->akid) == X509_V_OK /* SKID matches AKID */
565                 /* .. and the signature alg matches the PUBKEY alg: */
566                 && check_sig_alg_match(X509_get0_pubkey(x), x) == X509_V_OK)
567             x->ex_flags |= EXFLAG_SS; /* indicate self-signed */
568         /* This is very related to ossl_x509_likely_issued(x, x) == X509_V_OK */
569     }
570
571     /* Handle subject alternative names and various other extensions */
572     x->altname = X509_get_ext_d2i(x, NID_subject_alt_name, &i, NULL);
573     if (x->altname == NULL && i != -1)
574         x->ex_flags |= EXFLAG_INVALID;
575     x->nc = X509_get_ext_d2i(x, NID_name_constraints, &i, NULL);
576     if (x->nc == NULL && i != -1)
577         x->ex_flags |= EXFLAG_INVALID;
578
579     /* Handle CRL distribution point entries */
580     res = setup_crldp(x);
581     if (res == 0)
582         x->ex_flags |= EXFLAG_INVALID;
583
584 #ifndef OPENSSL_NO_RFC3779
585     x->rfc3779_addr = X509_get_ext_d2i(x, NID_sbgp_ipAddrBlock, &i, NULL);
586     if (x->rfc3779_addr == NULL && i != -1)
587         x->ex_flags |= EXFLAG_INVALID;
588     x->rfc3779_asid = X509_get_ext_d2i(x, NID_sbgp_autonomousSysNum, &i, NULL);
589     if (x->rfc3779_asid == NULL && i != -1)
590         x->ex_flags |= EXFLAG_INVALID;
591 #endif
592     for (i = 0; i < X509_get_ext_count(x); i++) {
593         X509_EXTENSION *ex = X509_get_ext(x, i);
594         int nid = OBJ_obj2nid(X509_EXTENSION_get_object(ex));
595
596         if (nid == NID_freshest_crl)
597             x->ex_flags |= EXFLAG_FRESHEST;
598         if (!X509_EXTENSION_get_critical(ex))
599             continue;
600         if (!X509_supported_extension(ex)) {
601             x->ex_flags |= EXFLAG_CRITICAL;
602             break;
603         }
604         switch (nid) {
605         case NID_basic_constraints:
606             x->ex_flags |= EXFLAG_BCONS_CRITICAL;
607             break;
608         case NID_authority_key_identifier:
609             x->ex_flags |= EXFLAG_AKID_CRITICAL;
610             break;
611         case NID_subject_key_identifier:
612             x->ex_flags |= EXFLAG_SKID_CRITICAL;
613             break;
614         case NID_subject_alt_name:
615             x->ex_flags |= EXFLAG_SAN_CRITICAL;
616             break;
617         default:
618             break;
619         }
620     }
621
622     /* Set x->siginf, ignoring errors due to unsupported algos */
623     (void)ossl_x509_init_sig_info(x);
624
625     x->ex_flags |= EXFLAG_SET; /* Indicate that cert has been processed */
626 #ifdef tsan_st_rel
627     tsan_st_rel((TSAN_QUALIFIER int *)&x->ex_cached, 1);
628     /*
629      * Above store triggers fast lock-free check in the beginning of the
630      * function. But one has to ensure that the structure is "stable", i.e.
631      * all stores are visible on all processors. Hence the release fence.
632      */
633 #endif
634     ERR_pop_to_mark();
635
636     if ((x->ex_flags & EXFLAG_INVALID) == 0) {
637         CRYPTO_THREAD_unlock(x->lock);
638         return 1;
639     }
640     CRYPTO_THREAD_unlock(x->lock);
641     ERR_raise(ERR_LIB_X509, X509V3_R_INVALID_CERTIFICATE);
642     return 0;
643 }
644
645 /*-
646  * CA checks common to all purposes
647  * return codes:
648  * 0 not a CA
649  * 1 is a CA
650  * 2 Only possible in older versions of openSSL when basicConstraints are absent
651  *   new versions will not return this value. May be a CA
652  * 3 basicConstraints absent but self-signed V1.
653  * 4 basicConstraints absent but keyUsage present and keyCertSign asserted.
654  * 5 Netscape specific CA Flags present
655  */
656
657 static int check_ca(const X509 *x)
658 {
659     /* keyUsage if present should allow cert signing */
660     if (ku_reject(x, KU_KEY_CERT_SIGN))
661         return 0;
662     if ((x->ex_flags & EXFLAG_BCONS) != 0) {
663         /* If basicConstraints says not a CA then say so */
664         return (x->ex_flags & EXFLAG_CA) != 0;
665     } else {
666         /* We support V1 roots for...  uh, I don't really know why. */
667         if ((x->ex_flags & V1_ROOT) == V1_ROOT)
668             return 3;
669         /*
670          * If key usage present it must have certSign so tolerate it
671          */
672         else if ((x->ex_flags & EXFLAG_KUSAGE) != 0)
673             return 4;
674         /* Older certificates could have Netscape-specific CA types */
675         else if ((x->ex_flags & EXFLAG_NSCERT) != 0
676                  && (x->ex_nscert & NS_ANY_CA) != 0)
677             return 5;
678         /* Can this still be regarded a CA certificate?  I doubt it. */
679         return 0;
680     }
681 }
682
683 void X509_set_proxy_flag(X509 *x)
684 {
685     if (CRYPTO_THREAD_write_lock(x->lock)) {
686         x->ex_flags |= EXFLAG_PROXY;
687         CRYPTO_THREAD_unlock(x->lock);
688     }
689 }
690
691 void X509_set_proxy_pathlen(X509 *x, long l)
692 {
693     x->ex_pcpathlen = l;
694 }
695
696 int X509_check_ca(X509 *x)
697 {
698     /* Note 0 normally means "not a CA" - but in this case means error. */
699     if (!ossl_x509v3_cache_extensions(x))
700         return 0;
701
702     return check_ca(x);
703 }
704
705 /* Check SSL CA: common checks for SSL client and server. */
706 static int check_ssl_ca(const X509 *x)
707 {
708     int ca_ret = check_ca(x);
709
710     if (ca_ret == 0)
711         return 0;
712     /* Check nsCertType if present */
713     return ca_ret != 5 || (x->ex_nscert & NS_SSL_CA) != 0;
714 }
715
716 static int check_purpose_ssl_client(const X509_PURPOSE *xp, const X509 *x,
717                                     int require_ca)
718 {
719     if (xku_reject(x, XKU_SSL_CLIENT))
720         return 0;
721     if (require_ca)
722         return check_ssl_ca(x);
723     /* We need to do digital signatures or key agreement */
724     if (ku_reject(x, KU_DIGITAL_SIGNATURE | KU_KEY_AGREEMENT))
725         return 0;
726     /* nsCertType if present should allow SSL client use */
727     if (ns_reject(x, NS_SSL_CLIENT))
728         return 0;
729     return 1;
730 }
731
732 /*
733  * Key usage needed for TLS/SSL server: digital signature, encipherment or
734  * key agreement. The ssl code can check this more thoroughly for individual
735  * key types.
736  */
737 #define KU_TLS \
738     KU_DIGITAL_SIGNATURE | KU_KEY_ENCIPHERMENT | KU_KEY_AGREEMENT
739
740 static int check_purpose_ssl_server(const X509_PURPOSE *xp, const X509 *x,
741                                     int require_ca)
742 {
743     if (xku_reject(x, XKU_SSL_SERVER | XKU_SGC))
744         return 0;
745     if (require_ca)
746         return check_ssl_ca(x);
747
748     if (ns_reject(x, NS_SSL_SERVER))
749         return 0;
750     if (ku_reject(x, KU_TLS))
751         return 0;
752
753     return 1;
754
755 }
756
757 static int check_purpose_ns_ssl_server(const X509_PURPOSE *xp, const X509 *x,
758                                        int require_ca)
759 {
760     int ret = check_purpose_ssl_server(xp, x, require_ca);
761
762     if (!ret || require_ca)
763         return ret;
764     /* We need to encipher or Netscape complains */
765     return ku_reject(x, KU_KEY_ENCIPHERMENT) ? 0 : ret;
766 }
767
768 /* common S/MIME checks */
769 static int purpose_smime(const X509 *x, int require_ca)
770 {
771     if (xku_reject(x, XKU_SMIME))
772         return 0;
773     if (require_ca) {
774         int ca_ret = check_ca(x);
775
776         if (ca_ret == 0)
777             return 0;
778         /* Check nsCertType if present */
779         if (ca_ret != 5 || (x->ex_nscert & NS_SMIME_CA) != 0)
780             return ca_ret;
781         else
782             return 0;
783     }
784     if ((x->ex_flags & EXFLAG_NSCERT) != 0) {
785         if ((x->ex_nscert & NS_SMIME) != 0)
786             return 1;
787         /* Workaround for some buggy certificates */
788         return (x->ex_nscert & NS_SSL_CLIENT) != 0 ? 2 : 0;
789     }
790     return 1;
791 }
792
793 static int check_purpose_smime_sign(const X509_PURPOSE *xp, const X509 *x,
794                                     int require_ca)
795 {
796     int ret = purpose_smime(x, require_ca);
797
798     if (!ret || require_ca)
799         return ret;
800     return ku_reject(x, KU_DIGITAL_SIGNATURE | KU_NON_REPUDIATION) ? 0 : ret;
801 }
802
803 static int check_purpose_smime_encrypt(const X509_PURPOSE *xp, const X509 *x,
804                                        int require_ca)
805 {
806     int ret = purpose_smime(x, require_ca);
807
808     if (!ret || require_ca)
809         return ret;
810     return ku_reject(x, KU_KEY_ENCIPHERMENT) ? 0 : ret;
811 }
812
813 static int check_purpose_crl_sign(const X509_PURPOSE *xp, const X509 *x,
814                                   int require_ca)
815 {
816     if (require_ca) {
817         int ca_ret = check_ca(x);
818
819         return ca_ret == 2 ? 0 : ca_ret;
820     }
821     return !ku_reject(x, KU_CRL_SIGN);
822 }
823
824 /*
825  * OCSP helper: this is *not* a full OCSP check. It just checks that each CA
826  * is valid. Additional checks must be made on the chain.
827  */
828 static int check_purpose_ocsp_helper(const X509_PURPOSE *xp, const X509 *x,
829                                      int require_ca)
830 {
831     /*
832      * Must be a valid CA.  Should we really support the "I don't know" value
833      * (2)?
834      */
835     if (require_ca)
836         return check_ca(x);
837     /* Leaf certificate is checked in OCSP_verify() */
838     return 1;
839 }
840
841 static int check_purpose_timestamp_sign(const X509_PURPOSE *xp, const X509 *x,
842                                         int require_ca)
843 {
844     int i_ext;
845
846     /* If ca is true we must return if this is a valid CA certificate. */
847     if (require_ca)
848         return check_ca(x);
849
850     /*
851      * Check the optional key usage field:
852      * if Key Usage is present, it must be one of digitalSignature
853      * and/or nonRepudiation (other values are not consistent and shall
854      * be rejected).
855      */
856     if ((x->ex_flags & EXFLAG_KUSAGE) != 0
857         && ((x->ex_kusage & ~(KU_NON_REPUDIATION | KU_DIGITAL_SIGNATURE)) ||
858             !(x->ex_kusage & (KU_NON_REPUDIATION | KU_DIGITAL_SIGNATURE))))
859         return 0;
860
861     /* Only time stamp key usage is permitted and it's required. */
862     if ((x->ex_flags & EXFLAG_XKUSAGE) == 0 || x->ex_xkusage != XKU_TIMESTAMP)
863         return 0;
864
865     /* Extended Key Usage MUST be critical */
866     i_ext = X509_get_ext_by_NID(x, NID_ext_key_usage, -1);
867     if (i_ext >= 0
868             && !X509_EXTENSION_get_critical(X509_get_ext((X509 *)x, i_ext)))
869         return 0;
870     return 1;
871 }
872
873 static int check_purpose_code_sign(const X509_PURPOSE *xp, const X509 *x,
874                                    int require_ca)
875 {
876     int i_ext;
877
878     /* If ca is true we must return if this is a valid CA certificate. */
879     if (require_ca)
880         return check_ca(x);
881
882     /*
883      * Check the key usage and extended key usage fields:
884      *
885      * Reference: CA Browser Forum,
886      * Baseline Requirements for the Issuance and Management of 
887      * Publicly‐Trusted Code Signing Certificates, Version 3.0.0,
888      * Section 7.1.2.3: Code signing and Timestamp Certificate
889      *
890      * Checking covers Key Usage and Extended Key Usage attributes.
891      * Other properties like CRL Distribution Points and Authoriy
892      * Information Access (AIA) are not checked.
893      */
894     /* Key Usage */
895     if ((x->ex_flags & EXFLAG_KUSAGE) == 0)
896         return 0;
897     if ((x->ex_kusage & KU_DIGITAL_SIGNATURE) == 0)
898         return 0;
899     if ((x->ex_kusage & (KU_KEY_CERT_SIGN | KU_CRL_SIGN)) != 0)
900         return 0;
901
902     /* Key Usage MUST be critical */
903     i_ext = X509_get_ext_by_NID(x, NID_key_usage, -1);
904     if (i_ext < 0)
905         return 0;
906     if (i_ext >= 0) {
907         X509_EXTENSION *ext = X509_get_ext((X509 *)x, i_ext);
908         if (!X509_EXTENSION_get_critical(ext))
909             return 0;
910     }
911
912     /* Extended Key Usage */
913     if ((x->ex_flags & EXFLAG_XKUSAGE) == 0)
914         return 0;
915     if ((x->ex_xkusage & XKU_CODE_SIGN) == 0)
916         return 0;
917     if ((x->ex_xkusage & (XKU_ANYEKU | XKU_SSL_SERVER)) != 0)
918         return 0;
919
920     return 1;
921
922 }
923
924 static int no_check_purpose(const X509_PURPOSE *xp, const X509 *x,
925                             int require_ca)
926 {
927     return 1;
928 }
929
930 /*-
931  * Various checks to see if one certificate potentially issued the second.
932  * This can be used to prune a set of possible issuer certificates which
933  * have been looked up using some simple method such as by subject name.
934  * These are:
935  * 1. issuer_name(subject) == subject_name(issuer)
936  * 2. If akid(subject) exists, it matches the respective issuer fields.
937  * 3. subject signature algorithm == issuer public key algorithm
938  * 4. If key_usage(issuer) exists, it allows for signing subject.
939  * Note that this does not include actually checking the signature.
940  * Returns 0 for OK, or positive for reason for mismatch
941  * where reason codes match those for X509_verify_cert().
942  */
943 int X509_check_issued(X509 *issuer, X509 *subject)
944 {
945     int ret;
946
947     if ((ret = ossl_x509_likely_issued(issuer, subject)) != X509_V_OK)
948         return ret;
949     return ossl_x509_signing_allowed(issuer, subject);
950 }
951
952 /* do the checks 1., 2., and 3. as described above for X509_check_issued() */
953 int ossl_x509_likely_issued(X509 *issuer, X509 *subject)
954 {
955     int ret;
956
957     if (X509_NAME_cmp(X509_get_subject_name(issuer),
958                       X509_get_issuer_name(subject)) != 0)
959         return X509_V_ERR_SUBJECT_ISSUER_MISMATCH;
960
961     /* set issuer->skid and subject->akid */
962     if (!ossl_x509v3_cache_extensions(issuer)
963             || !ossl_x509v3_cache_extensions(subject))
964         return X509_V_ERR_UNSPECIFIED;
965
966     ret = X509_check_akid(issuer, subject->akid);
967     if (ret != X509_V_OK)
968         return ret;
969
970     /* Check if the subject signature alg matches the issuer's PUBKEY alg */
971     return check_sig_alg_match(X509_get0_pubkey(issuer), subject);
972 }
973
974 /*-
975  * Check if certificate I<issuer> is allowed to issue certificate I<subject>
976  * according to the B<keyUsage> field of I<issuer> if present
977  * depending on any proxyCertInfo extension of I<subject>.
978  * Returns 0 for OK, or positive for reason for rejection
979  * where reason codes match those for X509_verify_cert().
980  */
981 int ossl_x509_signing_allowed(const X509 *issuer, const X509 *subject)
982 {
983     if ((subject->ex_flags & EXFLAG_PROXY) != 0) {
984         if (ku_reject(issuer, KU_DIGITAL_SIGNATURE))
985             return X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE;
986     } else if (ku_reject(issuer, KU_KEY_CERT_SIGN)) {
987         return X509_V_ERR_KEYUSAGE_NO_CERTSIGN;
988     }
989     return X509_V_OK;
990 }
991
992 int X509_check_akid(const X509 *issuer, const AUTHORITY_KEYID *akid)
993 {
994     if (akid == NULL)
995         return X509_V_OK;
996
997     /* Check key ids (if present) */
998     if (akid->keyid && issuer->skid &&
999         ASN1_OCTET_STRING_cmp(akid->keyid, issuer->skid))
1000         return X509_V_ERR_AKID_SKID_MISMATCH;
1001     /* Check serial number */
1002     if (akid->serial &&
1003         ASN1_INTEGER_cmp(X509_get0_serialNumber(issuer), akid->serial))
1004         return X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH;
1005     /* Check issuer name */
1006     if (akid->issuer) {
1007         /*
1008          * Ugh, for some peculiar reason AKID includes SEQUENCE OF
1009          * GeneralName. So look for a DirName. There may be more than one but
1010          * we only take any notice of the first.
1011          */
1012         GENERAL_NAMES *gens = akid->issuer;
1013         GENERAL_NAME *gen;
1014         X509_NAME *nm = NULL;
1015         int i;
1016
1017         for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
1018             gen = sk_GENERAL_NAME_value(gens, i);
1019             if (gen->type == GEN_DIRNAME) {
1020                 nm = gen->d.dirn;
1021                 break;
1022             }
1023         }
1024         if (nm != NULL && X509_NAME_cmp(nm, X509_get_issuer_name(issuer)) != 0)
1025             return X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH;
1026     }
1027     return X509_V_OK;
1028 }
1029
1030 uint32_t X509_get_extension_flags(X509 *x)
1031 {
1032     /* Call for side-effect of computing hash and caching extensions */
1033     X509_check_purpose(x, -1, 0);
1034     return x->ex_flags;
1035 }
1036
1037 uint32_t X509_get_key_usage(X509 *x)
1038 {
1039     /* Call for side-effect of computing hash and caching extensions */
1040     if (X509_check_purpose(x, -1, 0) != 1)
1041         return 0;
1042     return (x->ex_flags & EXFLAG_KUSAGE) != 0 ? x->ex_kusage : UINT32_MAX;
1043 }
1044
1045 uint32_t X509_get_extended_key_usage(X509 *x)
1046 {
1047     /* Call for side-effect of computing hash and caching extensions */
1048     if (X509_check_purpose(x, -1, 0) != 1)
1049         return 0;
1050     return (x->ex_flags & EXFLAG_XKUSAGE) != 0 ? x->ex_xkusage : UINT32_MAX;
1051 }
1052
1053 const ASN1_OCTET_STRING *X509_get0_subject_key_id(X509 *x)
1054 {
1055     /* Call for side-effect of computing hash and caching extensions */
1056     if (X509_check_purpose(x, -1, 0) != 1)
1057         return NULL;
1058     return x->skid;
1059 }
1060
1061 const ASN1_OCTET_STRING *X509_get0_authority_key_id(X509 *x)
1062 {
1063     /* Call for side-effect of computing hash and caching extensions */
1064     if (X509_check_purpose(x, -1, 0) != 1)
1065         return NULL;
1066     return (x->akid != NULL ? x->akid->keyid : NULL);
1067 }
1068
1069 const GENERAL_NAMES *X509_get0_authority_issuer(X509 *x)
1070 {
1071     /* Call for side-effect of computing hash and caching extensions */
1072     if (X509_check_purpose(x, -1, 0) != 1)
1073         return NULL;
1074     return (x->akid != NULL ? x->akid->issuer : NULL);
1075 }
1076
1077 const ASN1_INTEGER *X509_get0_authority_serial(X509 *x)
1078 {
1079     /* Call for side-effect of computing hash and caching extensions */
1080     if (X509_check_purpose(x, -1, 0) != 1)
1081         return NULL;
1082     return (x->akid != NULL ? x->akid->serial : NULL);
1083 }
1084
1085 long X509_get_pathlen(X509 *x)
1086 {
1087     /* Called for side effect of caching extensions */
1088     if (X509_check_purpose(x, -1, 0) != 1
1089             || (x->ex_flags & EXFLAG_BCONS) == 0)
1090         return -1;
1091     return x->ex_pathlen;
1092 }
1093
1094 long X509_get_proxy_pathlen(X509 *x)
1095 {
1096     /* Called for side effect of caching extensions */
1097     if (X509_check_purpose(x, -1, 0) != 1
1098             || (x->ex_flags & EXFLAG_PROXY) == 0)
1099         return -1;
1100     return x->ex_pcpathlen;
1101 }