In OpenSSL builds, declare STACK for datatypes ...
[openssl.git] / crypto / x509 / v3_purp.c
1 /*
2  * Copyright 1999-2020 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
18 DEFINE_STACK_OF(GENERAL_NAME)
19 DEFINE_STACK_OF(DIST_POINT)
20 DEFINE_STACK_OF(X509_PURPOSE)
21 DEFINE_STACK_OF(ASN1_OBJECT)
22
23 static int check_ssl_ca(const X509 *x);
24 static int check_purpose_ssl_client(const X509_PURPOSE *xp, const X509 *x,
25                                     int ca);
26 static int check_purpose_ssl_server(const X509_PURPOSE *xp, const X509 *x,
27                                     int ca);
28 static int check_purpose_ns_ssl_server(const X509_PURPOSE *xp, const X509 *x,
29                                        int ca);
30 static int purpose_smime(const X509 *x, int ca);
31 static int check_purpose_smime_sign(const X509_PURPOSE *xp, const X509 *x,
32                                     int ca);
33 static int check_purpose_smime_encrypt(const X509_PURPOSE *xp, const X509 *x,
34                                        int ca);
35 static int check_purpose_crl_sign(const X509_PURPOSE *xp, const X509 *x,
36                                   int ca);
37 static int check_purpose_timestamp_sign(const X509_PURPOSE *xp, const X509 *x,
38                                         int ca);
39 static int no_check(const X509_PURPOSE *xp, const X509 *x, int ca);
40 static int ocsp_helper(const X509_PURPOSE *xp, const X509 *x, int 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, "Any Purpose", "any",
59      NULL},
60     {X509_PURPOSE_OCSP_HELPER, X509_TRUST_COMPAT, 0, ocsp_helper,
61      "OCSP helper", "ocsphelper", NULL},
62     {X509_PURPOSE_TIMESTAMP_SIGN, X509_TRUST_TSA, 0,
63      check_purpose_timestamp_sign, "Time Stamp signing", "timestampsign",
64      NULL},
65 };
66
67 #define X509_PURPOSE_COUNT OSSL_NELEM(xstandard)
68
69 static STACK_OF(X509_PURPOSE) *xptable = NULL;
70
71 static int xp_cmp(const X509_PURPOSE *const *a, const X509_PURPOSE *const *b)
72 {
73     return (*a)->purpose - (*b)->purpose;
74 }
75
76 /*
77  * As much as I'd like to make X509_check_purpose use a "const" X509* I
78  * really can't because it does recalculate hashes and do other non-const
79  * things.
80  */
81 int X509_check_purpose(X509 *x, int id, int ca)
82 {
83     int idx;
84     const X509_PURPOSE *pt;
85
86     if (!X509v3_cache_extensions(x, NULL, NULL))
87         return -1;
88
89     /* Return if side-effect only call */
90     if (id == -1)
91         return 1;
92     idx = X509_PURPOSE_get_by_id(id);
93     if (idx == -1)
94         return -1;
95     pt = X509_PURPOSE_get0(idx);
96     return pt->check_purpose(pt, x, ca);
97 }
98
99 int X509_PURPOSE_set(int *p, int purpose)
100 {
101     if (X509_PURPOSE_get_by_id(purpose) == -1) {
102         X509V3err(X509V3_F_X509_PURPOSE_SET, X509V3_R_INVALID_PURPOSE);
103         return 0;
104     }
105     *p = purpose;
106     return 1;
107 }
108
109 int X509_PURPOSE_get_count(void)
110 {
111     if (!xptable)
112         return X509_PURPOSE_COUNT;
113     return sk_X509_PURPOSE_num(xptable) + X509_PURPOSE_COUNT;
114 }
115
116 X509_PURPOSE *X509_PURPOSE_get0(int idx)
117 {
118     if (idx < 0)
119         return NULL;
120     if (idx < (int)X509_PURPOSE_COUNT)
121         return xstandard + idx;
122     return sk_X509_PURPOSE_value(xptable, idx - X509_PURPOSE_COUNT);
123 }
124
125 int X509_PURPOSE_get_by_sname(const char *sname)
126 {
127     int i;
128     X509_PURPOSE *xptmp;
129     for (i = 0; i < X509_PURPOSE_get_count(); i++) {
130         xptmp = X509_PURPOSE_get0(i);
131         if (strcmp(xptmp->sname, sname) == 0)
132             return i;
133     }
134     return -1;
135 }
136
137 int X509_PURPOSE_get_by_id(int purpose)
138 {
139     X509_PURPOSE tmp;
140     int idx;
141
142     if ((purpose >= X509_PURPOSE_MIN) && (purpose <= X509_PURPOSE_MAX))
143         return purpose - X509_PURPOSE_MIN;
144     if (xptable == NULL)
145         return -1;
146     tmp.purpose = purpose;
147     idx = sk_X509_PURPOSE_find(xptable, &tmp);
148     if (idx < 0)
149         return -1;
150     return idx + X509_PURPOSE_COUNT;
151 }
152
153 int X509_PURPOSE_add(int id, int trust, int flags,
154                      int (*ck) (const X509_PURPOSE *, const X509 *, int),
155                      const char *name, const char *sname, void *arg)
156 {
157     int idx;
158     X509_PURPOSE *ptmp;
159     /*
160      * This is set according to what we change: application can't set it
161      */
162     flags &= ~X509_PURPOSE_DYNAMIC;
163     /* This will always be set for application modified trust entries */
164     flags |= X509_PURPOSE_DYNAMIC_NAME;
165     /* Get existing entry if any */
166     idx = X509_PURPOSE_get_by_id(id);
167     /* Need a new entry */
168     if (idx == -1) {
169         if ((ptmp = OPENSSL_malloc(sizeof(*ptmp))) == NULL) {
170             X509V3err(X509V3_F_X509_PURPOSE_ADD, ERR_R_MALLOC_FAILURE);
171             return 0;
172         }
173         ptmp->flags = X509_PURPOSE_DYNAMIC;
174     } else
175         ptmp = X509_PURPOSE_get0(idx);
176
177     /* OPENSSL_free existing name if dynamic */
178     if (ptmp->flags & X509_PURPOSE_DYNAMIC_NAME) {
179         OPENSSL_free(ptmp->name);
180         OPENSSL_free(ptmp->sname);
181     }
182     /* dup supplied name */
183     ptmp->name = OPENSSL_strdup(name);
184     ptmp->sname = OPENSSL_strdup(sname);
185     if (ptmp->name == NULL|| ptmp->sname == NULL) {
186         X509V3err(X509V3_F_X509_PURPOSE_ADD, ERR_R_MALLOC_FAILURE);
187         goto err;
188     }
189     /* Keep the dynamic flag of existing entry */
190     ptmp->flags &= X509_PURPOSE_DYNAMIC;
191     /* Set all other flags */
192     ptmp->flags |= flags;
193
194     ptmp->purpose = id;
195     ptmp->trust = trust;
196     ptmp->check_purpose = ck;
197     ptmp->usr_data = arg;
198
199     /* If its a new entry manage the dynamic table */
200     if (idx == -1) {
201         if (xptable == NULL
202             && (xptable = sk_X509_PURPOSE_new(xp_cmp)) == NULL) {
203             X509V3err(X509V3_F_X509_PURPOSE_ADD, ERR_R_MALLOC_FAILURE);
204             goto err;
205         }
206         if (!sk_X509_PURPOSE_push(xptable, ptmp)) {
207             X509V3err(X509V3_F_X509_PURPOSE_ADD, ERR_R_MALLOC_FAILURE);
208             goto err;
209         }
210     }
211     return 1;
212  err:
213     if (idx == -1) {
214         OPENSSL_free(ptmp->name);
215         OPENSSL_free(ptmp->sname);
216         OPENSSL_free(ptmp);
217     }
218     return 0;
219 }
220
221 static void xptable_free(X509_PURPOSE *p)
222 {
223     if (p == NULL)
224         return;
225     if (p->flags & X509_PURPOSE_DYNAMIC) {
226         if (p->flags & X509_PURPOSE_DYNAMIC_NAME) {
227             OPENSSL_free(p->name);
228             OPENSSL_free(p->sname);
229         }
230         OPENSSL_free(p);
231     }
232 }
233
234 void X509_PURPOSE_cleanup(void)
235 {
236     sk_X509_PURPOSE_pop_free(xptable, xptable_free);
237     xptable = NULL;
238 }
239
240 int X509_PURPOSE_get_id(const X509_PURPOSE *xp)
241 {
242     return xp->purpose;
243 }
244
245 char *X509_PURPOSE_get0_name(const X509_PURPOSE *xp)
246 {
247     return xp->name;
248 }
249
250 char *X509_PURPOSE_get0_sname(const X509_PURPOSE *xp)
251 {
252     return xp->sname;
253 }
254
255 int X509_PURPOSE_get_trust(const X509_PURPOSE *xp)
256 {
257     return xp->trust;
258 }
259
260 static int nid_cmp(const int *a, const int *b)
261 {
262     return *a - *b;
263 }
264
265 DECLARE_OBJ_BSEARCH_CMP_FN(int, int, nid);
266 IMPLEMENT_OBJ_BSEARCH_CMP_FN(int, int, nid);
267
268 int X509_supported_extension(X509_EXTENSION *ex)
269 {
270     /*
271      * This table is a list of the NIDs of supported extensions: that is
272      * those which are used by the verify process. If an extension is
273      * critical and doesn't appear in this list then the verify process will
274      * normally reject the certificate. The list must be kept in numerical
275      * order because it will be searched using bsearch.
276      */
277
278     static const int supported_nids[] = {
279         NID_netscape_cert_type, /* 71 */
280         NID_key_usage,          /* 83 */
281         NID_subject_alt_name,   /* 85 */
282         NID_basic_constraints,  /* 87 */
283         NID_certificate_policies, /* 89 */
284         NID_crl_distribution_points, /* 103 */
285         NID_ext_key_usage,      /* 126 */
286 #ifndef OPENSSL_NO_RFC3779
287         NID_sbgp_ipAddrBlock,   /* 290 */
288         NID_sbgp_autonomousSysNum, /* 291 */
289 #endif
290         NID_policy_constraints, /* 401 */
291         NID_proxyCertInfo,      /* 663 */
292         NID_name_constraints,   /* 666 */
293         NID_policy_mappings,    /* 747 */
294         NID_inhibit_any_policy  /* 748 */
295     };
296
297     int ex_nid = OBJ_obj2nid(X509_EXTENSION_get_object(ex));
298
299     if (ex_nid == NID_undef)
300         return 0;
301
302     if (OBJ_bsearch_nid(&ex_nid, supported_nids, OSSL_NELEM(supported_nids)))
303         return 1;
304     return 0;
305 }
306
307 static int setup_dp(X509 *x, DIST_POINT *dp)
308 {
309     const X509_NAME *iname = NULL;
310     int i;
311
312     if (dp->reasons) {
313         if (dp->reasons->length > 0)
314             dp->dp_reasons = dp->reasons->data[0];
315         if (dp->reasons->length > 1)
316             dp->dp_reasons |= (dp->reasons->data[1] << 8);
317         dp->dp_reasons &= CRLDP_ALL_REASONS;
318     } else
319         dp->dp_reasons = CRLDP_ALL_REASONS;
320     if (!dp->distpoint || (dp->distpoint->type != 1))
321         return 1;
322     for (i = 0; i < sk_GENERAL_NAME_num(dp->CRLissuer); i++) {
323         GENERAL_NAME *gen = sk_GENERAL_NAME_value(dp->CRLissuer, i);
324         if (gen->type == GEN_DIRNAME) {
325             iname = gen->d.directoryName;
326             break;
327         }
328     }
329     if (!iname)
330         iname = X509_get_issuer_name(x);
331
332     return DIST_POINT_set_dpname(dp->distpoint, iname);
333 }
334
335 static int setup_crldp(X509 *x)
336 {
337     int i;
338
339     x->crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, &i, NULL);
340     if (x->crldp == NULL && i != -1)
341         return 0;
342     for (i = 0; i < sk_DIST_POINT_num(x->crldp); i++) {
343         if (!setup_dp(x, sk_DIST_POINT_value(x->crldp, i)))
344             return 0;
345     }
346     return 1;
347 }
348
349 #define V1_ROOT (EXFLAG_V1|EXFLAG_SS)
350 #define ku_reject(x, usage) \
351         (((x)->ex_flags & EXFLAG_KUSAGE) && !((x)->ex_kusage & (usage)))
352 #define xku_reject(x, usage) \
353         (((x)->ex_flags & EXFLAG_XKUSAGE) && !((x)->ex_xkusage & (usage)))
354 #define ns_reject(x, usage) \
355         (((x)->ex_flags & EXFLAG_NSCERT) && !((x)->ex_nscert & (usage)))
356
357 int X509v3_cache_extensions(X509 *x, OPENSSL_CTX *libctx, const char *propq)
358 {
359     BASIC_CONSTRAINTS *bs;
360     PROXY_CERT_INFO_EXTENSION *pci;
361     ASN1_BIT_STRING *usage;
362     ASN1_BIT_STRING *ns;
363     EXTENDED_KEY_USAGE *extusage;
364     X509_EXTENSION *ex;
365     int i;
366     EVP_MD *sha1;
367
368 #ifdef tsan_ld_acq
369     /* fast lock-free check, see end of the function for details. */
370     if (tsan_ld_acq((TSAN_QUALIFIER int *)&x->ex_cached))
371         return (x->ex_flags & EXFLAG_INVALID) == 0;
372 #endif
373
374     CRYPTO_THREAD_write_lock(x->lock);
375     if (x->ex_flags & EXFLAG_SET) {
376         CRYPTO_THREAD_unlock(x->lock);
377         return (x->ex_flags & EXFLAG_INVALID) == 0;
378     }
379
380     sha1 = EVP_MD_fetch(libctx, "SHA1", propq);
381     if (sha1 == NULL || !X509_digest(x, sha1, x->sha1_hash, NULL))
382             x->ex_flags |= EXFLAG_INVALID;
383     EVP_MD_free(sha1);
384
385     /* V1 should mean no extensions ... */
386     if (!X509_get_version(x))
387         x->ex_flags |= EXFLAG_V1;
388     /* Handle basic constraints */
389     if ((bs = X509_get_ext_d2i(x, NID_basic_constraints, &i, NULL))) {
390         if (bs->ca)
391             x->ex_flags |= EXFLAG_CA;
392         if (bs->pathlen) {
393             if (bs->pathlen->type == V_ASN1_NEG_INTEGER) {
394                 x->ex_flags |= EXFLAG_INVALID;
395                 x->ex_pathlen = 0;
396             } else {
397                 x->ex_pathlen = ASN1_INTEGER_get(bs->pathlen);
398                 if (!bs->ca && x->ex_pathlen != 0) {
399                     x->ex_flags |= EXFLAG_INVALID;
400                     x->ex_pathlen = 0;
401                 }
402             }
403         } else
404             x->ex_pathlen = -1;
405         BASIC_CONSTRAINTS_free(bs);
406         x->ex_flags |= EXFLAG_BCONS;
407     } else if (i != -1) {
408         x->ex_flags |= EXFLAG_INVALID;
409     }
410     /* Handle proxy certificates */
411     if ((pci = X509_get_ext_d2i(x, NID_proxyCertInfo, &i, NULL))) {
412         if (x->ex_flags & EXFLAG_CA
413             || X509_get_ext_by_NID(x, NID_subject_alt_name, -1) >= 0
414             || X509_get_ext_by_NID(x, NID_issuer_alt_name, -1) >= 0) {
415             x->ex_flags |= EXFLAG_INVALID;
416         }
417         if (pci->pcPathLengthConstraint) {
418             x->ex_pcpathlen = ASN1_INTEGER_get(pci->pcPathLengthConstraint);
419         } else
420             x->ex_pcpathlen = -1;
421         PROXY_CERT_INFO_EXTENSION_free(pci);
422         x->ex_flags |= EXFLAG_PROXY;
423     } else if (i != -1) {
424         x->ex_flags |= EXFLAG_INVALID;
425     }
426     /* Handle key usage */
427     if ((usage = X509_get_ext_d2i(x, NID_key_usage, &i, NULL))) {
428         if (usage->length > 0) {
429             x->ex_kusage = usage->data[0];
430             if (usage->length > 1)
431                 x->ex_kusage |= usage->data[1] << 8;
432         } else
433             x->ex_kusage = 0;
434         x->ex_flags |= EXFLAG_KUSAGE;
435         ASN1_BIT_STRING_free(usage);
436     } else if (i != -1) {
437         x->ex_flags |= EXFLAG_INVALID;
438     }
439     x->ex_xkusage = 0;
440     if ((extusage = X509_get_ext_d2i(x, NID_ext_key_usage, &i, NULL))) {
441         x->ex_flags |= EXFLAG_XKUSAGE;
442         for (i = 0; i < sk_ASN1_OBJECT_num(extusage); i++) {
443             switch (OBJ_obj2nid(sk_ASN1_OBJECT_value(extusage, i))) {
444             case NID_server_auth:
445                 x->ex_xkusage |= XKU_SSL_SERVER;
446                 break;
447
448             case NID_client_auth:
449                 x->ex_xkusage |= XKU_SSL_CLIENT;
450                 break;
451
452             case NID_email_protect:
453                 x->ex_xkusage |= XKU_SMIME;
454                 break;
455
456             case NID_code_sign:
457                 x->ex_xkusage |= XKU_CODE_SIGN;
458                 break;
459
460             case NID_ms_sgc:
461             case NID_ns_sgc:
462                 x->ex_xkusage |= XKU_SGC;
463                 break;
464
465             case NID_OCSP_sign:
466                 x->ex_xkusage |= XKU_OCSP_SIGN;
467                 break;
468
469             case NID_time_stamp:
470                 x->ex_xkusage |= XKU_TIMESTAMP;
471                 break;
472
473             case NID_dvcs:
474                 x->ex_xkusage |= XKU_DVCS;
475                 break;
476
477             case NID_anyExtendedKeyUsage:
478                 x->ex_xkusage |= XKU_ANYEKU;
479                 break;
480             }
481         }
482         sk_ASN1_OBJECT_pop_free(extusage, ASN1_OBJECT_free);
483     } else if (i != -1) {
484         x->ex_flags |= EXFLAG_INVALID;
485     }
486
487     if ((ns = X509_get_ext_d2i(x, NID_netscape_cert_type, &i, NULL))) {
488         if (ns->length > 0)
489             x->ex_nscert = ns->data[0];
490         else
491             x->ex_nscert = 0;
492         x->ex_flags |= EXFLAG_NSCERT;
493         ASN1_BIT_STRING_free(ns);
494     } else if (i != -1) {
495         x->ex_flags |= EXFLAG_INVALID;
496     }
497     x->skid = X509_get_ext_d2i(x, NID_subject_key_identifier, &i, NULL);
498     if (x->skid == NULL && i != -1)
499         x->ex_flags |= EXFLAG_INVALID;
500     x->akid = X509_get_ext_d2i(x, NID_authority_key_identifier, &i, NULL);
501     if (x->akid == NULL && i != -1)
502         x->ex_flags |= EXFLAG_INVALID;
503     /* Does subject name match issuer ? */
504     if (!X509_NAME_cmp(X509_get_subject_name(x), X509_get_issuer_name(x))) {
505         x->ex_flags |= EXFLAG_SI;
506         /* If SKID matches AKID also indicate self signed */
507         if (X509_check_akid(x, x->akid) == X509_V_OK &&
508             !ku_reject(x, KU_KEY_CERT_SIGN))
509             x->ex_flags |= EXFLAG_SS;
510     }
511     x->altname = X509_get_ext_d2i(x, NID_subject_alt_name, &i, NULL);
512     if (x->altname == NULL && i != -1)
513         x->ex_flags |= EXFLAG_INVALID;
514     x->nc = X509_get_ext_d2i(x, NID_name_constraints, &i, NULL);
515     if (x->nc == NULL && i != -1)
516         x->ex_flags |= EXFLAG_INVALID;
517     if (!setup_crldp(x))
518         x->ex_flags |= EXFLAG_INVALID;
519
520 #ifndef OPENSSL_NO_RFC3779
521     x->rfc3779_addr = X509_get_ext_d2i(x, NID_sbgp_ipAddrBlock, &i, NULL);
522     if (x->rfc3779_addr == NULL && i != -1)
523         x->ex_flags |= EXFLAG_INVALID;
524     x->rfc3779_asid = X509_get_ext_d2i(x, NID_sbgp_autonomousSysNum, &i, NULL);
525     if (x->rfc3779_asid == NULL && i != -1)
526         x->ex_flags |= EXFLAG_INVALID;
527 #endif
528     for (i = 0; i < X509_get_ext_count(x); i++) {
529         ex = X509_get_ext(x, i);
530         if (OBJ_obj2nid(X509_EXTENSION_get_object(ex))
531             == NID_freshest_crl)
532             x->ex_flags |= EXFLAG_FRESHEST;
533         if (!X509_EXTENSION_get_critical(ex))
534             continue;
535         if (!X509_supported_extension(ex)) {
536             x->ex_flags |= EXFLAG_CRITICAL;
537             break;
538         }
539     }
540     x509_init_sig_info(x);
541     x->ex_flags |= EXFLAG_SET;
542 #ifdef tsan_st_rel
543     tsan_st_rel((TSAN_QUALIFIER int *)&x->ex_cached, 1);
544     /*
545      * Above store triggers fast lock-free check in the beginning of the
546      * function. But one has to ensure that the structure is "stable", i.e.
547      * all stores are visible on all processors. Hence the release fence.
548      */
549 #endif
550     CRYPTO_THREAD_unlock(x->lock);
551
552     return (x->ex_flags & EXFLAG_INVALID) == 0;
553 }
554
555 /*-
556  * CA checks common to all purposes
557  * return codes:
558  * 0 not a CA
559  * 1 is a CA
560  * 2 Only possible in older versions of openSSL when basicConstraints are absent
561  *   new versions will not return this value. May be a CA
562  * 3 basicConstraints absent but self signed V1.
563  * 4 basicConstraints absent but keyUsage present and keyCertSign asserted.
564  * 5 Netscape specific CA Flags present
565  */
566
567 static int check_ca(const X509 *x)
568 {
569     /* keyUsage if present should allow cert signing */
570     if (ku_reject(x, KU_KEY_CERT_SIGN))
571         return 0;
572     if (x->ex_flags & EXFLAG_BCONS) {
573         if (x->ex_flags & EXFLAG_CA)
574             return 1;
575         /* If basicConstraints says not a CA then say so */
576         else
577             return 0;
578     } else {
579         /* we support V1 roots for...  uh, I don't really know why. */
580         if ((x->ex_flags & V1_ROOT) == V1_ROOT)
581             return 3;
582         /*
583          * If key usage present it must have certSign so tolerate it
584          */
585         else if (x->ex_flags & EXFLAG_KUSAGE)
586             return 4;
587         /* Older certificates could have Netscape-specific CA types */
588         else if (x->ex_flags & EXFLAG_NSCERT && x->ex_nscert & NS_ANY_CA)
589             return 5;
590         /* can this still be regarded a CA certificate?  I doubt it */
591         return 0;
592     }
593 }
594
595 void X509_set_proxy_flag(X509 *x)
596 {
597     x->ex_flags |= EXFLAG_PROXY;
598 }
599
600 void X509_set_proxy_pathlen(X509 *x, long l)
601 {
602     x->ex_pcpathlen = l;
603 }
604
605 int X509_check_ca(X509 *x)
606 {
607     /* Note 0 normally means "not a CA" - but in this case means error. */
608     if (!X509v3_cache_extensions(x, NULL, NULL))
609         return 0;
610
611     return check_ca(x);
612 }
613
614 /* Check SSL CA: common checks for SSL client and server */
615 static int check_ssl_ca(const X509 *x)
616 {
617     int ca_ret;
618     ca_ret = check_ca(x);
619     if (!ca_ret)
620         return 0;
621     /* check nsCertType if present */
622     if (ca_ret != 5 || x->ex_nscert & NS_SSL_CA)
623         return ca_ret;
624     else
625         return 0;
626 }
627
628 static int check_purpose_ssl_client(const X509_PURPOSE *xp, const X509 *x,
629                                     int ca)
630 {
631     if (xku_reject(x, XKU_SSL_CLIENT))
632         return 0;
633     if (ca)
634         return check_ssl_ca(x);
635     /* We need to do digital signatures or key agreement */
636     if (ku_reject(x, KU_DIGITAL_SIGNATURE | KU_KEY_AGREEMENT))
637         return 0;
638     /* nsCertType if present should allow SSL client use */
639     if (ns_reject(x, NS_SSL_CLIENT))
640         return 0;
641     return 1;
642 }
643
644 /*
645  * Key usage needed for TLS/SSL server: digital signature, encipherment or
646  * key agreement. The ssl code can check this more thoroughly for individual
647  * key types.
648  */
649 #define KU_TLS \
650         KU_DIGITAL_SIGNATURE|KU_KEY_ENCIPHERMENT|KU_KEY_AGREEMENT
651
652 static int check_purpose_ssl_server(const X509_PURPOSE *xp, const X509 *x,
653                                     int ca)
654 {
655     if (xku_reject(x, XKU_SSL_SERVER | XKU_SGC))
656         return 0;
657     if (ca)
658         return check_ssl_ca(x);
659
660     if (ns_reject(x, NS_SSL_SERVER))
661         return 0;
662     if (ku_reject(x, KU_TLS))
663         return 0;
664
665     return 1;
666
667 }
668
669 static int check_purpose_ns_ssl_server(const X509_PURPOSE *xp, const X509 *x,
670                                        int ca)
671 {
672     int ret;
673     ret = check_purpose_ssl_server(xp, x, ca);
674     if (!ret || ca)
675         return ret;
676     /* We need to encipher or Netscape complains */
677     if (ku_reject(x, KU_KEY_ENCIPHERMENT))
678         return 0;
679     return ret;
680 }
681
682 /* common S/MIME checks */
683 static int purpose_smime(const X509 *x, int ca)
684 {
685     if (xku_reject(x, XKU_SMIME))
686         return 0;
687     if (ca) {
688         int ca_ret;
689         ca_ret = check_ca(x);
690         if (!ca_ret)
691             return 0;
692         /* check nsCertType if present */
693         if (ca_ret != 5 || x->ex_nscert & NS_SMIME_CA)
694             return ca_ret;
695         else
696             return 0;
697     }
698     if (x->ex_flags & EXFLAG_NSCERT) {
699         if (x->ex_nscert & NS_SMIME)
700             return 1;
701         /* Workaround for some buggy certificates */
702         if (x->ex_nscert & NS_SSL_CLIENT)
703             return 2;
704         return 0;
705     }
706     return 1;
707 }
708
709 static int check_purpose_smime_sign(const X509_PURPOSE *xp, const X509 *x,
710                                     int ca)
711 {
712     int ret;
713     ret = purpose_smime(x, ca);
714     if (!ret || ca)
715         return ret;
716     if (ku_reject(x, KU_DIGITAL_SIGNATURE | KU_NON_REPUDIATION))
717         return 0;
718     return ret;
719 }
720
721 static int check_purpose_smime_encrypt(const X509_PURPOSE *xp, const X509 *x,
722                                        int ca)
723 {
724     int ret;
725     ret = purpose_smime(x, ca);
726     if (!ret || ca)
727         return ret;
728     if (ku_reject(x, KU_KEY_ENCIPHERMENT))
729         return 0;
730     return ret;
731 }
732
733 static int check_purpose_crl_sign(const X509_PURPOSE *xp, const X509 *x,
734                                   int ca)
735 {
736     if (ca) {
737         int ca_ret;
738         if ((ca_ret = check_ca(x)) != 2)
739             return ca_ret;
740         else
741             return 0;
742     }
743     if (ku_reject(x, KU_CRL_SIGN))
744         return 0;
745     return 1;
746 }
747
748 /*
749  * OCSP helper: this is *not* a full OCSP check. It just checks that each CA
750  * is valid. Additional checks must be made on the chain.
751  */
752
753 static int ocsp_helper(const X509_PURPOSE *xp, const X509 *x, int ca)
754 {
755     /*
756      * Must be a valid CA.  Should we really support the "I don't know" value
757      * (2)?
758      */
759     if (ca)
760         return check_ca(x);
761     /* leaf certificate is checked in OCSP_verify() */
762     return 1;
763 }
764
765 static int check_purpose_timestamp_sign(const X509_PURPOSE *xp, const X509 *x,
766                                         int ca)
767 {
768     int i_ext;
769
770     /* If ca is true we must return if this is a valid CA certificate. */
771     if (ca)
772         return check_ca(x);
773
774     /*
775      * Check the optional key usage field:
776      * if Key Usage is present, it must be one of digitalSignature
777      * and/or nonRepudiation (other values are not consistent and shall
778      * be rejected).
779      */
780     if ((x->ex_flags & EXFLAG_KUSAGE)
781         && ((x->ex_kusage & ~(KU_NON_REPUDIATION | KU_DIGITAL_SIGNATURE)) ||
782             !(x->ex_kusage & (KU_NON_REPUDIATION | KU_DIGITAL_SIGNATURE))))
783         return 0;
784
785     /* Only time stamp key usage is permitted and it's required. */
786     if (!(x->ex_flags & EXFLAG_XKUSAGE) || x->ex_xkusage != XKU_TIMESTAMP)
787         return 0;
788
789     /* Extended Key Usage MUST be critical */
790     i_ext = X509_get_ext_by_NID(x, NID_ext_key_usage, -1);
791     if (i_ext >= 0) {
792         X509_EXTENSION *ext = X509_get_ext((X509 *)x, i_ext);
793         if (!X509_EXTENSION_get_critical(ext))
794             return 0;
795     }
796
797     return 1;
798 }
799
800 static int no_check(const X509_PURPOSE *xp, const X509 *x, int ca)
801 {
802     return 1;
803 }
804
805 /*-
806  * Various checks to see if one certificate issued the second.
807  * This can be used to prune a set of possible issuer certificates
808  * which have been looked up using some simple method such as by
809  * subject name.
810  * These are:
811  * 1. Check issuer_name(subject) == subject_name(issuer)
812  * 2. If akid(subject) exists, check that it matches issuer
813  * 3. Check that issuer public key algorithm matches subject signature algorithm
814  * 4. If key_usage(issuer) exists, check that it supports certificate signing
815  * returns 0 for OK, positive for reason for mismatch, reasons match
816  * codes for X509_verify_cert()
817  */
818
819 int x509_check_issued_int(X509 *issuer, X509 *subject, OPENSSL_CTX *libctx,
820                           const char *propq)
821 {
822     if (X509_NAME_cmp(X509_get_subject_name(issuer),
823                       X509_get_issuer_name(subject)))
824         return X509_V_ERR_SUBJECT_ISSUER_MISMATCH;
825
826     if (!X509v3_cache_extensions(issuer, libctx, propq)
827             || !X509v3_cache_extensions(subject, libctx, propq))
828         return X509_V_ERR_UNSPECIFIED;
829
830     if (subject->akid) {
831         int ret = X509_check_akid(issuer, subject->akid);
832         if (ret != X509_V_OK)
833             return ret;
834     }
835
836     {
837         /*
838          * Check if the subject signature algorithm matches the issuer's PUBKEY
839          * algorithm
840          */
841         EVP_PKEY *i_pkey = X509_get0_pubkey(issuer);
842         X509_ALGOR *s_algor = &subject->cert_info.signature;
843         int s_pknid = NID_undef, s_mdnid = NID_undef;
844
845         if (i_pkey == NULL)
846             return X509_V_ERR_NO_ISSUER_PUBLIC_KEY;
847
848         if (!OBJ_find_sigid_algs(OBJ_obj2nid(s_algor->algorithm),
849                                  &s_mdnid, &s_pknid)
850             || EVP_PKEY_type(s_pknid) != EVP_PKEY_base_id(i_pkey))
851             return X509_V_ERR_SIGNATURE_ALGORITHM_MISMATCH;
852     }
853
854     if (subject->ex_flags & EXFLAG_PROXY) {
855         if (ku_reject(issuer, KU_DIGITAL_SIGNATURE))
856             return X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE;
857     } else if (ku_reject(issuer, KU_KEY_CERT_SIGN))
858         return X509_V_ERR_KEYUSAGE_NO_CERTSIGN;
859     return X509_V_OK;
860 }
861
862 int X509_check_issued(X509 *issuer, X509 *subject)
863 {
864     return x509_check_issued_int(issuer, subject, NULL, NULL);
865 }
866
867 int X509_check_akid(X509 *issuer, AUTHORITY_KEYID *akid)
868 {
869
870     if (!akid)
871         return X509_V_OK;
872
873     /* Check key ids (if present) */
874     if (akid->keyid && issuer->skid &&
875         ASN1_OCTET_STRING_cmp(akid->keyid, issuer->skid))
876         return X509_V_ERR_AKID_SKID_MISMATCH;
877     /* Check serial number */
878     if (akid->serial &&
879         ASN1_INTEGER_cmp(X509_get_serialNumber(issuer), akid->serial))
880         return X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH;
881     /* Check issuer name */
882     if (akid->issuer) {
883         /*
884          * Ugh, for some peculiar reason AKID includes SEQUENCE OF
885          * GeneralName. So look for a DirName. There may be more than one but
886          * we only take any notice of the first.
887          */
888         GENERAL_NAMES *gens;
889         GENERAL_NAME *gen;
890         X509_NAME *nm = NULL;
891         int i;
892         gens = akid->issuer;
893         for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
894             gen = sk_GENERAL_NAME_value(gens, i);
895             if (gen->type == GEN_DIRNAME) {
896                 nm = gen->d.dirn;
897                 break;
898             }
899         }
900         if (nm && X509_NAME_cmp(nm, X509_get_issuer_name(issuer)))
901             return X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH;
902     }
903     return X509_V_OK;
904 }
905
906 uint32_t X509_get_extension_flags(X509 *x)
907 {
908     /* Call for side-effect of computing hash and caching extensions */
909     X509_check_purpose(x, -1, -1);
910     return x->ex_flags;
911 }
912
913 uint32_t X509_get_key_usage(X509 *x)
914 {
915     /* Call for side-effect of computing hash and caching extensions */
916     if (X509_check_purpose(x, -1, -1) != 1)
917         return 0;
918     if (x->ex_flags & EXFLAG_KUSAGE)
919         return x->ex_kusage;
920     return UINT32_MAX;
921 }
922
923 uint32_t X509_get_extended_key_usage(X509 *x)
924 {
925     /* Call for side-effect of computing hash and caching extensions */
926     if (X509_check_purpose(x, -1, -1) != 1)
927         return 0;
928     if (x->ex_flags & EXFLAG_XKUSAGE)
929         return x->ex_xkusage;
930     return UINT32_MAX;
931 }
932
933 const ASN1_OCTET_STRING *X509_get0_subject_key_id(X509 *x)
934 {
935     /* Call for side-effect of computing hash and caching extensions */
936     if (X509_check_purpose(x, -1, -1) != 1)
937         return NULL;
938     return x->skid;
939 }
940
941 const ASN1_OCTET_STRING *X509_get0_authority_key_id(X509 *x)
942 {
943     /* Call for side-effect of computing hash and caching extensions */
944     if (X509_check_purpose(x, -1, -1) != 1)
945         return NULL;
946     return (x->akid != NULL ? x->akid->keyid : NULL);
947 }
948
949 const GENERAL_NAMES *X509_get0_authority_issuer(X509 *x)
950 {
951     /* Call for side-effect of computing hash and caching extensions */
952     if (X509_check_purpose(x, -1, -1) != 1)
953         return NULL;
954     return (x->akid != NULL ? x->akid->issuer : NULL);
955 }
956
957 const ASN1_INTEGER *X509_get0_authority_serial(X509 *x)
958 {
959     /* Call for side-effect of computing hash and caching extensions */
960     if (X509_check_purpose(x, -1, -1) != 1)
961         return NULL;
962     return (x->akid != NULL ? x->akid->serial : NULL);
963 }
964
965 long X509_get_pathlen(X509 *x)
966 {
967     /* Called for side effect of caching extensions */
968     if (X509_check_purpose(x, -1, -1) != 1
969             || (x->ex_flags & EXFLAG_BCONS) == 0)
970         return -1;
971     return x->ex_pathlen;
972 }
973
974 long X509_get_proxy_pathlen(X509 *x)
975 {
976     /* Called for side effect of caching extensions */
977     if (X509_check_purpose(x, -1, -1) != 1
978             || (x->ex_flags & EXFLAG_PROXY) == 0)
979         return -1;
980     return x->ex_pcpathlen;
981 }