xref: /openbsd-src/lib/libcrypto/x509/x509_constraints.c (revision 8e3291af1e0f6fd63cae7c1511b0d04f99b74692)
1 /* $OpenBSD: x509_constraints.c,v 1.27 2022/06/26 11:29:27 beck Exp $ */
2 /*
3  * Copyright (c) 2020 Bob Beck <beck@openbsd.org>
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17 
18 #include <ctype.h>
19 #include <errno.h>
20 #include <stdio.h>
21 #include <string.h>
22 #include <time.h>
23 #include <unistd.h>
24 
25 #include <sys/socket.h>
26 #include <arpa/inet.h>
27 
28 #include <openssl/safestack.h>
29 #include <openssl/x509.h>
30 #include <openssl/x509v3.h>
31 
32 #include "x509_internal.h"
33 
34 /* RFC 2821 section 4.5.3.1 */
35 #define LOCAL_PART_MAX_LEN 64
36 #define DOMAIN_PART_MAX_LEN 255
37 
38 struct x509_constraints_name *
39 x509_constraints_name_new(void)
40 {
41 	return (calloc(1, sizeof(struct x509_constraints_name)));
42 }
43 
44 void
45 x509_constraints_name_clear(struct x509_constraints_name *name)
46 {
47 	free(name->name);
48 	free(name->local);
49 	free(name->der);
50 	memset(name, 0, sizeof(*name));
51 }
52 
53 void
54 x509_constraints_name_free(struct x509_constraints_name *name)
55 {
56 	if (name == NULL)
57 		return;
58 	x509_constraints_name_clear(name);
59 	free(name);
60 }
61 
62 struct x509_constraints_name *
63 x509_constraints_name_dup(struct x509_constraints_name *name)
64 {
65 	struct x509_constraints_name *new;
66 
67 	if ((new = x509_constraints_name_new()) == NULL)
68 		goto err;
69 	new->type = name->type;
70 	new->af = name->af;
71 	new->der_len = name->der_len;
72 	if (name->der_len > 0) {
73 		if ((new->der = malloc(name->der_len)) == NULL)
74 			goto err;
75 		memcpy(new->der, name->der, name->der_len);
76 	}
77 	if (name->name != NULL && (new->name = strdup(name->name)) == NULL)
78 		goto err;
79 	if (name->local != NULL && (new->local = strdup(name->local)) == NULL)
80 		goto err;
81 	memcpy(new->address, name->address, sizeof(name->address));
82 	return new;
83  err:
84 	x509_constraints_name_free(new);
85 	return NULL;
86 }
87 
88 struct x509_constraints_names *
89 x509_constraints_names_new(size_t names_max)
90 {
91 	struct x509_constraints_names *new;
92 
93 	if ((new = calloc(1, sizeof(struct x509_constraints_names))) == NULL)
94 		return NULL;
95 
96 	new->names_max = names_max;
97 
98 	return new;
99 }
100 
101 void
102 x509_constraints_names_clear(struct x509_constraints_names *names)
103 {
104 	size_t i;
105 
106 	for (i = 0; i < names->names_count; i++)
107 		x509_constraints_name_free(names->names[i]);
108 	free(names->names);
109 	memset(names, 0, sizeof(*names));
110 }
111 
112 void
113 x509_constraints_names_free(struct x509_constraints_names *names)
114 {
115 	if (names == NULL)
116 		return;
117 
118 	x509_constraints_names_clear(names);
119 	free(names);
120 }
121 
122 int
123 x509_constraints_names_add(struct x509_constraints_names *names,
124     struct x509_constraints_name *name)
125 {
126 	if (names->names_count >= names->names_max)
127 		return 0;
128 	if (names->names_count == names->names_len) {
129 		struct x509_constraints_name **tmp;
130 		if ((tmp = recallocarray(names->names, names->names_len,
131 		    names->names_len + 32, sizeof(*tmp))) == NULL)
132 			return 0;
133 		names->names_len += 32;
134 		names->names = tmp;
135 	}
136 	names->names[names->names_count] = name;
137 	names->names_count++;
138 	return 1;
139 }
140 
141 struct x509_constraints_names *
142 x509_constraints_names_dup(struct x509_constraints_names *names)
143 {
144 	struct x509_constraints_names *new = NULL;
145 	struct x509_constraints_name *name = NULL;
146 	size_t i;
147 
148 	if (names == NULL)
149 		return NULL;
150 
151 	if ((new = x509_constraints_names_new(names->names_max)) == NULL)
152 		goto err;
153 
154 	for (i = 0; i < names->names_count; i++) {
155 		if ((name = x509_constraints_name_dup(names->names[i])) == NULL)
156 			goto err;
157 		if (!x509_constraints_names_add(new, name))
158 			goto err;
159 	}
160 
161 	return new;
162  err:
163 	x509_constraints_names_free(new);
164 	x509_constraints_name_free(name);
165 	return NULL;
166 }
167 
168 
169 /*
170  * Validate that the name contains only a hostname consisting of RFC
171  * 5890 compliant A-labels (see RFC 6066 section 3). This is more
172  * permissive to allow for a leading '.'  for a subdomain based
173  * constraint, as well as allowing for '_' which is commonly accepted
174  * by nonconformant DNS implementaitons.
175  *
176  * if "wildcards" is set it allows '*' to occur in the string at the end of a
177  * component.
178  */
179 static int
180 x509_constraints_valid_domain_internal(uint8_t *name, size_t len, int wildcards)
181 {
182 	uint8_t prev, c = 0;
183 	int component = 0;
184 	int first;
185 	size_t i;
186 
187 	if (len > DOMAIN_PART_MAX_LEN)
188 		return 0;
189 
190 	for (i = 0; i < len; i++) {
191 		prev = c;
192 		c = name[i];
193 
194 		first = (i == 0);
195 
196 		/* Everything has to be ASCII, with no NUL byte */
197 		if (!isascii(c) || c == '\0')
198 			return 0;
199 		/* It must be alphanumeric, a '-', '.', '_' or '*' */
200 		if (!isalnum(c) && c != '-' && c != '.' && c != '_' && c != '*')
201 			return 0;
202 
203 		/* if it is a '*', fail if not wildcards */
204 		if (!wildcards && c == '*')
205 			return 0;
206 
207 		/* '-' must not start a component or be at the end. */
208 		if (c == '-' && (component == 0 || i == len - 1))
209 			return 0;
210 
211 		/*
212 		 * '.' must not be at the end. It may be first overall
213 		 * but must not otherwise start a component.
214 		 */
215 		if (c == '.' && ((component == 0 && !first) || i == len - 1))
216 			return 0;
217 
218 		if (c == '.') {
219 			/* Components can not end with a dash. */
220 			if (prev == '-')
221 				return 0;
222 			/* Start new component */
223 			component = 0;
224 			continue;
225 		}
226 		/*
227 		 * Wildcards can only occur at the end of a component.
228 		 * c*.com is valid, c*c.com is not.
229 		 */
230 		if (prev == '*')
231 			return 0;
232 
233 		/* Components must be 63 chars or less. */
234 		if (++component > 63)
235 			return 0;
236 	}
237 	return 1;
238 }
239 
240 int
241 x509_constraints_valid_domain(uint8_t *name, size_t len)
242 {
243 	if (len == 0)
244 		return 0;
245 	/*
246 	 * A domain may not be less than two characters, so you can't
247 	 * have a require subdomain name with less than that.
248 	 */
249 	if (len < 3 && name[0] == '.')
250 		return 0;
251 	return x509_constraints_valid_domain_internal(name, len, 0);
252 }
253 
254 int
255 x509_constraints_valid_host(uint8_t *name, size_t len)
256 {
257 	struct sockaddr_in sin4;
258 	struct sockaddr_in6 sin6;
259 
260 	if (len == 0)
261 		return 0;
262 	if (name[0] == '.') /* leading . not allowed in a host name*/
263 		return 0;
264 	if (inet_pton(AF_INET, name, &sin4) == 1)
265 		return 0;
266 	if (inet_pton(AF_INET6, name, &sin6) == 1)
267 		return 0;
268 	return x509_constraints_valid_domain_internal(name, len, 0);
269 }
270 
271 int
272 x509_constraints_valid_sandns(uint8_t *name, size_t len)
273 {
274 	if (len == 0)
275 		return 0;
276 
277 	if (name[0] == '.') /* leading . not allowed in a SAN DNS name */
278 		return 0;
279 	/*
280 	 * A domain may not be less than two characters, so you
281 	 * can't wildcard a single domain of less than that
282 	 */
283 	if (len < 4 && name[0] == '*')
284 		return 0;
285 	/*
286 	 * A wildcard may only be followed by a '.'
287 	 */
288 	if (len >= 4 && name[0] == '*' && name[1] != '.')
289 		return 0;
290 
291 	return x509_constraints_valid_domain_internal(name, len, 1);
292 }
293 
294 static inline int
295 local_part_ok(char c)
296 {
297 	return (('0' <= c && c <= '9') || ('a' <= c && c <= 'z') ||
298 	    ('A' <= c && c <= 'Z') || c == '!' || c == '#' || c == '$' ||
299 	    c == '%' || c == '&' || c == '\'' || c == '*' || c == '+' ||
300 	    c == '-' || c == '/' || c == '=' || c == '?' ||  c == '^' ||
301 	    c == '_' || c == '`' || c == '{' || c == '|' || c == '}' ||
302 	    c == '~' || c == '.');
303 }
304 
305 /*
306  * Parse "candidate" as an RFC 2821 mailbox.
307  * Returns 0 if candidate is not a valid mailbox or if an error occurs.
308  * Returns 1 if candidate is a mailbox and adds newly allocated
309  * local and domain parts of the mailbox to "name->local" and name->name"
310  */
311 int
312 x509_constraints_parse_mailbox(uint8_t *candidate, size_t len,
313     struct x509_constraints_name *name)
314 {
315 	char working[DOMAIN_PART_MAX_LEN + 1] = { 0 };
316 	char *candidate_local = NULL;
317 	char *candidate_domain = NULL;
318 	size_t i, wi = 0;
319 	int accept = 0;
320 	int quoted = 0;
321 
322 	if (candidate == NULL)
323 		return 0;
324 
325 	/* It can't be bigger than the local part, domain part and the '@' */
326 	if (len > LOCAL_PART_MAX_LEN + DOMAIN_PART_MAX_LEN + 1)
327 		return 0;
328 
329 	for (i = 0; i < len; i++) {
330 		char c = candidate[i];
331 		/* non ascii, cr, lf, or nul is never allowed */
332 		if (!isascii(c) || c == '\r' || c == '\n' || c == '\0')
333 			goto bad;
334 		if (i == 0) {
335 			/* local part is quoted part */
336 			if (c == '"')
337 				quoted = 1;
338 			/* can not start with a . */
339 			if (c == '.')
340 				goto bad;
341 		}
342 		if (accept) {
343 			if (wi >= DOMAIN_PART_MAX_LEN)
344 				goto bad;
345 			working[wi++] = c;
346 			accept = 0;
347 			continue;
348 		}
349 		if (candidate_local != NULL) {
350 			/* We are looking for the domain part */
351 			if (wi >= DOMAIN_PART_MAX_LEN)
352 				goto bad;
353 			working[wi++] = c;
354 			if (i == len - 1) {
355 				if (wi == 0)
356 					goto bad;
357 				if (candidate_domain != NULL)
358 					goto bad;
359 				candidate_domain = strdup(working);
360 				if (candidate_domain == NULL)
361 					goto bad;
362 			}
363 			continue;
364 		}
365 		/* We are looking for the local part */
366 		if (wi >= LOCAL_PART_MAX_LEN)
367 			break;
368 
369 		if (quoted) {
370 			if (c == '\\') {
371 				accept = 1;
372 				continue;
373 			}
374 			if (c == '"' && i != 0) {
375 				/* end the quoted part. @ must be next */
376 				if (i + 1 == len || candidate[i + 1] != '@')
377 					goto bad;
378 				quoted = 0;
379 			}
380 			/*
381 			 * XXX Go strangely permits sp but forbids ht
382 			 * mimic that for now
383 			 */
384 			if (c == 9)
385 				goto bad;
386 			if (wi >= LOCAL_PART_MAX_LEN)
387 				goto bad;
388 			working[wi++] = c;
389 			continue; /* all's good inside our quoted string */
390 		}
391 		if (c == '@') {
392 			if (wi == 0)
393 				goto bad;
394 			if (candidate_local != NULL)
395 				goto bad;
396 			candidate_local = strdup(working);
397 			if (candidate_local == NULL)
398 				goto bad;
399 			memset(working, 0, sizeof(working));
400 			wi = 0;
401 			continue;
402 		}
403 		if (c == '\\') {
404 			/*
405 			 * RFC 3936 hints these can happen outside of
406 			 * quotend string. don't include the \ but
407 			 * next character must be ok.
408 			 */
409 			if (i + 1 == len)
410 				goto bad;
411 			if (!local_part_ok(candidate[i + 1]))
412 				goto bad;
413 			accept = 1;
414 		}
415 		if (!local_part_ok(c))
416 			goto bad;
417 		if (wi >= LOCAL_PART_MAX_LEN)
418 			goto bad;
419 		working[wi++] = c;
420 	}
421 	if (candidate_local == NULL || candidate_domain == NULL)
422 		goto bad;
423 	if (!x509_constraints_valid_host(candidate_domain,
424 	    strlen(candidate_domain)))
425 		goto bad;
426 
427 	if (name != NULL) {
428 		name->local = candidate_local;
429 		name->name = candidate_domain;
430 		name->type = GEN_EMAIL;
431 	} else {
432 		free(candidate_local);
433 		free(candidate_domain);
434 	}
435 	return 1;
436  bad:
437 	free(candidate_local);
438 	free(candidate_domain);
439 	return 0;
440 }
441 
442 int
443 x509_constraints_valid_domain_constraint(uint8_t *constraint, size_t len)
444 {
445 	if (len == 0)
446 		return 1;	/* empty constraints match */
447 
448 	/*
449 	 * A domain may not be less than two characters, so you
450 	 * can't match a single domain of less than that
451 	 */
452 	if (len < 3 && constraint[0] == '.')
453 		return 0;
454 	return x509_constraints_valid_domain_internal(constraint, len, 0);
455 }
456 
457 /*
458  * Extract the host part of a URI, returns the host part as a c string
459  * the caller must free, or or NULL if it could not be found or is
460  * invalid.
461  *
462  * RFC 3986:
463  * the authority part of a uri starts with // and is terminated with
464  * the next '/', '?', '#' or end of the URI.
465  *
466  * The authority itself contains [userinfo '@'] host [: port]
467  *
468  * so the host starts at the start or after the '@', and ends
469  * with end of URI, '/', '?', "#', or ':'.
470  */
471 int
472 x509_constraints_uri_host(uint8_t *uri, size_t len, char **hostpart)
473 {
474 	size_t i, hostlen = 0;
475 	uint8_t *authority = NULL;
476 	char *host = NULL;
477 
478 	/*
479 	 * Find first '//'. there must be at least a '//' and
480 	 * something else.
481 	 */
482 	if (len < 3)
483 		return 0;
484 	for (i = 0; i < len - 1; i++) {
485 		if (!isascii(uri[i]))
486 			return 0;
487 		if (uri[i] == '/' && uri[i + 1] == '/') {
488 			authority = uri + i + 2;
489 			break;
490 		}
491 	}
492 	if (authority == NULL) {
493 		/*
494 		 * There is no authority, so no host part in this
495 		 * URI. This might be ok or might not, but it must
496 		 * fail if we run into a name constraint later, so
497 		 * we indicate that we have a URI with an empty
498 		 * host part, and succeed.
499 		 */
500 		*hostpart = strdup("");
501 		return 1;
502 	}
503 	for (i = authority - uri; i < len; i++) {
504 		if (!isascii(uri[i]))
505 			return 0;
506 		/* it has a userinfo part */
507 		if (uri[i] == '@') {
508 			hostlen = 0;
509 			/* it can only have one */
510 			if (host != NULL)
511 				break;
512 			/* start after the userinfo part */
513 			host = uri + i + 1;
514 			continue;
515 		}
516 		/* did we find the end? */
517 		if (uri[i] == ':' || uri[i] == '/' || uri[i] == '?' ||
518 		    uri[i] == '#')
519 			break;
520 		hostlen++;
521 	}
522 	if (hostlen == 0)
523 		return 0;
524 	if (host == NULL)
525 		host = authority;
526 	if (!x509_constraints_valid_host(host, hostlen))
527 		return 0;
528 	if (hostpart != NULL)
529 		*hostpart = strndup(host, hostlen);
530 	return 1;
531 }
532 
533 int
534 x509_constraints_sandns(char *sandns, size_t dlen, char *constraint, size_t len)
535 {
536 	char *suffix;
537 
538 	if (len == 0)
539 		return 1; /* an empty constraint matches everything */
540 
541 	/* match the end of the domain */
542 	if (dlen < len)
543 		return 0;
544 	suffix = sandns + (dlen - len);
545 	return (strncasecmp(suffix, constraint, len) == 0);
546 }
547 
548 /*
549  * Validate a pre-validated domain of length dlen against a pre-validated
550  * constraint of length len.
551  *
552  * returns 1 if the domain and constraint match.
553  * returns 0 otherwise.
554  *
555  * an empty constraint matches everyting.
556  * constraint will be matched against the domain as a suffix if it
557  * starts with a '.'.
558  * domain will be matched against the constraint as a suffix if it
559  * starts with a '.'.
560  */
561 int
562 x509_constraints_domain(char *domain, size_t dlen, char *constraint, size_t len)
563 {
564 	if (len == 0)
565 		return 1; /* an empty constraint matches everything */
566 
567 	if (constraint[0] == '.') {
568 		/* match the end of the domain */
569 		char *suffix;
570 		if (dlen < len)
571 			return 0;
572 		suffix = domain + (dlen - len);
573 		return (strncasecmp(suffix, constraint, len) == 0);
574 	}
575 	if (domain[0] == '.') {
576 		/* match the end of the constraint */
577 		char *suffix;
578 		if (len < dlen)
579 			return 0;
580 		suffix = constraint + (len - dlen);
581 		return (strncasecmp(suffix, domain, dlen) == 0);
582 	}
583 	/* otherwise we must exactly match the constraint */
584 	if (dlen != len)
585 		return 0;
586 	return (strncasecmp(domain, constraint, len) == 0);
587 }
588 
589 int
590 x509_constraints_uri(uint8_t *uri, size_t ulen, uint8_t *constraint, size_t len,
591     int *error)
592 {
593 	int ret = 0;
594 	char *hostpart = NULL;
595 
596 	if (!x509_constraints_uri_host(uri, ulen, &hostpart)) {
597 		*error = X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
598 		goto err;
599 	}
600 	if (hostpart == NULL) {
601 		*error = X509_V_ERR_OUT_OF_MEM;
602 		goto err;
603 	}
604 	if (!x509_constraints_valid_domain_constraint(constraint, len)) {
605 		*error = X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX;
606 		goto err;
607 	}
608 	ret = x509_constraints_domain(hostpart, strlen(hostpart), constraint,
609 	    len);
610  err:
611 	free(hostpart);
612 	return ret;
613 }
614 
615 /*
616  * Verify a validated address of size alen with a validated contraint
617  * of size constraint_len. returns 1 if matching, 0 if not.
618  * Addresses are assumed to be pre-validated for a length of 4 and 8
619  * respectively for ipv4 addreses and constraints, and a length of
620  * 16 and 32 respectively for ipv6 address constraints by the caller.
621  */
622 int
623 x509_constraints_ipaddr(uint8_t *address, size_t alen, uint8_t *constraint,
624     size_t len)
625 {
626 	uint8_t *mask;
627 	size_t i;
628 
629 	if (alen * 2 != len)
630 		return 0;
631 
632 	mask = constraint + alen;
633 	for (i = 0; i < alen; i++) {
634 		if ((address[i] & mask[i]) != (constraint[i] & mask[i]))
635 			return 0;
636 	}
637 	return 1;
638 }
639 
640 /*
641  * Verify a canonicalized der encoded constraint dirname
642  * a canonicalized der encoded constraint.
643  */
644 int
645 x509_constraints_dirname(uint8_t *dirname, size_t dlen,
646     uint8_t *constraint, size_t len)
647 {
648 	/*
649 	 * The constraint must be a prefix in DER format, so it can't be
650 	 * longer than the name it is checked against.
651 	 */
652 	if (len > dlen)
653 		return 0;
654 	return (memcmp(constraint, dirname, len) == 0);
655 }
656 
657 /*
658  * De-obfuscate a GENERAL_NAME into useful bytes for a name or constraint.
659  */
660 int
661 x509_constraints_general_to_bytes(GENERAL_NAME *name, uint8_t **bytes,
662     size_t *len)
663 {
664 	*bytes = NULL;
665 	*len = 0;
666 
667 	if (name->type == GEN_DNS) {
668 		ASN1_IA5STRING *aname = name->d.dNSName;
669 
670 		*bytes = aname->data;
671 		*len = aname->length;
672 
673 		return name->type;
674 	}
675 	if (name->type == GEN_EMAIL) {
676 		ASN1_IA5STRING *aname = name->d.rfc822Name;
677 
678 		*bytes = aname->data;
679 		*len = aname->length;
680 
681 		return name->type;
682 	}
683 	if (name->type == GEN_URI) {
684 		ASN1_IA5STRING *aname = name->d.uniformResourceIdentifier;
685 
686 		*bytes = aname->data;
687 		*len = aname->length;
688 
689 		return name->type;
690 	}
691 	if (name->type == GEN_DIRNAME) {
692 		X509_NAME *dname = name->d.directoryName;
693 
694 		if (!dname->modified || i2d_X509_NAME(dname, NULL) >= 0) {
695 			*bytes = dname->canon_enc;
696 			*len = dname->canon_enclen;
697 
698 			return name->type;
699 		}
700 	}
701 	if (name->type == GEN_IPADD) {
702 		*bytes = name->d.ip->data;
703 		*len = name->d.ip->length;
704 
705 		return name->type;
706 	}
707 
708 	return 0;
709 }
710 
711 
712 /*
713  * Extract the relevant names for constraint checking from "cert",
714  * validate them, and add them to the list of cert names for "chain".
715  * returns 1 on success sets error and returns 0 on failure.
716  */
717 int
718 x509_constraints_extract_names(struct x509_constraints_names *names,
719     X509 *cert, int is_leaf, int *error)
720 {
721 	struct x509_constraints_name *vname = NULL;
722 	X509_NAME *subject_name;
723 	GENERAL_NAME *name;
724 	ssize_t i = 0;
725 	int name_type, include_cn = is_leaf, include_email = is_leaf;
726 
727 	/* first grab the altnames */
728 	while ((name = sk_GENERAL_NAME_value(cert->altname, i++)) != NULL) {
729 		uint8_t *bytes = NULL;
730 		size_t len = 0;
731 
732 		if ((vname = x509_constraints_name_new()) == NULL) {
733 			*error = X509_V_ERR_OUT_OF_MEM;
734 			goto err;
735 		}
736 
737 		name_type = x509_constraints_general_to_bytes(name, &bytes,
738 		    &len);
739 		switch(name_type) {
740 		case GEN_DNS:
741 			if (!x509_constraints_valid_sandns(bytes, len)) {
742 				*error = X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
743 				goto err;
744 			}
745 			if ((vname->name = strndup(bytes, len)) == NULL) {
746 				*error = X509_V_ERR_OUT_OF_MEM;
747 				goto err;
748 			}
749 			vname->type = GEN_DNS;
750 			include_cn = 0; /* don't use cn from subject */
751 			break;
752 		case GEN_EMAIL:
753 			if (!x509_constraints_parse_mailbox(bytes, len,
754 			    vname)) {
755 				*error = X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
756 				goto err;
757 			}
758 			vname->type = GEN_EMAIL;
759 			include_email = 0; /* don't use email from subject */
760 			break;
761 		case GEN_URI:
762 			if (!x509_constraints_uri_host(bytes, len, &vname->name)) {
763 				*error = X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
764 				goto err;
765 			}
766 			if (vname->name == NULL) {
767 				*error = X509_V_ERR_OUT_OF_MEM;
768 				goto err;
769 			}
770 			vname->type = GEN_URI;
771 			break;
772 		case GEN_DIRNAME:
773 			if (len == 0) {
774 				*error = X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
775 				goto err;
776 			}
777 			if (bytes == NULL || ((vname->der = malloc(len)) ==
778 			    NULL)) {
779 				*error = X509_V_ERR_OUT_OF_MEM;
780 				goto err;
781 			}
782 			memcpy(vname->der, bytes, len);
783 			vname->der_len = len;
784 			vname->type = GEN_DIRNAME;
785 			break;
786 		case GEN_IPADD:
787 			if (len == 4)
788 				vname->af = AF_INET;
789 			if (len == 16)
790 				vname->af = AF_INET6;
791 			if (vname->af != AF_INET && vname->af != AF_INET6) {
792 				*error = X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
793 				goto err;
794 			}
795 			memcpy(vname->address, bytes, len);
796 			vname->type = GEN_IPADD;
797 			break;
798 		default:
799 			/* Ignore this name */
800 			x509_constraints_name_free(vname);
801 			vname = NULL;
802 			continue;
803 		}
804 		if (!x509_constraints_names_add(names, vname)) {
805 			*error = X509_V_ERR_OUT_OF_MEM;
806 			goto err;
807 		}
808 		vname = NULL;
809 	}
810 
811 	x509_constraints_name_free(vname);
812 	vname = NULL;
813 
814 	subject_name = X509_get_subject_name(cert);
815 	if (X509_NAME_entry_count(subject_name) > 0) {
816 		X509_NAME_ENTRY *email;
817 		X509_NAME_ENTRY *cn;
818 		/*
819 		 * This cert has a non-empty subject, so we must add
820 		 * the subject as a dirname to be compared against
821 		 * any dirname constraints
822 		 */
823 		if ((subject_name->modified &&
824 		    i2d_X509_NAME(subject_name, NULL) < 0) ||
825 		    (vname = x509_constraints_name_new()) == NULL ||
826 		    (vname->der = malloc(subject_name->canon_enclen)) == NULL) {
827 			*error = X509_V_ERR_OUT_OF_MEM;
828 			goto err;
829 		}
830 
831 		memcpy(vname->der, subject_name->canon_enc,
832 		    subject_name->canon_enclen);
833 		vname->der_len = subject_name->canon_enclen;
834 		vname->type = GEN_DIRNAME;
835 		if (!x509_constraints_names_add(names, vname)) {
836 			*error = X509_V_ERR_OUT_OF_MEM;
837 			goto err;
838 		}
839 		vname = NULL;
840 		/*
841 		 * Get any email addresses from the subject line, and
842 		 * add them as mbox names to be compared against any
843 		 * email constraints
844 		 */
845 		while (include_email &&
846 		    (i = X509_NAME_get_index_by_NID(subject_name,
847 		    NID_pkcs9_emailAddress, i)) >= 0) {
848 			ASN1_STRING *aname;
849 			if ((email = X509_NAME_get_entry(subject_name, i)) == NULL ||
850 			    (aname = X509_NAME_ENTRY_get_data(email)) == NULL) {
851 				*error = X509_V_ERR_OUT_OF_MEM;
852 				goto err;
853 			}
854 			if ((vname = x509_constraints_name_new()) == NULL) {
855 				*error = X509_V_ERR_OUT_OF_MEM;
856 				goto err;
857 			}
858 			if (!x509_constraints_parse_mailbox(aname->data,
859 			    aname->length, vname)) {
860 				*error = X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
861 				goto err;
862 			}
863 			vname->type = GEN_EMAIL;
864 			if (!x509_constraints_names_add(names, vname)) {
865 				*error = X509_V_ERR_OUT_OF_MEM;
866 				goto err;
867 			}
868 			vname = NULL;
869 		}
870 		/*
871 		 * Include the CN as a hostname to be checked againt
872 		 * name constraints if it looks like a hostname.
873 		 */
874 		while (include_cn &&
875 		    (i = X509_NAME_get_index_by_NID(subject_name,
876 		    NID_commonName, i)) >= 0) {
877 			ASN1_STRING *aname;
878 			if ((cn = X509_NAME_get_entry(subject_name, i)) == NULL ||
879 			    (aname = X509_NAME_ENTRY_get_data(cn)) == NULL) {
880 				*error = X509_V_ERR_OUT_OF_MEM;
881 				goto err;
882 			}
883 			if (!x509_constraints_valid_host(aname->data,
884 			    aname->length))
885 				continue; /* ignore it if not a hostname */
886 			if ((vname = x509_constraints_name_new()) == NULL) {
887 				*error = X509_V_ERR_OUT_OF_MEM;
888 				goto err;
889 			}
890 			if ((vname->name = strndup(aname->data,
891 			    aname->length)) == NULL) {
892 				*error = X509_V_ERR_OUT_OF_MEM;
893 				goto err;
894 			}
895 			vname->type = GEN_DNS;
896 			if (!x509_constraints_names_add(names, vname)) {
897 				*error = X509_V_ERR_OUT_OF_MEM;
898 				goto err;
899 			}
900 			vname = NULL;
901 		}
902 	}
903 	return 1;
904  err:
905 	x509_constraints_name_free(vname);
906 	return 0;
907 }
908 
909 /*
910  * Validate a constraint in a general name, putting the relevant data
911  * into "name" if valid. returns 0, and sets error if the constraint is
912  * not valid. returns 1 if the constraint validated. name->type will be
913  * set to a valid type if there is constraint data in name, or unmodified
914  * if the GENERAL_NAME had a valid type but was ignored.
915  */
916 int
917 x509_constraints_validate(GENERAL_NAME *constraint,
918     struct x509_constraints_name **out_name, int *out_error)
919 {
920 	uint8_t *bytes = NULL;
921 	size_t len = 0;
922 	struct x509_constraints_name *name;
923 	int error = X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX;
924 	int name_type;
925 
926 	if (out_name == NULL || *out_name != NULL)
927 		return 0;
928 
929 	if (out_error != NULL)
930 		*out_error = 0;
931 
932 	if ((name = x509_constraints_name_new()) == NULL) {
933 		error = X509_V_ERR_OUT_OF_MEM;
934 		goto err;
935 	}
936 
937 	name_type = x509_constraints_general_to_bytes(constraint, &bytes, &len);
938 	switch (name_type) {
939 	case GEN_DIRNAME:
940 		if (len == 0)
941 			goto err; /* XXX The RFCs are delightfully vague */
942 		if (bytes == NULL || (name->der = malloc(len)) == NULL) {
943 			error = X509_V_ERR_OUT_OF_MEM;
944 			goto err;
945 		}
946 		memcpy(name->der, bytes, len);
947 		name->der_len = len;
948 		name->type = GEN_DIRNAME;
949 		break;
950 	case GEN_DNS:
951 		if (!x509_constraints_valid_domain_constraint(bytes, len))
952 			goto err;
953 		if ((name->name = strndup(bytes, len)) == NULL) {
954 			error = X509_V_ERR_OUT_OF_MEM;
955 			goto err;
956 		}
957 		name->type = GEN_DNS;
958 		break;
959 	case GEN_EMAIL:
960 		if (len > 0 && memchr(bytes + 1, '@', len - 1) != NULL) {
961 			if (!x509_constraints_parse_mailbox(bytes, len, name))
962 				goto err;
963 			break;
964 		}
965 		/*
966 		 * Mail constraints of the form @domain.com are accepted by
967 		 * OpenSSL and Microsoft.
968 		 */
969 		if (len > 0 && bytes[0] == '@') {
970 			bytes++;
971 			len--;
972 		}
973 		if (!x509_constraints_valid_domain_constraint(bytes, len))
974 			goto err;
975 		if ((name->name = strndup(bytes, len)) == NULL) {
976 			error = X509_V_ERR_OUT_OF_MEM;
977 			goto err;
978 		}
979 		name->type = GEN_EMAIL;
980 		break;
981 	case GEN_IPADD:
982 		/* Constraints are ip then mask */
983 		if (len == 8)
984 			name->af = AF_INET;
985 		else if (len == 32)
986 			name->af = AF_INET6;
987 		else
988 			goto err;
989 		memcpy(&name->address[0], bytes, len);
990 		name->type = GEN_IPADD;
991 		break;
992 	case GEN_URI:
993 		if (!x509_constraints_valid_domain_constraint(bytes, len))
994 			goto err;
995 		if ((name->name = strndup(bytes, len)) == NULL) {
996 			error = X509_V_ERR_OUT_OF_MEM;
997 			goto err;
998 		}
999 		name->type = GEN_URI;
1000 		break;
1001 	default:
1002 		break;
1003 	}
1004 
1005 	*out_name = name;
1006 
1007 	return 1;
1008 
1009  err:
1010 	x509_constraints_name_free(name);
1011 	if (out_error != NULL)
1012 		*out_error = error;
1013 
1014 	return 0;
1015 }
1016 
1017 int
1018 x509_constraints_extract_constraints(X509 *cert,
1019     struct x509_constraints_names *permitted,
1020     struct x509_constraints_names *excluded,
1021     int *error)
1022 {
1023 	struct x509_constraints_name *vname = NULL;
1024 	NAME_CONSTRAINTS *nc = cert->nc;
1025 	GENERAL_SUBTREE *subtree;
1026 	int i;
1027 
1028 	if (nc == NULL)
1029 		return 1;
1030 
1031 	for (i = 0; i < sk_GENERAL_SUBTREE_num(nc->permittedSubtrees); i++) {
1032 
1033 		subtree = sk_GENERAL_SUBTREE_value(nc->permittedSubtrees, i);
1034 		if (subtree->minimum || subtree->maximum) {
1035 			*error = X509_V_ERR_SUBTREE_MINMAX;
1036 			return 0;
1037 		}
1038 		if (!x509_constraints_validate(subtree->base, &vname, error))
1039 			return 0;
1040 		if (vname->type == 0) {
1041 			x509_constraints_name_free(vname);
1042 			vname = NULL;
1043 			continue;
1044 		}
1045 		if (!x509_constraints_names_add(permitted, vname)) {
1046 			x509_constraints_name_free(vname);
1047 			vname = NULL;
1048 			*error = X509_V_ERR_OUT_OF_MEM;
1049 			return 0;
1050 		}
1051 		vname = NULL;
1052 	}
1053 
1054 	for (i = 0; i < sk_GENERAL_SUBTREE_num(nc->excludedSubtrees); i++) {
1055 		subtree = sk_GENERAL_SUBTREE_value(nc->excludedSubtrees, i);
1056 		if (subtree->minimum || subtree->maximum) {
1057 			*error = X509_V_ERR_SUBTREE_MINMAX;
1058 			return 0;
1059 		}
1060 		if (!x509_constraints_validate(subtree->base, &vname, error))
1061 			return 0;
1062 		if (vname->type == 0) {
1063 			x509_constraints_name_free(vname);
1064 			vname = NULL;
1065 			continue;
1066 		}
1067 		if (!x509_constraints_names_add(excluded, vname)) {
1068 			x509_constraints_name_free(vname);
1069 			vname = NULL;
1070 			*error = X509_V_ERR_OUT_OF_MEM;
1071 			return 0;
1072 		}
1073 		vname = NULL;
1074 	}
1075 
1076 	return 1;
1077 }
1078 
1079 /*
1080  * Match a validated name in "name" against a validated constraint in
1081  * "constraint" return 1 if then name matches, 0 otherwise.
1082  */
1083 int
1084 x509_constraints_match(struct x509_constraints_name *name,
1085     struct x509_constraints_name *constraint)
1086 {
1087 	if (name->type != constraint->type)
1088 		return 0;
1089 	if (name->type == GEN_DNS)
1090 		return x509_constraints_sandns(name->name, strlen(name->name),
1091 		    constraint->name, strlen(constraint->name));
1092 	if (name->type == GEN_URI)
1093 		return x509_constraints_domain(name->name, strlen(name->name),
1094 		    constraint->name, strlen(constraint->name));
1095 	if (name->type == GEN_IPADD) {
1096 		size_t nlen = name->af == AF_INET ? 4 : 16;
1097 		size_t clen = name->af == AF_INET ? 8 : 32;
1098 		if (name->af != AF_INET && name->af != AF_INET6)
1099 			return 0;
1100 		if (constraint->af != AF_INET && constraint->af != AF_INET6)
1101 			return 0;
1102 		if (name->af != constraint->af)
1103 			return 0;
1104 		return x509_constraints_ipaddr(name->address, nlen,
1105 		    constraint->address, clen);
1106 	}
1107 	if (name->type == GEN_EMAIL) {
1108 		if (constraint->local) {
1109 			/* mailbox local and domain parts must exactly match */
1110 			return (strcmp(name->local, constraint->local) == 0 &&
1111 			    strcmp(name->name, constraint->name) == 0);
1112 		}
1113 		/* otherwise match the constraint to the domain part */
1114 		return x509_constraints_domain(name->name, strlen(name->name),
1115 		    constraint->name, strlen(constraint->name));
1116 	}
1117 	if (name->type == GEN_DIRNAME)
1118 		return x509_constraints_dirname(name->der, name->der_len,
1119 		    constraint->der, constraint->der_len);
1120 	return 0;
1121 }
1122 
1123 /*
1124  * Make sure every name in names does not match any excluded
1125  * constraints, and does match at least one permitted constraint if
1126  * any are present. Returns 1 if ok, 0, and sets error if not.
1127  */
1128 int
1129 x509_constraints_check(struct x509_constraints_names *names,
1130     struct x509_constraints_names *permitted,
1131     struct x509_constraints_names *excluded, int *error)
1132 {
1133 	size_t i, j;
1134 
1135 	for (i = 0; i < names->names_count; i++) {
1136 		int permitted_seen = 0;
1137 		int permitted_matched = 0;
1138 
1139 		for (j = 0; j < excluded->names_count; j++) {
1140 			if (x509_constraints_match(names->names[i],
1141 			    excluded->names[j])) {
1142 				*error = X509_V_ERR_EXCLUDED_VIOLATION;
1143 				return 0;
1144 			}
1145 		}
1146 		for (j = 0; j < permitted->names_count; j++) {
1147 			if (permitted->names[j]->type == names->names[i]->type)
1148 				permitted_seen++;
1149 			if (x509_constraints_match(names->names[i],
1150 			    permitted->names[j])) {
1151 				permitted_matched++;
1152 				break;
1153 			}
1154 		}
1155 		if (permitted_seen && !permitted_matched) {
1156 			*error = X509_V_ERR_PERMITTED_VIOLATION;
1157 			return 0;
1158 		}
1159 	}
1160 	return 1;
1161 }
1162 
1163 /*
1164  * Walk a validated chain of X509 certs, starting at the leaf, and
1165  * validate the name constraints in the chain. Intended for use with
1166  * the legacy X509 validtion code in x509_vfy.c
1167  *
1168  * returns 1 if the constraints are ok, 0 otherwise, setting error and
1169  * depth
1170  */
1171 int
1172 x509_constraints_chain(STACK_OF(X509) *chain, int *error, int *depth)
1173 {
1174 	int chain_length, verify_err = X509_V_ERR_UNSPECIFIED, i = 0;
1175 	struct x509_constraints_names *names = NULL;
1176 	struct x509_constraints_names *excluded = NULL;
1177 	struct x509_constraints_names *permitted = NULL;
1178 	size_t constraints_count = 0;
1179 	X509 *cert;
1180 
1181 	if (chain == NULL || (chain_length = sk_X509_num(chain)) == 0)
1182 		goto err;
1183 	if (chain_length == 1)
1184 		return 1;
1185 	if ((names = x509_constraints_names_new(
1186 	    X509_VERIFY_MAX_CHAIN_NAMES)) == NULL) {
1187 		verify_err = X509_V_ERR_OUT_OF_MEM;
1188 		goto err;
1189 	}
1190 
1191 	if ((cert = sk_X509_value(chain, 0)) == NULL)
1192 		goto err;
1193 	if (!x509_constraints_extract_names(names, cert, 1, &verify_err))
1194 		goto err;
1195 	for (i = 1; i < chain_length; i++) {
1196 		if ((cert = sk_X509_value(chain, i)) == NULL)
1197 			goto err;
1198 		if (cert->nc != NULL) {
1199 			if ((permitted = x509_constraints_names_new(
1200 			    X509_VERIFY_MAX_CHAIN_CONSTRAINTS)) == NULL) {
1201 				verify_err = X509_V_ERR_OUT_OF_MEM;
1202 				goto err;
1203 			}
1204 			if ((excluded = x509_constraints_names_new(
1205 			    X509_VERIFY_MAX_CHAIN_CONSTRAINTS)) == NULL) {
1206 				verify_err = X509_V_ERR_OUT_OF_MEM;
1207 				goto err;
1208 			}
1209 			if (!x509_constraints_extract_constraints(cert,
1210 			    permitted, excluded, &verify_err))
1211 				goto err;
1212 			constraints_count += permitted->names_count;
1213 			constraints_count += excluded->names_count;
1214 			if (constraints_count >
1215 			    X509_VERIFY_MAX_CHAIN_CONSTRAINTS) {
1216 				verify_err = X509_V_ERR_OUT_OF_MEM;
1217 				goto err;
1218 			}
1219 			if (!x509_constraints_check(names, permitted, excluded,
1220 			    &verify_err))
1221 				goto err;
1222 			x509_constraints_names_free(excluded);
1223 			excluded = NULL;
1224 			x509_constraints_names_free(permitted);
1225 			permitted = NULL;
1226 		}
1227 		if (!x509_constraints_extract_names(names, cert, 0,
1228 		    &verify_err))
1229 			goto err;
1230 	}
1231 
1232 	x509_constraints_names_free(names);
1233 	return 1;
1234 
1235  err:
1236 	*error = verify_err;
1237 	*depth = i;
1238 	x509_constraints_names_free(excluded);
1239 	x509_constraints_names_free(permitted);
1240 	x509_constraints_names_free(names);
1241 	return 0;
1242 }
1243