1 /* $OpenBSD: x509_purp.c,v 1.2 2020/09/13 15:06:17 beck Exp $ */
2 /* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
3  * project 2001.
4  */
5 /* ====================================================================
6  * Copyright (c) 1999-2004 The OpenSSL Project.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in
17  *    the documentation and/or other materials provided with the
18  *    distribution.
19  *
20  * 3. All advertising materials mentioning features or use of this
21  *    software must display the following acknowledgment:
22  *    "This product includes software developed by the OpenSSL Project
23  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24  *
25  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26  *    endorse or promote products derived from this software without
27  *    prior written permission. For written permission, please contact
28  *    licensing@OpenSSL.org.
29  *
30  * 5. Products derived from this software may not be called "OpenSSL"
31  *    nor may "OpenSSL" appear in their names without prior written
32  *    permission of the OpenSSL Project.
33  *
34  * 6. Redistributions of any form whatsoever must retain the following
35  *    acknowledgment:
36  *    "This product includes software developed by the OpenSSL Project
37  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38  *
39  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
43  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50  * OF THE POSSIBILITY OF SUCH DAMAGE.
51  * ====================================================================
52  *
53  * This product includes cryptographic software written by Eric Young
54  * (eay@cryptsoft.com).  This product includes software written by Tim
55  * Hudson (tjh@cryptsoft.com).
56  *
57  */
58 
59 #include <stdio.h>
60 #include <string.h>
61 
62 #include <openssl/opensslconf.h>
63 
64 #include <openssl/err.h>
65 #include <openssl/x509v3.h>
66 #include <openssl/x509_vfy.h>
67 
68 #define V1_ROOT (EXFLAG_V1|EXFLAG_SS)
69 #define ku_reject(x, usage) \
70 	(((x)->ex_flags & EXFLAG_KUSAGE) && !((x)->ex_kusage & (usage)))
71 #define xku_reject(x, usage) \
72 	(((x)->ex_flags & EXFLAG_XKUSAGE) && !((x)->ex_xkusage & (usage)))
73 #define ns_reject(x, usage) \
74 	(((x)->ex_flags & EXFLAG_NSCERT) && !((x)->ex_nscert & (usage)))
75 
76 void x509v3_cache_extensions(X509 *x);
77 
78 static int check_ssl_ca(const X509 *x);
79 static int check_purpose_ssl_client(const X509_PURPOSE *xp, const X509 *x,
80     int ca);
81 static int check_purpose_ssl_server(const X509_PURPOSE *xp, const X509 *x,
82     int ca);
83 static int check_purpose_ns_ssl_server(const X509_PURPOSE *xp, const X509 *x,
84     int ca);
85 static int purpose_smime(const X509 *x, int ca);
86 static int check_purpose_smime_sign(const X509_PURPOSE *xp, const X509 *x,
87     int ca);
88 static int check_purpose_smime_encrypt(const X509_PURPOSE *xp, const X509 *x,
89     int ca);
90 static int check_purpose_crl_sign(const X509_PURPOSE *xp, const X509 *x,
91     int ca);
92 static int check_purpose_timestamp_sign(const X509_PURPOSE *xp, const X509 *x,
93     int ca);
94 static int no_check(const X509_PURPOSE *xp, const X509 *x, int ca);
95 static int ocsp_helper(const X509_PURPOSE *xp, const X509 *x, int ca);
96 
97 static int xp_cmp(const X509_PURPOSE * const *a, const X509_PURPOSE * const *b);
98 static void xptable_free(X509_PURPOSE *p);
99 
100 static X509_PURPOSE xstandard[] = {
101 	{X509_PURPOSE_SSL_CLIENT, X509_TRUST_SSL_CLIENT, 0, check_purpose_ssl_client, "SSL client", "sslclient", NULL},
102 	{X509_PURPOSE_SSL_SERVER, X509_TRUST_SSL_SERVER, 0, check_purpose_ssl_server, "SSL server", "sslserver", NULL},
103 	{X509_PURPOSE_NS_SSL_SERVER, X509_TRUST_SSL_SERVER, 0, check_purpose_ns_ssl_server, "Netscape SSL server", "nssslserver", NULL},
104 	{X509_PURPOSE_SMIME_SIGN, X509_TRUST_EMAIL, 0, check_purpose_smime_sign, "S/MIME signing", "smimesign", NULL},
105 	{X509_PURPOSE_SMIME_ENCRYPT, X509_TRUST_EMAIL, 0, check_purpose_smime_encrypt, "S/MIME encryption", "smimeencrypt", NULL},
106 	{X509_PURPOSE_CRL_SIGN, X509_TRUST_COMPAT, 0, check_purpose_crl_sign, "CRL signing", "crlsign", NULL},
107 	{X509_PURPOSE_ANY, X509_TRUST_DEFAULT, 0, no_check, "Any Purpose", "any", NULL},
108 	{X509_PURPOSE_OCSP_HELPER, X509_TRUST_COMPAT, 0, ocsp_helper, "OCSP helper", "ocsphelper", NULL},
109 	{X509_PURPOSE_TIMESTAMP_SIGN, X509_TRUST_TSA, 0, check_purpose_timestamp_sign, "Time Stamp signing", "timestampsign", NULL},
110 };
111 
112 #define X509_PURPOSE_COUNT (sizeof(xstandard)/sizeof(X509_PURPOSE))
113 
114 static STACK_OF(X509_PURPOSE) *xptable = NULL;
115 
116 static int
117 xp_cmp(const X509_PURPOSE * const *a, const X509_PURPOSE * const *b)
118 {
119 	return (*a)->purpose - (*b)->purpose;
120 }
121 
122 /* As much as I'd like to make X509_check_purpose use a "const" X509*
123  * I really can't because it does recalculate hashes and do other non-const
124  * things. */
125 int
126 X509_check_purpose(X509 *x, int id, int ca)
127 {
128 	int idx;
129 	const X509_PURPOSE *pt;
130 
131 	if (!(x->ex_flags & EXFLAG_SET)) {
132 		CRYPTO_w_lock(CRYPTO_LOCK_X509);
133 		x509v3_cache_extensions(x);
134 		CRYPTO_w_unlock(CRYPTO_LOCK_X509);
135 	}
136 	if (id == -1)
137 		return 1;
138 	idx = X509_PURPOSE_get_by_id(id);
139 	if (idx == -1)
140 		return -1;
141 	pt = X509_PURPOSE_get0(idx);
142 	return pt->check_purpose(pt, x, ca);
143 }
144 
145 int
146 X509_PURPOSE_set(int *p, int purpose)
147 {
148 	if (X509_PURPOSE_get_by_id(purpose) == -1) {
149 		X509V3error(X509V3_R_INVALID_PURPOSE);
150 		return 0;
151 	}
152 	*p = purpose;
153 	return 1;
154 }
155 
156 int
157 X509_PURPOSE_get_count(void)
158 {
159 	if (!xptable)
160 		return X509_PURPOSE_COUNT;
161 	return sk_X509_PURPOSE_num(xptable) + X509_PURPOSE_COUNT;
162 }
163 
164 X509_PURPOSE *
165 X509_PURPOSE_get0(int idx)
166 {
167 	if (idx < 0)
168 		return NULL;
169 	if (idx < (int)X509_PURPOSE_COUNT)
170 		return xstandard + idx;
171 	return sk_X509_PURPOSE_value(xptable, idx - X509_PURPOSE_COUNT);
172 }
173 
174 int
175 X509_PURPOSE_get_by_sname(const char *sname)
176 {
177 	int i;
178 	X509_PURPOSE *xptmp;
179 
180 	for (i = 0; i < X509_PURPOSE_get_count(); i++) {
181 		xptmp = X509_PURPOSE_get0(i);
182 		if (!strcmp(xptmp->sname, sname))
183 			return i;
184 	}
185 	return -1;
186 }
187 
188 int
189 X509_PURPOSE_get_by_id(int purpose)
190 {
191 	X509_PURPOSE tmp;
192 	int idx;
193 
194 	if ((purpose >= X509_PURPOSE_MIN) && (purpose <= X509_PURPOSE_MAX))
195 		return purpose - X509_PURPOSE_MIN;
196 	tmp.purpose = purpose;
197 	if (!xptable)
198 		return -1;
199 	idx = sk_X509_PURPOSE_find(xptable, &tmp);
200 	if (idx == -1)
201 		return -1;
202 	return idx + X509_PURPOSE_COUNT;
203 }
204 
205 int
206 X509_PURPOSE_add(int id, int trust, int flags,
207     int (*ck)(const X509_PURPOSE *, const X509 *, int), const char *name,
208     const char *sname, void *arg)
209 {
210 	int idx;
211 	X509_PURPOSE *ptmp;
212 	char *name_dup, *sname_dup;
213 
214 	name_dup = sname_dup = NULL;
215 
216 	if (name == NULL || sname == NULL) {
217 		X509V3error(X509V3_R_INVALID_NULL_ARGUMENT);
218 		return 0;
219 	}
220 
221 	/* This is set according to what we change: application can't set it */
222 	flags &= ~X509_PURPOSE_DYNAMIC;
223 	/* This will always be set for application modified trust entries */
224 	flags |= X509_PURPOSE_DYNAMIC_NAME;
225 	/* Get existing entry if any */
226 	idx = X509_PURPOSE_get_by_id(id);
227 	/* Need a new entry */
228 	if (idx == -1) {
229 		if ((ptmp = malloc(sizeof(X509_PURPOSE))) == NULL) {
230 			X509V3error(ERR_R_MALLOC_FAILURE);
231 			return 0;
232 		}
233 		ptmp->flags = X509_PURPOSE_DYNAMIC;
234 	} else
235 		ptmp = X509_PURPOSE_get0(idx);
236 
237 	if ((name_dup = strdup(name)) == NULL)
238 		goto err;
239 	if ((sname_dup = strdup(sname)) == NULL)
240 		goto err;
241 
242 	/* free existing name if dynamic */
243 	if (ptmp->flags & X509_PURPOSE_DYNAMIC_NAME) {
244 		free(ptmp->name);
245 		free(ptmp->sname);
246 	}
247 	/* dup supplied name */
248 	ptmp->name = name_dup;
249 	ptmp->sname = sname_dup;
250 	/* Keep the dynamic flag of existing entry */
251 	ptmp->flags &= X509_PURPOSE_DYNAMIC;
252 	/* Set all other flags */
253 	ptmp->flags |= flags;
254 
255 	ptmp->purpose = id;
256 	ptmp->trust = trust;
257 	ptmp->check_purpose = ck;
258 	ptmp->usr_data = arg;
259 
260 	/* If its a new entry manage the dynamic table */
261 	if (idx == -1) {
262 		if (xptable == NULL &&
263 		    (xptable = sk_X509_PURPOSE_new(xp_cmp)) == NULL)
264 			goto err;
265 		if (sk_X509_PURPOSE_push(xptable, ptmp) == 0)
266 			goto err;
267 	}
268 	return 1;
269 
270 err:
271 	free(name_dup);
272 	free(sname_dup);
273 	if (idx == -1)
274 		free(ptmp);
275 	X509V3error(ERR_R_MALLOC_FAILURE);
276 	return 0;
277 }
278 
279 static void
280 xptable_free(X509_PURPOSE *p)
281 {
282 	if (!p)
283 		return;
284 	if (p->flags & X509_PURPOSE_DYNAMIC) {
285 		if (p->flags & X509_PURPOSE_DYNAMIC_NAME) {
286 			free(p->name);
287 			free(p->sname);
288 		}
289 		free(p);
290 	}
291 }
292 
293 void
294 X509_PURPOSE_cleanup(void)
295 {
296 	unsigned int i;
297 
298 	sk_X509_PURPOSE_pop_free(xptable, xptable_free);
299 	for(i = 0; i < X509_PURPOSE_COUNT; i++)
300 		xptable_free(xstandard + i);
301 	xptable = NULL;
302 }
303 
304 int
305 X509_PURPOSE_get_id(const X509_PURPOSE *xp)
306 {
307 	return xp->purpose;
308 }
309 
310 char *
311 X509_PURPOSE_get0_name(const X509_PURPOSE *xp)
312 {
313 	return xp->name;
314 }
315 
316 char *
317 X509_PURPOSE_get0_sname(const X509_PURPOSE *xp)
318 {
319 	return xp->sname;
320 }
321 
322 int
323 X509_PURPOSE_get_trust(const X509_PURPOSE *xp)
324 {
325 	return xp->trust;
326 }
327 
328 static int
329 nid_cmp(const int *a, const int *b)
330 {
331 	return *a - *b;
332 }
333 
334 static int nid_cmp_BSEARCH_CMP_FN(const void *, const void *);
335 static int nid_cmp(int const *, int const *);
336 static int *OBJ_bsearch_nid(int *key, int const *base, int num);
337 
338 static int
339 nid_cmp_BSEARCH_CMP_FN(const void *a_, const void *b_)
340 {
341 	int const *a = a_;
342 	int const *b = b_;
343 	return nid_cmp(a, b);
344 }
345 
346 static int *
347 OBJ_bsearch_nid(int *key, int const *base, int num)
348 {
349 	return (int *)OBJ_bsearch_(key, base, num, sizeof(int),
350 	    nid_cmp_BSEARCH_CMP_FN);
351 }
352 
353 int
354 X509_supported_extension(X509_EXTENSION *ex)
355 {
356 	/* This table is a list of the NIDs of supported extensions:
357 	 * that is those which are used by the verify process. If
358 	 * an extension is critical and doesn't appear in this list
359 	 * then the verify process will normally reject the certificate.
360 	 * The list must be kept in numerical order because it will be
361 	 * searched using bsearch.
362 	 */
363 
364 	static const int supported_nids[] = {
365 		NID_netscape_cert_type, /* 71 */
366 		NID_key_usage,		/* 83 */
367 		NID_subject_alt_name,	/* 85 */
368 		NID_basic_constraints,	/* 87 */
369 		NID_certificate_policies, /* 89 */
370 		NID_ext_key_usage,	/* 126 */
371 		NID_policy_constraints,	/* 401 */
372 		NID_proxyCertInfo,	/* 663 */
373 		NID_name_constraints,	/* 666 */
374 		NID_policy_mappings,	/* 747 */
375 		NID_inhibit_any_policy	/* 748 */
376 	};
377 
378 	int ex_nid = OBJ_obj2nid(X509_EXTENSION_get_object(ex));
379 
380 	if (ex_nid == NID_undef)
381 		return 0;
382 
383 	if (OBJ_bsearch_nid(&ex_nid, supported_nids,
384 	    sizeof(supported_nids) / sizeof(int)))
385 		return 1;
386 	return 0;
387 }
388 
389 static void
390 setup_dp(X509 *x, DIST_POINT *dp)
391 {
392 	X509_NAME *iname = NULL;
393 	int i;
394 
395 	if (dp->reasons) {
396 		if (dp->reasons->length > 0)
397 			dp->dp_reasons = dp->reasons->data[0];
398 		if (dp->reasons->length > 1)
399 			dp->dp_reasons |= (dp->reasons->data[1] << 8);
400 		dp->dp_reasons &= CRLDP_ALL_REASONS;
401 	} else
402 		dp->dp_reasons = CRLDP_ALL_REASONS;
403 	if (!dp->distpoint || (dp->distpoint->type != 1))
404 		return;
405 	for (i = 0; i < sk_GENERAL_NAME_num(dp->CRLissuer); i++) {
406 		GENERAL_NAME *gen = sk_GENERAL_NAME_value(dp->CRLissuer, i);
407 		if (gen->type == GEN_DIRNAME) {
408 			iname = gen->d.directoryName;
409 			break;
410 		}
411 	}
412 	if (!iname)
413 		iname = X509_get_issuer_name(x);
414 
415 	DIST_POINT_set_dpname(dp->distpoint, iname);
416 
417 }
418 
419 static void
420 setup_crldp(X509 *x)
421 {
422 	int i;
423 
424 	x->crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, NULL, NULL);
425 	for (i = 0; i < sk_DIST_POINT_num(x->crldp); i++)
426 		setup_dp(x, sk_DIST_POINT_value(x->crldp, i));
427 }
428 
429 void
430 x509v3_cache_extensions(X509 *x)
431 {
432 	BASIC_CONSTRAINTS *bs;
433 	PROXY_CERT_INFO_EXTENSION *pci;
434 	ASN1_BIT_STRING *usage;
435 	ASN1_BIT_STRING *ns;
436 	EXTENDED_KEY_USAGE *extusage;
437 	X509_EXTENSION *ex;
438 	int i;
439 
440 	if (x->ex_flags & EXFLAG_SET)
441 		return;
442 
443 #ifndef OPENSSL_NO_SHA
444 	X509_digest(x, EVP_sha1(), x->sha1_hash, NULL);
445 #endif
446 
447 	/* V1 should mean no extensions ... */
448 	if (!X509_get_version(x))
449 		x->ex_flags |= EXFLAG_V1;
450 
451 	/* Handle basic constraints */
452 	if ((bs = X509_get_ext_d2i(x, NID_basic_constraints, NULL, NULL))) {
453 		if (bs->ca)
454 			x->ex_flags |= EXFLAG_CA;
455 		if (bs->pathlen) {
456 			if ((bs->pathlen->type == V_ASN1_NEG_INTEGER) ||
457 			    !bs->ca) {
458 				x->ex_flags |= EXFLAG_INVALID;
459 				x->ex_pathlen = 0;
460 			} else
461 				x->ex_pathlen = ASN1_INTEGER_get(bs->pathlen);
462 		} else
463 			x->ex_pathlen = -1;
464 		BASIC_CONSTRAINTS_free(bs);
465 		x->ex_flags |= EXFLAG_BCONS;
466 	}
467 
468 	/* Handle proxy certificates */
469 	if ((pci = X509_get_ext_d2i(x, NID_proxyCertInfo, NULL, NULL))) {
470 		if (x->ex_flags & EXFLAG_CA ||
471 		    X509_get_ext_by_NID(x, NID_subject_alt_name, -1) >= 0 ||
472 		    X509_get_ext_by_NID(x, NID_issuer_alt_name, -1) >= 0) {
473 			x->ex_flags |= EXFLAG_INVALID;
474 		}
475 		if (pci->pcPathLengthConstraint) {
476 			if (pci->pcPathLengthConstraint->type ==
477 			    V_ASN1_NEG_INTEGER) {
478 				x->ex_flags |= EXFLAG_INVALID;
479 				x->ex_pcpathlen = 0;
480 			} else
481 				x->ex_pcpathlen =
482 				    ASN1_INTEGER_get(pci->
483 				      pcPathLengthConstraint);
484 		} else
485 			x->ex_pcpathlen = -1;
486 		PROXY_CERT_INFO_EXTENSION_free(pci);
487 		x->ex_flags |= EXFLAG_PROXY;
488 	}
489 
490 	/* Handle key usage */
491 	if ((usage = X509_get_ext_d2i(x, NID_key_usage, NULL, NULL))) {
492 		if (usage->length > 0) {
493 			x->ex_kusage = usage->data[0];
494 			if (usage->length > 1)
495 				x->ex_kusage |= usage->data[1] << 8;
496 		} else
497 			x->ex_kusage = 0;
498 		x->ex_flags |= EXFLAG_KUSAGE;
499 		ASN1_BIT_STRING_free(usage);
500 	}
501 	x->ex_xkusage = 0;
502 	if ((extusage = X509_get_ext_d2i(x, NID_ext_key_usage, NULL, NULL))) {
503 		x->ex_flags |= EXFLAG_XKUSAGE;
504 		for (i = 0; i < sk_ASN1_OBJECT_num(extusage); i++) {
505 			switch (OBJ_obj2nid(sk_ASN1_OBJECT_value(extusage, i))) {
506 			case NID_server_auth:
507 				x->ex_xkusage |= XKU_SSL_SERVER;
508 				break;
509 
510 			case NID_client_auth:
511 				x->ex_xkusage |= XKU_SSL_CLIENT;
512 				break;
513 
514 			case NID_email_protect:
515 				x->ex_xkusage |= XKU_SMIME;
516 				break;
517 
518 			case NID_code_sign:
519 				x->ex_xkusage |= XKU_CODE_SIGN;
520 				break;
521 
522 			case NID_ms_sgc:
523 			case NID_ns_sgc:
524 				x->ex_xkusage |= XKU_SGC;
525 				break;
526 
527 			case NID_OCSP_sign:
528 				x->ex_xkusage |= XKU_OCSP_SIGN;
529 				break;
530 
531 			case NID_time_stamp:
532 				x->ex_xkusage |= XKU_TIMESTAMP;
533 				break;
534 
535 			case NID_dvcs:
536 				x->ex_xkusage |= XKU_DVCS;
537 				break;
538 			}
539 		}
540 		sk_ASN1_OBJECT_pop_free(extusage, ASN1_OBJECT_free);
541 	}
542 
543 	if ((ns = X509_get_ext_d2i(x, NID_netscape_cert_type, NULL, NULL))) {
544 		if (ns->length > 0)
545 			x->ex_nscert = ns->data[0];
546 		else
547 			x->ex_nscert = 0;
548 		x->ex_flags |= EXFLAG_NSCERT;
549 		ASN1_BIT_STRING_free(ns);
550 	}
551 
552 	x->skid = X509_get_ext_d2i(x, NID_subject_key_identifier, NULL, NULL);
553 	x->akid = X509_get_ext_d2i(x, NID_authority_key_identifier, NULL, NULL);
554 
555 	/* Does subject name match issuer? */
556 	if (!X509_NAME_cmp(X509_get_subject_name(x), X509_get_issuer_name(x))) {
557 		x->ex_flags |= EXFLAG_SI;
558 		/* If SKID matches AKID also indicate self signed. */
559 		if (X509_check_akid(x, x->akid) == X509_V_OK &&
560 		    !ku_reject(x, KU_KEY_CERT_SIGN))
561 			x->ex_flags |= EXFLAG_SS;
562 	}
563 
564 	x->altname = X509_get_ext_d2i(x, NID_subject_alt_name, NULL, NULL);
565 	x->nc = X509_get_ext_d2i(x, NID_name_constraints, &i, NULL);
566 	if (!x->nc && (i != -1))
567 		x->ex_flags |= EXFLAG_INVALID;
568 	setup_crldp(x);
569 
570 	for (i = 0; i < X509_get_ext_count(x); i++) {
571 		ex = X509_get_ext(x, i);
572 		if (OBJ_obj2nid(X509_EXTENSION_get_object(ex)) ==
573 		    NID_freshest_crl)
574 			x->ex_flags |= EXFLAG_FRESHEST;
575 		if (!X509_EXTENSION_get_critical(ex))
576 			continue;
577 		if (!X509_supported_extension(ex)) {
578 			x->ex_flags |= EXFLAG_CRITICAL;
579 			break;
580 		}
581 	}
582 	x->ex_flags |= EXFLAG_SET;
583 }
584 
585 /* CA checks common to all purposes
586  * return codes:
587  * 0 not a CA
588  * 1 is a CA
589  * 2 basicConstraints absent so "maybe" a CA
590  * 3 basicConstraints absent but self signed V1.
591  * 4 basicConstraints absent but keyUsage present and keyCertSign asserted.
592  */
593 
594 static int
595 check_ca(const X509 *x)
596 {
597 	/* keyUsage if present should allow cert signing */
598 	if (ku_reject(x, KU_KEY_CERT_SIGN))
599 		return 0;
600 	if (x->ex_flags & EXFLAG_BCONS) {
601 		if (x->ex_flags & EXFLAG_CA)
602 			return 1;
603 		/* If basicConstraints says not a CA then say so */
604 		else
605 			return 0;
606 	} else {
607 		/* we support V1 roots for...  uh, I don't really know why. */
608 		if ((x->ex_flags & V1_ROOT) == V1_ROOT)
609 			return 3;
610 		/* If key usage present it must have certSign so tolerate it */
611 		else if (x->ex_flags & EXFLAG_KUSAGE)
612 			return 4;
613 		/* Older certificates could have Netscape-specific CA types */
614 		else if (x->ex_flags & EXFLAG_NSCERT &&
615 		    x->ex_nscert & NS_ANY_CA)
616 			return 5;
617 		/* can this still be regarded a CA certificate?  I doubt it */
618 		return 0;
619 	}
620 }
621 
622 int
623 X509_check_ca(X509 *x)
624 {
625 	if (!(x->ex_flags & EXFLAG_SET)) {
626 		CRYPTO_w_lock(CRYPTO_LOCK_X509);
627 		x509v3_cache_extensions(x);
628 		CRYPTO_w_unlock(CRYPTO_LOCK_X509);
629 	}
630 
631 	return check_ca(x);
632 }
633 
634 /* Check SSL CA: common checks for SSL client and server */
635 static int
636 check_ssl_ca(const X509 *x)
637 {
638 	int ca_ret;
639 
640 	ca_ret = check_ca(x);
641 	if (!ca_ret)
642 		return 0;
643 	/* check nsCertType if present */
644 	if (ca_ret != 5 || x->ex_nscert & NS_SSL_CA)
645 		return ca_ret;
646 	else
647 		return 0;
648 }
649 
650 static int
651 check_purpose_ssl_client(const X509_PURPOSE *xp, const X509 *x, int ca)
652 {
653 	if (xku_reject(x, XKU_SSL_CLIENT))
654 		return 0;
655 	if (ca)
656 		return check_ssl_ca(x);
657 	/* We need to do digital signatures with it */
658 	if (ku_reject(x, KU_DIGITAL_SIGNATURE))
659 		return 0;
660 	/* nsCertType if present should allow SSL client use */
661 	if (ns_reject(x, NS_SSL_CLIENT))
662 		return 0;
663 	return 1;
664 }
665 
666 static int
667 check_purpose_ssl_server(const X509_PURPOSE *xp, const X509 *x, int ca)
668 {
669 	if (xku_reject(x, XKU_SSL_SERVER|XKU_SGC))
670 		return 0;
671 	if (ca)
672 		return check_ssl_ca(x);
673 
674 	if (ns_reject(x, NS_SSL_SERVER))
675 		return 0;
676 	/* Now as for keyUsage: we'll at least need to sign OR encipher */
677 	if (ku_reject(x, KU_DIGITAL_SIGNATURE|KU_KEY_ENCIPHERMENT))
678 		return 0;
679 
680 	return 1;
681 }
682 
683 static int
684 check_purpose_ns_ssl_server(const X509_PURPOSE *xp, const X509 *x, int ca)
685 {
686 	int ret;
687 
688 	ret = check_purpose_ssl_server(xp, x, ca);
689 	if (!ret || ca)
690 		return ret;
691 	/* We need to encipher or Netscape complains */
692 	if (ku_reject(x, KU_KEY_ENCIPHERMENT))
693 		return 0;
694 	return ret;
695 }
696 
697 /* common S/MIME checks */
698 static int
699 purpose_smime(const X509 *x, int ca)
700 {
701 	if (xku_reject(x, XKU_SMIME))
702 		return 0;
703 	if (ca) {
704 		int ca_ret;
705 		ca_ret = check_ca(x);
706 		if (!ca_ret)
707 			return 0;
708 		/* check nsCertType if present */
709 		if (ca_ret != 5 || x->ex_nscert & NS_SMIME_CA)
710 			return ca_ret;
711 		else
712 			return 0;
713 	}
714 	if (x->ex_flags & EXFLAG_NSCERT) {
715 		if (x->ex_nscert & NS_SMIME)
716 			return 1;
717 		/* Workaround for some buggy certificates */
718 		if (x->ex_nscert & NS_SSL_CLIENT)
719 			return 2;
720 		return 0;
721 	}
722 	return 1;
723 }
724 
725 static int
726 check_purpose_smime_sign(const X509_PURPOSE *xp, const X509 *x, int ca)
727 {
728 	int ret;
729 
730 	ret = purpose_smime(x, ca);
731 	if (!ret || ca)
732 		return ret;
733 	if (ku_reject(x, KU_DIGITAL_SIGNATURE|KU_NON_REPUDIATION))
734 		return 0;
735 	return ret;
736 }
737 
738 static int
739 check_purpose_smime_encrypt(const X509_PURPOSE *xp, const X509 *x, int ca)
740 {
741 	int ret;
742 
743 	ret = purpose_smime(x, ca);
744 	if (!ret || ca)
745 		return ret;
746 	if (ku_reject(x, KU_KEY_ENCIPHERMENT))
747 		return 0;
748 	return ret;
749 }
750 
751 static int
752 check_purpose_crl_sign(const X509_PURPOSE *xp, const X509 *x, int ca)
753 {
754 	if (ca) {
755 		int ca_ret;
756 		if ((ca_ret = check_ca(x)) != 2)
757 			return ca_ret;
758 		else
759 			return 0;
760 	}
761 	if (ku_reject(x, KU_CRL_SIGN))
762 		return 0;
763 	return 1;
764 }
765 
766 /* OCSP helper: this is *not* a full OCSP check. It just checks that
767  * each CA is valid. Additional checks must be made on the chain.
768  */
769 static int
770 ocsp_helper(const X509_PURPOSE *xp, const X509 *x, int ca)
771 {
772 	/* Must be a valid CA.  Should we really support the "I don't know"
773 	   value (2)? */
774 	if (ca)
775 		return check_ca(x);
776 	/* leaf certificate is checked in OCSP_verify() */
777 	return 1;
778 }
779 
780 static int
781 check_purpose_timestamp_sign(const X509_PURPOSE *xp, const X509 *x, int ca)
782 {
783 	int i_ext;
784 
785 	/* If ca is true we must return if this is a valid CA certificate. */
786 	if (ca)
787 		return check_ca(x);
788 
789 	/*
790 	 * Check the optional key usage field:
791 	 * if Key Usage is present, it must be one of digitalSignature
792 	 * and/or nonRepudiation (other values are not consistent and shall
793 	 * be rejected).
794 	 */
795 	if ((x->ex_flags & EXFLAG_KUSAGE) &&
796 	    ((x->ex_kusage & ~(KU_NON_REPUDIATION | KU_DIGITAL_SIGNATURE)) ||
797 	    !(x->ex_kusage & (KU_NON_REPUDIATION | KU_DIGITAL_SIGNATURE))))
798 		return 0;
799 
800 	/* Only time stamp key usage is permitted and it's required. */
801 	if (!(x->ex_flags & EXFLAG_XKUSAGE) || x->ex_xkusage != XKU_TIMESTAMP)
802 		return 0;
803 
804 	/* Extended Key Usage MUST be critical */
805 	i_ext = X509_get_ext_by_NID((X509 *) x, NID_ext_key_usage, -1);
806 	if (i_ext >= 0) {
807 		X509_EXTENSION *ext = X509_get_ext((X509 *) x, i_ext);
808 		if (!X509_EXTENSION_get_critical(ext))
809 			return 0;
810 	}
811 
812 	return 1;
813 }
814 
815 static int
816 no_check(const X509_PURPOSE *xp, const X509 *x, int ca)
817 {
818 	return 1;
819 }
820 
821 /* Various checks to see if one certificate issued the second.
822  * This can be used to prune a set of possible issuer certificates
823  * which have been looked up using some simple method such as by
824  * subject name.
825  * These are:
826  * 1. Check issuer_name(subject) == subject_name(issuer)
827  * 2. If akid(subject) exists check it matches issuer
828  * 3. If key_usage(issuer) exists check it supports certificate signing
829  * returns 0 for OK, positive for reason for mismatch, reasons match
830  * codes for X509_verify_cert()
831  */
832 
833 int
834 X509_check_issued(X509 *issuer, X509 *subject)
835 {
836 	if (X509_NAME_cmp(X509_get_subject_name(issuer),
837 	    X509_get_issuer_name(subject)))
838 		return X509_V_ERR_SUBJECT_ISSUER_MISMATCH;
839 	x509v3_cache_extensions(issuer);
840 	x509v3_cache_extensions(subject);
841 
842 	if (subject->akid) {
843 		int ret = X509_check_akid(issuer, subject->akid);
844 		if (ret != X509_V_OK)
845 			return ret;
846 	}
847 
848 	if (subject->ex_flags & EXFLAG_PROXY) {
849 		if (ku_reject(issuer, KU_DIGITAL_SIGNATURE))
850 			return X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE;
851 	} else if (ku_reject(issuer, KU_KEY_CERT_SIGN))
852 		return X509_V_ERR_KEYUSAGE_NO_CERTSIGN;
853 	return X509_V_OK;
854 }
855 
856 int
857 X509_check_akid(X509 *issuer, AUTHORITY_KEYID *akid)
858 {
859 	if (!akid)
860 		return X509_V_OK;
861 
862 	/* Check key ids (if present) */
863 	if (akid->keyid && issuer->skid &&
864 	    ASN1_OCTET_STRING_cmp(akid->keyid, issuer->skid) )
865 		return X509_V_ERR_AKID_SKID_MISMATCH;
866 	/* Check serial number */
867 	if (akid->serial &&
868 	    ASN1_INTEGER_cmp(X509_get_serialNumber(issuer), akid->serial))
869 		return X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH;
870 	/* Check issuer name */
871 	if (akid->issuer) {
872 		/* Ugh, for some peculiar reason AKID includes
873 		 * SEQUENCE OF GeneralName. So look for a DirName.
874 		 * There may be more than one but we only take any
875 		 * notice of the first.
876 		 */
877 		GENERAL_NAMES *gens;
878 		GENERAL_NAME *gen;
879 		X509_NAME *nm = NULL;
880 		int i;
881 		gens = akid->issuer;
882 		for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
883 			gen = sk_GENERAL_NAME_value(gens, i);
884 			if (gen->type == GEN_DIRNAME) {
885 				nm = gen->d.dirn;
886 				break;
887 			}
888 		}
889 		if (nm && X509_NAME_cmp(nm, X509_get_issuer_name(issuer)))
890 			return X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH;
891 	}
892 	return X509_V_OK;
893 }
894