xref: /openbsd-src/lib/libcrypto/x509/x509_constraints.c (revision 42ac1f71ddfc8f2b1ea1555399aa1e1ffc2faced)
1 /* $OpenBSD: x509_constraints.c,v 1.26 2022/03/26 16:34:21 tb 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 		return 0;
494 	for (i = authority - uri; i < len; i++) {
495 		if (!isascii(uri[i]))
496 			return 0;
497 		/* it has a userinfo part */
498 		if (uri[i] == '@') {
499 			hostlen = 0;
500 			/* it can only have one */
501 			if (host != NULL)
502 				break;
503 			/* start after the userinfo part */
504 			host = uri + i + 1;
505 			continue;
506 		}
507 		/* did we find the end? */
508 		if (uri[i] == ':' || uri[i] == '/' || uri[i] == '?' ||
509 		    uri[i] == '#')
510 			break;
511 		hostlen++;
512 	}
513 	if (hostlen == 0)
514 		return 0;
515 	if (host == NULL)
516 		host = authority;
517 	if (!x509_constraints_valid_host(host, hostlen))
518 		return 0;
519 	if (hostpart != NULL)
520 		*hostpart = strndup(host, hostlen);
521 	return 1;
522 }
523 
524 int
525 x509_constraints_sandns(char *sandns, size_t dlen, char *constraint, size_t len)
526 {
527 	char *suffix;
528 
529 	if (len == 0)
530 		return 1; /* an empty constraint matches everything */
531 
532 	/* match the end of the domain */
533 	if (dlen < len)
534 		return 0;
535 	suffix = sandns + (dlen - len);
536 	return (strncasecmp(suffix, constraint, len) == 0);
537 }
538 
539 /*
540  * Validate a pre-validated domain of length dlen against a pre-validated
541  * constraint of length len.
542  *
543  * returns 1 if the domain and constraint match.
544  * returns 0 otherwise.
545  *
546  * an empty constraint matches everyting.
547  * constraint will be matched against the domain as a suffix if it
548  * starts with a '.'.
549  * domain will be matched against the constraint as a suffix if it
550  * starts with a '.'.
551  */
552 int
553 x509_constraints_domain(char *domain, size_t dlen, char *constraint, size_t len)
554 {
555 	if (len == 0)
556 		return 1; /* an empty constraint matches everything */
557 
558 	if (constraint[0] == '.') {
559 		/* match the end of the domain */
560 		char *suffix;
561 		if (dlen < len)
562 			return 0;
563 		suffix = domain + (dlen - len);
564 		return (strncasecmp(suffix, constraint, len) == 0);
565 	}
566 	if (domain[0] == '.') {
567 		/* match the end of the constraint */
568 		char *suffix;
569 		if (len < dlen)
570 			return 0;
571 		suffix = constraint + (len - dlen);
572 		return (strncasecmp(suffix, domain, dlen) == 0);
573 	}
574 	/* otherwise we must exactly match the constraint */
575 	if (dlen != len)
576 		return 0;
577 	return (strncasecmp(domain, constraint, len) == 0);
578 }
579 
580 int
581 x509_constraints_uri(uint8_t *uri, size_t ulen, uint8_t *constraint, size_t len,
582     int *error)
583 {
584 	int ret = 0;
585 	char *hostpart = NULL;
586 
587 	if (!x509_constraints_uri_host(uri, ulen, &hostpart)) {
588 		*error = X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
589 		goto err;
590 	}
591 	if (hostpart == NULL) {
592 		*error = X509_V_ERR_OUT_OF_MEM;
593 		goto err;
594 	}
595 	if (!x509_constraints_valid_domain_constraint(constraint, len)) {
596 		*error = X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX;
597 		goto err;
598 	}
599 	ret = x509_constraints_domain(hostpart, strlen(hostpart), constraint,
600 	    len);
601  err:
602 	free(hostpart);
603 	return ret;
604 }
605 
606 /*
607  * Verify a validated address of size alen with a validated contraint
608  * of size constraint_len. returns 1 if matching, 0 if not.
609  * Addresses are assumed to be pre-validated for a length of 4 and 8
610  * respectively for ipv4 addreses and constraints, and a length of
611  * 16 and 32 respectively for ipv6 address constraints by the caller.
612  */
613 int
614 x509_constraints_ipaddr(uint8_t *address, size_t alen, uint8_t *constraint,
615     size_t len)
616 {
617 	uint8_t *mask;
618 	size_t i;
619 
620 	if (alen * 2 != len)
621 		return 0;
622 
623 	mask = constraint + alen;
624 	for (i = 0; i < alen; i++) {
625 		if ((address[i] & mask[i]) != (constraint[i] & mask[i]))
626 			return 0;
627 	}
628 	return 1;
629 }
630 
631 /*
632  * Verify a canonicalized der encoded constraint dirname
633  * a canonicalized der encoded constraint.
634  */
635 int
636 x509_constraints_dirname(uint8_t *dirname, size_t dlen,
637     uint8_t *constraint, size_t len)
638 {
639 	/*
640 	 * The constraint must be a prefix in DER format, so it can't be
641 	 * longer than the name it is checked against.
642 	 */
643 	if (len > dlen)
644 		return 0;
645 	return (memcmp(constraint, dirname, len) == 0);
646 }
647 
648 /*
649  * De-obfuscate a GENERAL_NAME into useful bytes for a name or constraint.
650  */
651 int
652 x509_constraints_general_to_bytes(GENERAL_NAME *name, uint8_t **bytes,
653     size_t *len)
654 {
655 	*bytes = NULL;
656 	*len = 0;
657 
658 	if (name->type == GEN_DNS) {
659 		ASN1_IA5STRING *aname = name->d.dNSName;
660 
661 		*bytes = aname->data;
662 		*len = aname->length;
663 
664 		return name->type;
665 	}
666 	if (name->type == GEN_EMAIL) {
667 		ASN1_IA5STRING *aname = name->d.rfc822Name;
668 
669 		*bytes = aname->data;
670 		*len = aname->length;
671 
672 		return name->type;
673 	}
674 	if (name->type == GEN_URI) {
675 		ASN1_IA5STRING *aname = name->d.uniformResourceIdentifier;
676 
677 		*bytes = aname->data;
678 		*len = aname->length;
679 
680 		return name->type;
681 	}
682 	if (name->type == GEN_DIRNAME) {
683 		X509_NAME *dname = name->d.directoryName;
684 
685 		if (!dname->modified || i2d_X509_NAME(dname, NULL) >= 0) {
686 			*bytes = dname->canon_enc;
687 			*len = dname->canon_enclen;
688 
689 			return name->type;
690 		}
691 	}
692 	if (name->type == GEN_IPADD) {
693 		*bytes = name->d.ip->data;
694 		*len = name->d.ip->length;
695 
696 		return name->type;
697 	}
698 
699 	return 0;
700 }
701 
702 
703 /*
704  * Extract the relevant names for constraint checking from "cert",
705  * validate them, and add them to the list of cert names for "chain".
706  * returns 1 on success sets error and returns 0 on failure.
707  */
708 int
709 x509_constraints_extract_names(struct x509_constraints_names *names,
710     X509 *cert, int is_leaf, int *error)
711 {
712 	struct x509_constraints_name *vname = NULL;
713 	X509_NAME *subject_name;
714 	GENERAL_NAME *name;
715 	ssize_t i = 0;
716 	int name_type, include_cn = is_leaf, include_email = is_leaf;
717 
718 	/* first grab the altnames */
719 	while ((name = sk_GENERAL_NAME_value(cert->altname, i++)) != NULL) {
720 		uint8_t *bytes = NULL;
721 		size_t len = 0;
722 
723 		if ((vname = x509_constraints_name_new()) == NULL) {
724 			*error = X509_V_ERR_OUT_OF_MEM;
725 			goto err;
726 		}
727 
728 		name_type = x509_constraints_general_to_bytes(name, &bytes,
729 		    &len);
730 		switch(name_type) {
731 		case GEN_DNS:
732 			if (!x509_constraints_valid_sandns(bytes, len)) {
733 				*error = X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
734 				goto err;
735 			}
736 			if ((vname->name = strndup(bytes, len)) == NULL) {
737 				*error = X509_V_ERR_OUT_OF_MEM;
738 				goto err;
739 			}
740 			vname->type = GEN_DNS;
741 			include_cn = 0; /* don't use cn from subject */
742 			break;
743 		case GEN_EMAIL:
744 			if (!x509_constraints_parse_mailbox(bytes, len,
745 			    vname)) {
746 				*error = X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
747 				goto err;
748 			}
749 			vname->type = GEN_EMAIL;
750 			include_email = 0; /* don't use email from subject */
751 			break;
752 		case GEN_URI:
753 			if (!x509_constraints_uri_host(bytes, len, &vname->name)) {
754 				*error = X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
755 				goto err;
756 			}
757 			if (vname->name == NULL) {
758 				*error = X509_V_ERR_OUT_OF_MEM;
759 				goto err;
760 			}
761 			vname->type = GEN_URI;
762 			break;
763 		case GEN_DIRNAME:
764 			if (len == 0) {
765 				*error = X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
766 				goto err;
767 			}
768 			if (bytes == NULL || ((vname->der = malloc(len)) ==
769 			    NULL)) {
770 				*error = X509_V_ERR_OUT_OF_MEM;
771 				goto err;
772 			}
773 			memcpy(vname->der, bytes, len);
774 			vname->der_len = len;
775 			vname->type = GEN_DIRNAME;
776 			break;
777 		case GEN_IPADD:
778 			if (len == 4)
779 				vname->af = AF_INET;
780 			if (len == 16)
781 				vname->af = AF_INET6;
782 			if (vname->af != AF_INET && vname->af != AF_INET6) {
783 				*error = X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
784 				goto err;
785 			}
786 			memcpy(vname->address, bytes, len);
787 			vname->type = GEN_IPADD;
788 			break;
789 		default:
790 			/* Ignore this name */
791 			x509_constraints_name_free(vname);
792 			vname = NULL;
793 			continue;
794 		}
795 		if (!x509_constraints_names_add(names, vname)) {
796 			*error = X509_V_ERR_OUT_OF_MEM;
797 			goto err;
798 		}
799 		vname = NULL;
800 	}
801 
802 	x509_constraints_name_free(vname);
803 	vname = NULL;
804 
805 	subject_name = X509_get_subject_name(cert);
806 	if (X509_NAME_entry_count(subject_name) > 0) {
807 		X509_NAME_ENTRY *email;
808 		X509_NAME_ENTRY *cn;
809 		/*
810 		 * This cert has a non-empty subject, so we must add
811 		 * the subject as a dirname to be compared against
812 		 * any dirname constraints
813 		 */
814 		if ((subject_name->modified &&
815 		    i2d_X509_NAME(subject_name, NULL) < 0) ||
816 		    (vname = x509_constraints_name_new()) == NULL ||
817 		    (vname->der = malloc(subject_name->canon_enclen)) == NULL) {
818 			*error = X509_V_ERR_OUT_OF_MEM;
819 			goto err;
820 		}
821 
822 		memcpy(vname->der, subject_name->canon_enc,
823 		    subject_name->canon_enclen);
824 		vname->der_len = subject_name->canon_enclen;
825 		vname->type = GEN_DIRNAME;
826 		if (!x509_constraints_names_add(names, vname)) {
827 			*error = X509_V_ERR_OUT_OF_MEM;
828 			goto err;
829 		}
830 		vname = NULL;
831 		/*
832 		 * Get any email addresses from the subject line, and
833 		 * add them as mbox names to be compared against any
834 		 * email constraints
835 		 */
836 		while (include_email &&
837 		    (i = X509_NAME_get_index_by_NID(subject_name,
838 		    NID_pkcs9_emailAddress, i)) >= 0) {
839 			ASN1_STRING *aname;
840 			if ((email = X509_NAME_get_entry(subject_name, i)) == NULL ||
841 			    (aname = X509_NAME_ENTRY_get_data(email)) == NULL) {
842 				*error = X509_V_ERR_OUT_OF_MEM;
843 				goto err;
844 			}
845 			if ((vname = x509_constraints_name_new()) == NULL) {
846 				*error = X509_V_ERR_OUT_OF_MEM;
847 				goto err;
848 			}
849 			if (!x509_constraints_parse_mailbox(aname->data,
850 			    aname->length, vname)) {
851 				*error = X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
852 				goto err;
853 			}
854 			vname->type = GEN_EMAIL;
855 			if (!x509_constraints_names_add(names, vname)) {
856 				*error = X509_V_ERR_OUT_OF_MEM;
857 				goto err;
858 			}
859 			vname = NULL;
860 		}
861 		/*
862 		 * Include the CN as a hostname to be checked againt
863 		 * name constraints if it looks like a hostname.
864 		 */
865 		while (include_cn &&
866 		    (i = X509_NAME_get_index_by_NID(subject_name,
867 		    NID_commonName, i)) >= 0) {
868 			ASN1_STRING *aname;
869 			if ((cn = X509_NAME_get_entry(subject_name, i)) == NULL ||
870 			    (aname = X509_NAME_ENTRY_get_data(cn)) == NULL) {
871 				*error = X509_V_ERR_OUT_OF_MEM;
872 				goto err;
873 			}
874 			if (!x509_constraints_valid_host(aname->data,
875 			    aname->length))
876 				continue; /* ignore it if not a hostname */
877 			if ((vname = x509_constraints_name_new()) == NULL) {
878 				*error = X509_V_ERR_OUT_OF_MEM;
879 				goto err;
880 			}
881 			if ((vname->name = strndup(aname->data,
882 			    aname->length)) == NULL) {
883 				*error = X509_V_ERR_OUT_OF_MEM;
884 				goto err;
885 			}
886 			vname->type = GEN_DNS;
887 			if (!x509_constraints_names_add(names, vname)) {
888 				*error = X509_V_ERR_OUT_OF_MEM;
889 				goto err;
890 			}
891 			vname = NULL;
892 		}
893 	}
894 	return 1;
895  err:
896 	x509_constraints_name_free(vname);
897 	return 0;
898 }
899 
900 /*
901  * Validate a constraint in a general name, putting the relevant data
902  * into "name" if valid. returns 0, and sets error if the constraint is
903  * not valid. returns 1 if the constraint validated. name->type will be
904  * set to a valid type if there is constraint data in name, or unmodified
905  * if the GENERAL_NAME had a valid type but was ignored.
906  */
907 int
908 x509_constraints_validate(GENERAL_NAME *constraint,
909     struct x509_constraints_name **out_name, int *out_error)
910 {
911 	uint8_t *bytes = NULL;
912 	size_t len = 0;
913 	struct x509_constraints_name *name;
914 	int error = X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX;
915 	int name_type;
916 
917 	if (out_name == NULL || *out_name != NULL)
918 		return 0;
919 
920 	if (out_error != NULL)
921 		*out_error = 0;
922 
923 	if ((name = x509_constraints_name_new()) == NULL) {
924 		error = X509_V_ERR_OUT_OF_MEM;
925 		goto err;
926 	}
927 
928 	name_type = x509_constraints_general_to_bytes(constraint, &bytes, &len);
929 	switch (name_type) {
930 	case GEN_DIRNAME:
931 		if (len == 0)
932 			goto err; /* XXX The RFCs are delightfully vague */
933 		if (bytes == NULL || (name->der = malloc(len)) == NULL) {
934 			error = X509_V_ERR_OUT_OF_MEM;
935 			goto err;
936 		}
937 		memcpy(name->der, bytes, len);
938 		name->der_len = len;
939 		name->type = GEN_DIRNAME;
940 		break;
941 	case GEN_DNS:
942 		if (!x509_constraints_valid_domain_constraint(bytes, len))
943 			goto err;
944 		if ((name->name = strndup(bytes, len)) == NULL) {
945 			error = X509_V_ERR_OUT_OF_MEM;
946 			goto err;
947 		}
948 		name->type = GEN_DNS;
949 		break;
950 	case GEN_EMAIL:
951 		if (len > 0 && memchr(bytes + 1, '@', len - 1) != NULL) {
952 			if (!x509_constraints_parse_mailbox(bytes, len, name))
953 				goto err;
954 			break;
955 		}
956 		/*
957 		 * Mail constraints of the form @domain.com are accepted by
958 		 * OpenSSL and Microsoft.
959 		 */
960 		if (len > 0 && bytes[0] == '@') {
961 			bytes++;
962 			len--;
963 		}
964 		if (!x509_constraints_valid_domain_constraint(bytes, len))
965 			goto err;
966 		if ((name->name = strndup(bytes, len)) == NULL) {
967 			error = X509_V_ERR_OUT_OF_MEM;
968 			goto err;
969 		}
970 		name->type = GEN_EMAIL;
971 		break;
972 	case GEN_IPADD:
973 		/* Constraints are ip then mask */
974 		if (len == 8)
975 			name->af = AF_INET;
976 		else if (len == 32)
977 			name->af = AF_INET6;
978 		else
979 			goto err;
980 		memcpy(&name->address[0], bytes, len);
981 		name->type = GEN_IPADD;
982 		break;
983 	case GEN_URI:
984 		if (!x509_constraints_valid_domain_constraint(bytes, len))
985 			goto err;
986 		if ((name->name = strndup(bytes, len)) == NULL) {
987 			error = X509_V_ERR_OUT_OF_MEM;
988 			goto err;
989 		}
990 		name->type = GEN_URI;
991 		break;
992 	default:
993 		break;
994 	}
995 
996 	*out_name = name;
997 
998 	return 1;
999 
1000  err:
1001 	x509_constraints_name_free(name);
1002 	if (out_error != NULL)
1003 		*out_error = error;
1004 
1005 	return 0;
1006 }
1007 
1008 int
1009 x509_constraints_extract_constraints(X509 *cert,
1010     struct x509_constraints_names *permitted,
1011     struct x509_constraints_names *excluded,
1012     int *error)
1013 {
1014 	struct x509_constraints_name *vname = NULL;
1015 	NAME_CONSTRAINTS *nc = cert->nc;
1016 	GENERAL_SUBTREE *subtree;
1017 	int i;
1018 
1019 	if (nc == NULL)
1020 		return 1;
1021 
1022 	for (i = 0; i < sk_GENERAL_SUBTREE_num(nc->permittedSubtrees); i++) {
1023 
1024 		subtree = sk_GENERAL_SUBTREE_value(nc->permittedSubtrees, i);
1025 		if (subtree->minimum || subtree->maximum) {
1026 			*error = X509_V_ERR_SUBTREE_MINMAX;
1027 			return 0;
1028 		}
1029 		if (!x509_constraints_validate(subtree->base, &vname, error))
1030 			return 0;
1031 		if (vname->type == 0) {
1032 			x509_constraints_name_free(vname);
1033 			vname = NULL;
1034 			continue;
1035 		}
1036 		if (!x509_constraints_names_add(permitted, vname)) {
1037 			x509_constraints_name_free(vname);
1038 			vname = NULL;
1039 			*error = X509_V_ERR_OUT_OF_MEM;
1040 			return 0;
1041 		}
1042 		vname = NULL;
1043 	}
1044 
1045 	for (i = 0; i < sk_GENERAL_SUBTREE_num(nc->excludedSubtrees); i++) {
1046 		subtree = sk_GENERAL_SUBTREE_value(nc->excludedSubtrees, i);
1047 		if (subtree->minimum || subtree->maximum) {
1048 			*error = X509_V_ERR_SUBTREE_MINMAX;
1049 			return 0;
1050 		}
1051 		if (!x509_constraints_validate(subtree->base, &vname, error))
1052 			return 0;
1053 		if (vname->type == 0) {
1054 			x509_constraints_name_free(vname);
1055 			vname = NULL;
1056 			continue;
1057 		}
1058 		if (!x509_constraints_names_add(excluded, vname)) {
1059 			x509_constraints_name_free(vname);
1060 			vname = NULL;
1061 			*error = X509_V_ERR_OUT_OF_MEM;
1062 			return 0;
1063 		}
1064 		vname = NULL;
1065 	}
1066 
1067 	return 1;
1068 }
1069 
1070 /*
1071  * Match a validated name in "name" against a validated constraint in
1072  * "constraint" return 1 if then name matches, 0 otherwise.
1073  */
1074 int
1075 x509_constraints_match(struct x509_constraints_name *name,
1076     struct x509_constraints_name *constraint)
1077 {
1078 	if (name->type != constraint->type)
1079 		return 0;
1080 	if (name->type == GEN_DNS)
1081 		return x509_constraints_sandns(name->name, strlen(name->name),
1082 		    constraint->name, strlen(constraint->name));
1083 	if (name->type == GEN_URI)
1084 		return x509_constraints_domain(name->name, strlen(name->name),
1085 		    constraint->name, strlen(constraint->name));
1086 	if (name->type == GEN_IPADD) {
1087 		size_t nlen = name->af == AF_INET ? 4 : 16;
1088 		size_t clen = name->af == AF_INET ? 8 : 32;
1089 		if (name->af != AF_INET && name->af != AF_INET6)
1090 			return 0;
1091 		if (constraint->af != AF_INET && constraint->af != AF_INET6)
1092 			return 0;
1093 		if (name->af != constraint->af)
1094 			return 0;
1095 		return x509_constraints_ipaddr(name->address, nlen,
1096 		    constraint->address, clen);
1097 	}
1098 	if (name->type == GEN_EMAIL) {
1099 		if (constraint->local) {
1100 			/* mailbox local and domain parts must exactly match */
1101 			return (strcmp(name->local, constraint->local) == 0 &&
1102 			    strcmp(name->name, constraint->name) == 0);
1103 		}
1104 		/* otherwise match the constraint to the domain part */
1105 		return x509_constraints_domain(name->name, strlen(name->name),
1106 		    constraint->name, strlen(constraint->name));
1107 	}
1108 	if (name->type == GEN_DIRNAME)
1109 		return x509_constraints_dirname(name->der, name->der_len,
1110 		    constraint->der, constraint->der_len);
1111 	return 0;
1112 }
1113 
1114 /*
1115  * Make sure every name in names does not match any excluded
1116  * constraints, and does match at least one permitted constraint if
1117  * any are present. Returns 1 if ok, 0, and sets error if not.
1118  */
1119 int
1120 x509_constraints_check(struct x509_constraints_names *names,
1121     struct x509_constraints_names *permitted,
1122     struct x509_constraints_names *excluded, int *error)
1123 {
1124 	size_t i, j;
1125 
1126 	for (i = 0; i < names->names_count; i++) {
1127 		int permitted_seen = 0;
1128 		int permitted_matched = 0;
1129 
1130 		for (j = 0; j < excluded->names_count; j++) {
1131 			if (x509_constraints_match(names->names[i],
1132 			    excluded->names[j])) {
1133 				*error = X509_V_ERR_EXCLUDED_VIOLATION;
1134 				return 0;
1135 			}
1136 		}
1137 		for (j = 0; j < permitted->names_count; j++) {
1138 			if (permitted->names[j]->type == names->names[i]->type)
1139 				permitted_seen++;
1140 			if (x509_constraints_match(names->names[i],
1141 			    permitted->names[j])) {
1142 				permitted_matched++;
1143 				break;
1144 			}
1145 		}
1146 		if (permitted_seen && !permitted_matched) {
1147 			*error = X509_V_ERR_PERMITTED_VIOLATION;
1148 			return 0;
1149 		}
1150 	}
1151 	return 1;
1152 }
1153 
1154 /*
1155  * Walk a validated chain of X509 certs, starting at the leaf, and
1156  * validate the name constraints in the chain. Intended for use with
1157  * the legacy X509 validtion code in x509_vfy.c
1158  *
1159  * returns 1 if the constraints are ok, 0 otherwise, setting error and
1160  * depth
1161  */
1162 int
1163 x509_constraints_chain(STACK_OF(X509) *chain, int *error, int *depth)
1164 {
1165 	int chain_length, verify_err = X509_V_ERR_UNSPECIFIED, i = 0;
1166 	struct x509_constraints_names *names = NULL;
1167 	struct x509_constraints_names *excluded = NULL;
1168 	struct x509_constraints_names *permitted = NULL;
1169 	size_t constraints_count = 0;
1170 	X509 *cert;
1171 
1172 	if (chain == NULL || (chain_length = sk_X509_num(chain)) == 0)
1173 		goto err;
1174 	if (chain_length == 1)
1175 		return 1;
1176 	if ((names = x509_constraints_names_new(
1177 	    X509_VERIFY_MAX_CHAIN_NAMES)) == NULL) {
1178 		verify_err = X509_V_ERR_OUT_OF_MEM;
1179 		goto err;
1180 	}
1181 
1182 	if ((cert = sk_X509_value(chain, 0)) == NULL)
1183 		goto err;
1184 	if (!x509_constraints_extract_names(names, cert, 1, &verify_err))
1185 		goto err;
1186 	for (i = 1; i < chain_length; i++) {
1187 		if ((cert = sk_X509_value(chain, i)) == NULL)
1188 			goto err;
1189 		if (cert->nc != NULL) {
1190 			if ((permitted = x509_constraints_names_new(
1191 			    X509_VERIFY_MAX_CHAIN_CONSTRAINTS)) == NULL) {
1192 				verify_err = X509_V_ERR_OUT_OF_MEM;
1193 				goto err;
1194 			}
1195 			if ((excluded = x509_constraints_names_new(
1196 			    X509_VERIFY_MAX_CHAIN_CONSTRAINTS)) == NULL) {
1197 				verify_err = X509_V_ERR_OUT_OF_MEM;
1198 				goto err;
1199 			}
1200 			if (!x509_constraints_extract_constraints(cert,
1201 			    permitted, excluded, &verify_err))
1202 				goto err;
1203 			constraints_count += permitted->names_count;
1204 			constraints_count += excluded->names_count;
1205 			if (constraints_count >
1206 			    X509_VERIFY_MAX_CHAIN_CONSTRAINTS) {
1207 				verify_err = X509_V_ERR_OUT_OF_MEM;
1208 				goto err;
1209 			}
1210 			if (!x509_constraints_check(names, permitted, excluded,
1211 			    &verify_err))
1212 				goto err;
1213 			x509_constraints_names_free(excluded);
1214 			excluded = NULL;
1215 			x509_constraints_names_free(permitted);
1216 			permitted = NULL;
1217 		}
1218 		if (!x509_constraints_extract_names(names, cert, 0,
1219 		    &verify_err))
1220 			goto err;
1221 	}
1222 
1223 	x509_constraints_names_free(names);
1224 	return 1;
1225 
1226  err:
1227 	*error = verify_err;
1228 	*depth = i;
1229 	x509_constraints_names_free(excluded);
1230 	x509_constraints_names_free(permitted);
1231 	x509_constraints_names_free(names);
1232 	return 0;
1233 }
1234