xref: /openbsd-src/lib/libcrypto/x509/x509_purp.c (revision f1dd7b858388b4a23f4f67a4957ec5ff656ebbe8)
1 /* $OpenBSD: x509_purp.c,v 1.4 2021/03/19 18:52:14 tb 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 		if (x->ex_flags & EXFLAG_INVALID)
136 			return X509_V_ERR_UNSPECIFIED;
137 	}
138 	if (id == -1)
139 		return 1;
140 	idx = X509_PURPOSE_get_by_id(id);
141 	if (idx == -1)
142 		return -1;
143 	pt = X509_PURPOSE_get0(idx);
144 	return pt->check_purpose(pt, x, ca);
145 }
146 
147 int
148 X509_PURPOSE_set(int *p, int purpose)
149 {
150 	if (X509_PURPOSE_get_by_id(purpose) == -1) {
151 		X509V3error(X509V3_R_INVALID_PURPOSE);
152 		return 0;
153 	}
154 	*p = purpose;
155 	return 1;
156 }
157 
158 int
159 X509_PURPOSE_get_count(void)
160 {
161 	if (!xptable)
162 		return X509_PURPOSE_COUNT;
163 	return sk_X509_PURPOSE_num(xptable) + X509_PURPOSE_COUNT;
164 }
165 
166 X509_PURPOSE *
167 X509_PURPOSE_get0(int idx)
168 {
169 	if (idx < 0)
170 		return NULL;
171 	if (idx < (int)X509_PURPOSE_COUNT)
172 		return xstandard + idx;
173 	return sk_X509_PURPOSE_value(xptable, idx - X509_PURPOSE_COUNT);
174 }
175 
176 int
177 X509_PURPOSE_get_by_sname(const char *sname)
178 {
179 	int i;
180 	X509_PURPOSE *xptmp;
181 
182 	for (i = 0; i < X509_PURPOSE_get_count(); i++) {
183 		xptmp = X509_PURPOSE_get0(i);
184 		if (!strcmp(xptmp->sname, sname))
185 			return i;
186 	}
187 	return -1;
188 }
189 
190 int
191 X509_PURPOSE_get_by_id(int purpose)
192 {
193 	X509_PURPOSE tmp;
194 	int idx;
195 
196 	if ((purpose >= X509_PURPOSE_MIN) && (purpose <= X509_PURPOSE_MAX))
197 		return purpose - X509_PURPOSE_MIN;
198 	tmp.purpose = purpose;
199 	if (!xptable)
200 		return -1;
201 	idx = sk_X509_PURPOSE_find(xptable, &tmp);
202 	if (idx == -1)
203 		return -1;
204 	return idx + X509_PURPOSE_COUNT;
205 }
206 
207 int
208 X509_PURPOSE_add(int id, int trust, int flags,
209     int (*ck)(const X509_PURPOSE *, const X509 *, int), const char *name,
210     const char *sname, void *arg)
211 {
212 	int idx;
213 	X509_PURPOSE *ptmp;
214 	char *name_dup, *sname_dup;
215 
216 	name_dup = sname_dup = NULL;
217 
218 	if (name == NULL || sname == NULL) {
219 		X509V3error(X509V3_R_INVALID_NULL_ARGUMENT);
220 		return 0;
221 	}
222 
223 	/* This is set according to what we change: application can't set it */
224 	flags &= ~X509_PURPOSE_DYNAMIC;
225 	/* This will always be set for application modified trust entries */
226 	flags |= X509_PURPOSE_DYNAMIC_NAME;
227 	/* Get existing entry if any */
228 	idx = X509_PURPOSE_get_by_id(id);
229 	/* Need a new entry */
230 	if (idx == -1) {
231 		if ((ptmp = malloc(sizeof(X509_PURPOSE))) == NULL) {
232 			X509V3error(ERR_R_MALLOC_FAILURE);
233 			return 0;
234 		}
235 		ptmp->flags = X509_PURPOSE_DYNAMIC;
236 	} else
237 		ptmp = X509_PURPOSE_get0(idx);
238 
239 	if ((name_dup = strdup(name)) == NULL)
240 		goto err;
241 	if ((sname_dup = strdup(sname)) == NULL)
242 		goto err;
243 
244 	/* free existing name if dynamic */
245 	if (ptmp->flags & X509_PURPOSE_DYNAMIC_NAME) {
246 		free(ptmp->name);
247 		free(ptmp->sname);
248 	}
249 	/* dup supplied name */
250 	ptmp->name = name_dup;
251 	ptmp->sname = sname_dup;
252 	/* Keep the dynamic flag of existing entry */
253 	ptmp->flags &= X509_PURPOSE_DYNAMIC;
254 	/* Set all other flags */
255 	ptmp->flags |= flags;
256 
257 	ptmp->purpose = id;
258 	ptmp->trust = trust;
259 	ptmp->check_purpose = ck;
260 	ptmp->usr_data = arg;
261 
262 	/* If its a new entry manage the dynamic table */
263 	if (idx == -1) {
264 		if (xptable == NULL &&
265 		    (xptable = sk_X509_PURPOSE_new(xp_cmp)) == NULL)
266 			goto err;
267 		if (sk_X509_PURPOSE_push(xptable, ptmp) == 0)
268 			goto err;
269 	}
270 	return 1;
271 
272 err:
273 	free(name_dup);
274 	free(sname_dup);
275 	if (idx == -1)
276 		free(ptmp);
277 	X509V3error(ERR_R_MALLOC_FAILURE);
278 	return 0;
279 }
280 
281 static void
282 xptable_free(X509_PURPOSE *p)
283 {
284 	if (!p)
285 		return;
286 	if (p->flags & X509_PURPOSE_DYNAMIC) {
287 		if (p->flags & X509_PURPOSE_DYNAMIC_NAME) {
288 			free(p->name);
289 			free(p->sname);
290 		}
291 		free(p);
292 	}
293 }
294 
295 void
296 X509_PURPOSE_cleanup(void)
297 {
298 	unsigned int i;
299 
300 	sk_X509_PURPOSE_pop_free(xptable, xptable_free);
301 	for(i = 0; i < X509_PURPOSE_COUNT; i++)
302 		xptable_free(xstandard + i);
303 	xptable = NULL;
304 }
305 
306 int
307 X509_PURPOSE_get_id(const X509_PURPOSE *xp)
308 {
309 	return xp->purpose;
310 }
311 
312 char *
313 X509_PURPOSE_get0_name(const X509_PURPOSE *xp)
314 {
315 	return xp->name;
316 }
317 
318 char *
319 X509_PURPOSE_get0_sname(const X509_PURPOSE *xp)
320 {
321 	return xp->sname;
322 }
323 
324 int
325 X509_PURPOSE_get_trust(const X509_PURPOSE *xp)
326 {
327 	return xp->trust;
328 }
329 
330 static int
331 nid_cmp(const int *a, const int *b)
332 {
333 	return *a - *b;
334 }
335 
336 static int nid_cmp_BSEARCH_CMP_FN(const void *, const void *);
337 static int nid_cmp(int const *, int const *);
338 static int *OBJ_bsearch_nid(int *key, int const *base, int num);
339 
340 static int
341 nid_cmp_BSEARCH_CMP_FN(const void *a_, const void *b_)
342 {
343 	int const *a = a_;
344 	int const *b = b_;
345 	return nid_cmp(a, b);
346 }
347 
348 static int *
349 OBJ_bsearch_nid(int *key, int const *base, int num)
350 {
351 	return (int *)OBJ_bsearch_(key, base, num, sizeof(int),
352 	    nid_cmp_BSEARCH_CMP_FN);
353 }
354 
355 int
356 X509_supported_extension(X509_EXTENSION *ex)
357 {
358 	/* This table is a list of the NIDs of supported extensions:
359 	 * that is those which are used by the verify process. If
360 	 * an extension is critical and doesn't appear in this list
361 	 * then the verify process will normally reject the certificate.
362 	 * The list must be kept in numerical order because it will be
363 	 * searched using bsearch.
364 	 */
365 
366 	static const int supported_nids[] = {
367 		NID_netscape_cert_type, /* 71 */
368 		NID_key_usage,		/* 83 */
369 		NID_subject_alt_name,	/* 85 */
370 		NID_basic_constraints,	/* 87 */
371 		NID_certificate_policies, /* 89 */
372 		NID_ext_key_usage,	/* 126 */
373 		NID_policy_constraints,	/* 401 */
374 		NID_proxyCertInfo,	/* 663 */
375 		NID_name_constraints,	/* 666 */
376 		NID_policy_mappings,	/* 747 */
377 		NID_inhibit_any_policy	/* 748 */
378 	};
379 
380 	int ex_nid = OBJ_obj2nid(X509_EXTENSION_get_object(ex));
381 
382 	if (ex_nid == NID_undef)
383 		return 0;
384 
385 	if (OBJ_bsearch_nid(&ex_nid, supported_nids,
386 	    sizeof(supported_nids) / sizeof(int)))
387 		return 1;
388 	return 0;
389 }
390 
391 static void
392 setup_dp(X509 *x, DIST_POINT *dp)
393 {
394 	X509_NAME *iname = NULL;
395 	int i;
396 
397 	if (dp->reasons) {
398 		if (dp->reasons->length > 0)
399 			dp->dp_reasons = dp->reasons->data[0];
400 		if (dp->reasons->length > 1)
401 			dp->dp_reasons |= (dp->reasons->data[1] << 8);
402 		dp->dp_reasons &= CRLDP_ALL_REASONS;
403 	} else
404 		dp->dp_reasons = CRLDP_ALL_REASONS;
405 	if (!dp->distpoint || (dp->distpoint->type != 1))
406 		return;
407 	for (i = 0; i < sk_GENERAL_NAME_num(dp->CRLissuer); i++) {
408 		GENERAL_NAME *gen = sk_GENERAL_NAME_value(dp->CRLissuer, i);
409 		if (gen->type == GEN_DIRNAME) {
410 			iname = gen->d.directoryName;
411 			break;
412 		}
413 	}
414 	if (!iname)
415 		iname = X509_get_issuer_name(x);
416 
417 	DIST_POINT_set_dpname(dp->distpoint, iname);
418 
419 }
420 
421 static void
422 setup_crldp(X509 *x)
423 {
424 	int i;
425 
426 	x->crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, &i, NULL);
427 	if (x->crldp == NULL && i != -1) {
428 		x->ex_flags |= EXFLAG_INVALID;
429 		return;
430 	}
431 
432 	for (i = 0; i < sk_DIST_POINT_num(x->crldp); i++)
433 		setup_dp(x, sk_DIST_POINT_value(x->crldp, i));
434 }
435 
436 void
437 x509v3_cache_extensions(X509 *x)
438 {
439 	BASIC_CONSTRAINTS *bs;
440 	PROXY_CERT_INFO_EXTENSION *pci;
441 	ASN1_BIT_STRING *usage;
442 	ASN1_BIT_STRING *ns;
443 	EXTENDED_KEY_USAGE *extusage;
444 	X509_EXTENSION *ex;
445 	int i;
446 
447 	if (x->ex_flags & EXFLAG_SET)
448 		return;
449 
450 #ifndef OPENSSL_NO_SHA
451 	X509_digest(x, EVP_sha1(), x->sha1_hash, NULL);
452 #endif
453 
454 	/* V1 should mean no extensions ... */
455 	if (!X509_get_version(x))
456 		x->ex_flags |= EXFLAG_V1;
457 
458 	/* Handle basic constraints */
459 	if ((bs = X509_get_ext_d2i(x, NID_basic_constraints, &i, NULL))) {
460 		if (bs->ca)
461 			x->ex_flags |= EXFLAG_CA;
462 		if (bs->pathlen) {
463 			if ((bs->pathlen->type == V_ASN1_NEG_INTEGER) ||
464 			    !bs->ca) {
465 				x->ex_flags |= EXFLAG_INVALID;
466 				x->ex_pathlen = 0;
467 			} else
468 				x->ex_pathlen = ASN1_INTEGER_get(bs->pathlen);
469 		} else
470 			x->ex_pathlen = -1;
471 		BASIC_CONSTRAINTS_free(bs);
472 		x->ex_flags |= EXFLAG_BCONS;
473 	} else if (i != -1) {
474 		x->ex_flags |= EXFLAG_INVALID;
475 	}
476 
477 	/* Handle proxy certificates */
478 	if ((pci = X509_get_ext_d2i(x, NID_proxyCertInfo, &i, NULL))) {
479 		if (x->ex_flags & EXFLAG_CA ||
480 		    X509_get_ext_by_NID(x, NID_subject_alt_name, -1) >= 0 ||
481 		    X509_get_ext_by_NID(x, NID_issuer_alt_name, -1) >= 0) {
482 			x->ex_flags |= EXFLAG_INVALID;
483 		}
484 		if (pci->pcPathLengthConstraint) {
485 			if (pci->pcPathLengthConstraint->type ==
486 			    V_ASN1_NEG_INTEGER) {
487 				x->ex_flags |= EXFLAG_INVALID;
488 				x->ex_pcpathlen = 0;
489 			} else
490 				x->ex_pcpathlen =
491 				    ASN1_INTEGER_get(pci->
492 				      pcPathLengthConstraint);
493 		} else
494 			x->ex_pcpathlen = -1;
495 		PROXY_CERT_INFO_EXTENSION_free(pci);
496 		x->ex_flags |= EXFLAG_PROXY;
497 	} else if (i != -1) {
498 		x->ex_flags |= EXFLAG_INVALID;
499 	}
500 
501 	/* Handle key usage */
502 	if ((usage = X509_get_ext_d2i(x, NID_key_usage, &i, NULL))) {
503 		if (usage->length > 0) {
504 			x->ex_kusage = usage->data[0];
505 			if (usage->length > 1)
506 				x->ex_kusage |= usage->data[1] << 8;
507 		} else
508 			x->ex_kusage = 0;
509 		x->ex_flags |= EXFLAG_KUSAGE;
510 		ASN1_BIT_STRING_free(usage);
511 	} else if (i != -1) {
512 		x->ex_flags |= EXFLAG_INVALID;
513 	}
514 
515 	x->ex_xkusage = 0;
516 	if ((extusage = X509_get_ext_d2i(x, NID_ext_key_usage, &i, NULL))) {
517 		x->ex_flags |= EXFLAG_XKUSAGE;
518 		for (i = 0; i < sk_ASN1_OBJECT_num(extusage); i++) {
519 			switch (OBJ_obj2nid(sk_ASN1_OBJECT_value(extusage, i))) {
520 			case NID_server_auth:
521 				x->ex_xkusage |= XKU_SSL_SERVER;
522 				break;
523 
524 			case NID_client_auth:
525 				x->ex_xkusage |= XKU_SSL_CLIENT;
526 				break;
527 
528 			case NID_email_protect:
529 				x->ex_xkusage |= XKU_SMIME;
530 				break;
531 
532 			case NID_code_sign:
533 				x->ex_xkusage |= XKU_CODE_SIGN;
534 				break;
535 
536 			case NID_ms_sgc:
537 			case NID_ns_sgc:
538 				x->ex_xkusage |= XKU_SGC;
539 				break;
540 
541 			case NID_OCSP_sign:
542 				x->ex_xkusage |= XKU_OCSP_SIGN;
543 				break;
544 
545 			case NID_time_stamp:
546 				x->ex_xkusage |= XKU_TIMESTAMP;
547 				break;
548 
549 			case NID_dvcs:
550 				x->ex_xkusage |= XKU_DVCS;
551 				break;
552 			}
553 		}
554 		sk_ASN1_OBJECT_pop_free(extusage, ASN1_OBJECT_free);
555 	} else if (i != -1) {
556 		x->ex_flags |= EXFLAG_INVALID;
557 	}
558 
559 	if ((ns = X509_get_ext_d2i(x, NID_netscape_cert_type, &i, NULL))) {
560 		if (ns->length > 0)
561 			x->ex_nscert = ns->data[0];
562 		else
563 			x->ex_nscert = 0;
564 		x->ex_flags |= EXFLAG_NSCERT;
565 		ASN1_BIT_STRING_free(ns);
566 	} else if (i != -1) {
567 		x->ex_flags |= EXFLAG_INVALID;
568 	}
569 
570 	x->skid = X509_get_ext_d2i(x, NID_subject_key_identifier, &i, NULL);
571 	if (x->skid == NULL && i != -1)
572 		x->ex_flags |= EXFLAG_INVALID;
573 	x->akid = X509_get_ext_d2i(x, NID_authority_key_identifier, &i, NULL);
574 	if (x->akid == NULL && i != -1)
575 		x->ex_flags |= EXFLAG_INVALID;
576 
577 	/* Does subject name match issuer? */
578 	if (!X509_NAME_cmp(X509_get_subject_name(x), X509_get_issuer_name(x))) {
579 		x->ex_flags |= EXFLAG_SI;
580 		/* If SKID matches AKID also indicate self signed. */
581 		if (X509_check_akid(x, x->akid) == X509_V_OK &&
582 		    !ku_reject(x, KU_KEY_CERT_SIGN))
583 			x->ex_flags |= EXFLAG_SS;
584 	}
585 
586 	x->altname = X509_get_ext_d2i(x, NID_subject_alt_name, &i, NULL);
587 	if (x->altname == NULL && i != -1)
588 		x->ex_flags |= EXFLAG_INVALID;
589 	x->nc = X509_get_ext_d2i(x, NID_name_constraints, &i, NULL);
590 	if (!x->nc && (i != -1))
591 		x->ex_flags |= EXFLAG_INVALID;
592 	setup_crldp(x);
593 
594 	for (i = 0; i < X509_get_ext_count(x); i++) {
595 		ex = X509_get_ext(x, i);
596 		if (OBJ_obj2nid(X509_EXTENSION_get_object(ex)) ==
597 		    NID_freshest_crl)
598 			x->ex_flags |= EXFLAG_FRESHEST;
599 		if (!X509_EXTENSION_get_critical(ex))
600 			continue;
601 		if (!X509_supported_extension(ex)) {
602 			x->ex_flags |= EXFLAG_CRITICAL;
603 			break;
604 		}
605 	}
606 	x->ex_flags |= EXFLAG_SET;
607 }
608 
609 /* CA checks common to all purposes
610  * return codes:
611  * 0 not a CA
612  * 1 is a CA
613  * 2 basicConstraints absent so "maybe" a CA
614  * 3 basicConstraints absent but self signed V1.
615  * 4 basicConstraints absent but keyUsage present and keyCertSign asserted.
616  */
617 
618 static int
619 check_ca(const X509 *x)
620 {
621 	/* keyUsage if present should allow cert signing */
622 	if (ku_reject(x, KU_KEY_CERT_SIGN))
623 		return 0;
624 	if (x->ex_flags & EXFLAG_BCONS) {
625 		if (x->ex_flags & EXFLAG_CA)
626 			return 1;
627 		/* If basicConstraints says not a CA then say so */
628 		else
629 			return 0;
630 	} else {
631 		/* we support V1 roots for...  uh, I don't really know why. */
632 		if ((x->ex_flags & V1_ROOT) == V1_ROOT)
633 			return 3;
634 		/* If key usage present it must have certSign so tolerate it */
635 		else if (x->ex_flags & EXFLAG_KUSAGE)
636 			return 4;
637 		/* Older certificates could have Netscape-specific CA types */
638 		else if (x->ex_flags & EXFLAG_NSCERT &&
639 		    x->ex_nscert & NS_ANY_CA)
640 			return 5;
641 		/* can this still be regarded a CA certificate?  I doubt it */
642 		return 0;
643 	}
644 }
645 
646 int
647 X509_check_ca(X509 *x)
648 {
649 	if (!(x->ex_flags & EXFLAG_SET)) {
650 		CRYPTO_w_lock(CRYPTO_LOCK_X509);
651 		x509v3_cache_extensions(x);
652 		CRYPTO_w_unlock(CRYPTO_LOCK_X509);
653 		if (x->ex_flags & EXFLAG_INVALID)
654 			return X509_V_ERR_UNSPECIFIED;
655 	}
656 
657 	return check_ca(x);
658 }
659 
660 /* Check SSL CA: common checks for SSL client and server */
661 static int
662 check_ssl_ca(const X509 *x)
663 {
664 	int ca_ret;
665 
666 	ca_ret = check_ca(x);
667 	if (!ca_ret)
668 		return 0;
669 	/* check nsCertType if present */
670 	if (ca_ret != 5 || x->ex_nscert & NS_SSL_CA)
671 		return ca_ret;
672 	else
673 		return 0;
674 }
675 
676 static int
677 check_purpose_ssl_client(const X509_PURPOSE *xp, const X509 *x, int ca)
678 {
679 	if (xku_reject(x, XKU_SSL_CLIENT))
680 		return 0;
681 	if (ca)
682 		return check_ssl_ca(x);
683 	/* We need to do digital signatures with it */
684 	if (ku_reject(x, KU_DIGITAL_SIGNATURE))
685 		return 0;
686 	/* nsCertType if present should allow SSL client use */
687 	if (ns_reject(x, NS_SSL_CLIENT))
688 		return 0;
689 	return 1;
690 }
691 
692 static int
693 check_purpose_ssl_server(const X509_PURPOSE *xp, const X509 *x, int ca)
694 {
695 	if (xku_reject(x, XKU_SSL_SERVER|XKU_SGC))
696 		return 0;
697 	if (ca)
698 		return check_ssl_ca(x);
699 
700 	if (ns_reject(x, NS_SSL_SERVER))
701 		return 0;
702 	/* Now as for keyUsage: we'll at least need to sign OR encipher */
703 	if (ku_reject(x, KU_DIGITAL_SIGNATURE|KU_KEY_ENCIPHERMENT))
704 		return 0;
705 
706 	return 1;
707 }
708 
709 static int
710 check_purpose_ns_ssl_server(const X509_PURPOSE *xp, const X509 *x, int ca)
711 {
712 	int ret;
713 
714 	ret = check_purpose_ssl_server(xp, x, ca);
715 	if (!ret || ca)
716 		return ret;
717 	/* We need to encipher or Netscape complains */
718 	if (ku_reject(x, KU_KEY_ENCIPHERMENT))
719 		return 0;
720 	return ret;
721 }
722 
723 /* common S/MIME checks */
724 static int
725 purpose_smime(const X509 *x, int ca)
726 {
727 	if (xku_reject(x, XKU_SMIME))
728 		return 0;
729 	if (ca) {
730 		int ca_ret;
731 		ca_ret = check_ca(x);
732 		if (!ca_ret)
733 			return 0;
734 		/* check nsCertType if present */
735 		if (ca_ret != 5 || x->ex_nscert & NS_SMIME_CA)
736 			return ca_ret;
737 		else
738 			return 0;
739 	}
740 	if (x->ex_flags & EXFLAG_NSCERT) {
741 		if (x->ex_nscert & NS_SMIME)
742 			return 1;
743 		/* Workaround for some buggy certificates */
744 		if (x->ex_nscert & NS_SSL_CLIENT)
745 			return 2;
746 		return 0;
747 	}
748 	return 1;
749 }
750 
751 static int
752 check_purpose_smime_sign(const X509_PURPOSE *xp, const X509 *x, int ca)
753 {
754 	int ret;
755 
756 	ret = purpose_smime(x, ca);
757 	if (!ret || ca)
758 		return ret;
759 	if (ku_reject(x, KU_DIGITAL_SIGNATURE|KU_NON_REPUDIATION))
760 		return 0;
761 	return ret;
762 }
763 
764 static int
765 check_purpose_smime_encrypt(const X509_PURPOSE *xp, const X509 *x, int ca)
766 {
767 	int ret;
768 
769 	ret = purpose_smime(x, ca);
770 	if (!ret || ca)
771 		return ret;
772 	if (ku_reject(x, KU_KEY_ENCIPHERMENT))
773 		return 0;
774 	return ret;
775 }
776 
777 static int
778 check_purpose_crl_sign(const X509_PURPOSE *xp, const X509 *x, int ca)
779 {
780 	if (ca) {
781 		int ca_ret;
782 		if ((ca_ret = check_ca(x)) != 2)
783 			return ca_ret;
784 		else
785 			return 0;
786 	}
787 	if (ku_reject(x, KU_CRL_SIGN))
788 		return 0;
789 	return 1;
790 }
791 
792 /* OCSP helper: this is *not* a full OCSP check. It just checks that
793  * each CA is valid. Additional checks must be made on the chain.
794  */
795 static int
796 ocsp_helper(const X509_PURPOSE *xp, const X509 *x, int ca)
797 {
798 	/* Must be a valid CA.  Should we really support the "I don't know"
799 	   value (2)? */
800 	if (ca)
801 		return check_ca(x);
802 	/* leaf certificate is checked in OCSP_verify() */
803 	return 1;
804 }
805 
806 static int
807 check_purpose_timestamp_sign(const X509_PURPOSE *xp, const X509 *x, int ca)
808 {
809 	int i_ext;
810 
811 	/* If ca is true we must return if this is a valid CA certificate. */
812 	if (ca)
813 		return check_ca(x);
814 
815 	/*
816 	 * Check the optional key usage field:
817 	 * if Key Usage is present, it must be one of digitalSignature
818 	 * and/or nonRepudiation (other values are not consistent and shall
819 	 * be rejected).
820 	 */
821 	if ((x->ex_flags & EXFLAG_KUSAGE) &&
822 	    ((x->ex_kusage & ~(KU_NON_REPUDIATION | KU_DIGITAL_SIGNATURE)) ||
823 	    !(x->ex_kusage & (KU_NON_REPUDIATION | KU_DIGITAL_SIGNATURE))))
824 		return 0;
825 
826 	/* Only time stamp key usage is permitted and it's required. */
827 	if (!(x->ex_flags & EXFLAG_XKUSAGE) || x->ex_xkusage != XKU_TIMESTAMP)
828 		return 0;
829 
830 	/* Extended Key Usage MUST be critical */
831 	i_ext = X509_get_ext_by_NID((X509 *) x, NID_ext_key_usage, -1);
832 	if (i_ext >= 0) {
833 		X509_EXTENSION *ext = X509_get_ext((X509 *) x, i_ext);
834 		if (!X509_EXTENSION_get_critical(ext))
835 			return 0;
836 	}
837 
838 	return 1;
839 }
840 
841 static int
842 no_check(const X509_PURPOSE *xp, const X509 *x, int ca)
843 {
844 	return 1;
845 }
846 
847 /* Various checks to see if one certificate issued the second.
848  * This can be used to prune a set of possible issuer certificates
849  * which have been looked up using some simple method such as by
850  * subject name.
851  * These are:
852  * 1. Check issuer_name(subject) == subject_name(issuer)
853  * 2. If akid(subject) exists check it matches issuer
854  * 3. If key_usage(issuer) exists check it supports certificate signing
855  * returns 0 for OK, positive for reason for mismatch, reasons match
856  * codes for X509_verify_cert()
857  */
858 
859 int
860 X509_check_issued(X509 *issuer, X509 *subject)
861 {
862 	if (X509_NAME_cmp(X509_get_subject_name(issuer),
863 	    X509_get_issuer_name(subject)))
864 		return X509_V_ERR_SUBJECT_ISSUER_MISMATCH;
865 	x509v3_cache_extensions(issuer);
866 	if (issuer->ex_flags & EXFLAG_INVALID)
867 		return X509_V_ERR_UNSPECIFIED;
868 	x509v3_cache_extensions(subject);
869 	if (subject->ex_flags & EXFLAG_INVALID)
870 		return X509_V_ERR_UNSPECIFIED;
871 
872 	if (subject->akid) {
873 		int ret = X509_check_akid(issuer, subject->akid);
874 		if (ret != X509_V_OK)
875 			return ret;
876 	}
877 
878 	if (subject->ex_flags & EXFLAG_PROXY) {
879 		if (ku_reject(issuer, KU_DIGITAL_SIGNATURE))
880 			return X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE;
881 	} else if (ku_reject(issuer, KU_KEY_CERT_SIGN))
882 		return X509_V_ERR_KEYUSAGE_NO_CERTSIGN;
883 	return X509_V_OK;
884 }
885 
886 int
887 X509_check_akid(X509 *issuer, AUTHORITY_KEYID *akid)
888 {
889 	if (!akid)
890 		return X509_V_OK;
891 
892 	/* Check key ids (if present) */
893 	if (akid->keyid && issuer->skid &&
894 	    ASN1_OCTET_STRING_cmp(akid->keyid, issuer->skid) )
895 		return X509_V_ERR_AKID_SKID_MISMATCH;
896 	/* Check serial number */
897 	if (akid->serial &&
898 	    ASN1_INTEGER_cmp(X509_get_serialNumber(issuer), akid->serial))
899 		return X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH;
900 	/* Check issuer name */
901 	if (akid->issuer) {
902 		/* Ugh, for some peculiar reason AKID includes
903 		 * SEQUENCE OF GeneralName. So look for a DirName.
904 		 * There may be more than one but we only take any
905 		 * notice of the first.
906 		 */
907 		GENERAL_NAMES *gens;
908 		GENERAL_NAME *gen;
909 		X509_NAME *nm = NULL;
910 		int i;
911 		gens = akid->issuer;
912 		for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
913 			gen = sk_GENERAL_NAME_value(gens, i);
914 			if (gen->type == GEN_DIRNAME) {
915 				nm = gen->d.dirn;
916 				break;
917 			}
918 		}
919 		if (nm && X509_NAME_cmp(nm, X509_get_issuer_name(issuer)))
920 			return X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH;
921 	}
922 	return X509_V_OK;
923 }
924