xref: /openbsd-src/lib/libcrypto/x509/x509_constraints.c (revision 1a892b579fd23444f4850d4083b4f56433d36dc8)
1 /* $OpenBSD: x509_constraints.c,v 1.25 2022/03/14 21:29:46 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 		*bytes = aname->data;
661 		*len = strlen(aname->data);
662 		return name->type;
663 	}
664 	if (name->type == GEN_EMAIL) {
665 		ASN1_IA5STRING *aname = name->d.rfc822Name;
666 		*bytes = aname->data;
667 		*len = strlen(aname->data);
668 		return name->type;
669 	}
670 	if (name->type == GEN_URI) {
671 		ASN1_IA5STRING *aname = name->d.uniformResourceIdentifier;
672 		*bytes = aname->data;
673 		*len = strlen(aname->data);
674 		return name->type;
675 	}
676 	if (name->type == GEN_DIRNAME) {
677 		X509_NAME *dname = name->d.directoryName;
678 		if (!dname->modified || i2d_X509_NAME(dname, NULL) >= 0) {
679 			*bytes = dname->canon_enc;
680 			*len = dname->canon_enclen;
681 			return name->type;
682 		}
683 	}
684 	if (name->type == GEN_IPADD) {
685 		*bytes = name->d.ip->data;
686 		*len = name->d.ip->length;
687 		return name->type;
688 	}
689 	return 0;
690 }
691 
692 
693 /*
694  * Extract the relevant names for constraint checking from "cert",
695  * validate them, and add them to the list of cert names for "chain".
696  * returns 1 on success sets error and returns 0 on failure.
697  */
698 int
699 x509_constraints_extract_names(struct x509_constraints_names *names,
700     X509 *cert, int is_leaf, int *error)
701 {
702 	struct x509_constraints_name *vname = NULL;
703 	X509_NAME *subject_name;
704 	GENERAL_NAME *name;
705 	ssize_t i = 0;
706 	int name_type, include_cn = is_leaf, include_email = is_leaf;
707 
708 	/* first grab the altnames */
709 	while ((name = sk_GENERAL_NAME_value(cert->altname, i++)) != NULL) {
710 		uint8_t *bytes = NULL;
711 		size_t len = 0;
712 
713 		if ((vname = x509_constraints_name_new()) == NULL) {
714 			*error = X509_V_ERR_OUT_OF_MEM;
715 			goto err;
716 		}
717 
718 		name_type = x509_constraints_general_to_bytes(name, &bytes,
719 		    &len);
720 		switch(name_type) {
721 		case GEN_DNS:
722 			if (!x509_constraints_valid_sandns(bytes, len)) {
723 				*error = X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
724 				goto err;
725 			}
726 			if ((vname->name = strdup(bytes)) == NULL) {
727 				*error = X509_V_ERR_OUT_OF_MEM;
728 				goto err;
729 			}
730 			vname->type = GEN_DNS;
731 			include_cn = 0; /* don't use cn from subject */
732 			break;
733 		case GEN_EMAIL:
734 			if (!x509_constraints_parse_mailbox(bytes, len,
735 			    vname)) {
736 				*error = X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
737 				goto err;
738 			}
739 			vname->type = GEN_EMAIL;
740 			include_email = 0; /* don't use email from subject */
741 			break;
742 		case GEN_URI:
743 			if (!x509_constraints_uri_host(bytes, len, &vname->name)) {
744 				*error = X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
745 				goto err;
746 			}
747 			if (vname->name == NULL) {
748 				*error = X509_V_ERR_OUT_OF_MEM;
749 				goto err;
750 			}
751 			vname->type = GEN_URI;
752 			break;
753 		case GEN_DIRNAME:
754 			if (len == 0) {
755 				*error = X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
756 				goto err;
757 			}
758 			if (bytes == NULL || ((vname->der = malloc(len)) ==
759 			    NULL)) {
760 				*error = X509_V_ERR_OUT_OF_MEM;
761 				goto err;
762 			}
763 			memcpy(vname->der, bytes, len);
764 			vname->der_len = len;
765 			vname->type = GEN_DIRNAME;
766 			break;
767 		case GEN_IPADD:
768 			if (len == 4)
769 				vname->af = AF_INET;
770 			if (len == 16)
771 				vname->af = AF_INET6;
772 			if (vname->af != AF_INET && vname->af != AF_INET6) {
773 				*error = X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
774 				goto err;
775 			}
776 			memcpy(vname->address, bytes, len);
777 			vname->type = GEN_IPADD;
778 			break;
779 		default:
780 			/* Ignore this name */
781 			x509_constraints_name_free(vname);
782 			vname = NULL;
783 			continue;
784 		}
785 		if (!x509_constraints_names_add(names, vname)) {
786 			*error = X509_V_ERR_OUT_OF_MEM;
787 			goto err;
788 		}
789 		vname = NULL;
790 	}
791 
792 	x509_constraints_name_free(vname);
793 	vname = NULL;
794 
795 	subject_name = X509_get_subject_name(cert);
796 	if (X509_NAME_entry_count(subject_name) > 0) {
797 		X509_NAME_ENTRY *email;
798 		X509_NAME_ENTRY *cn;
799 		/*
800 		 * This cert has a non-empty subject, so we must add
801 		 * the subject as a dirname to be compared against
802 		 * any dirname constraints
803 		 */
804 		if ((subject_name->modified &&
805 		    i2d_X509_NAME(subject_name, NULL) < 0) ||
806 		    (vname = x509_constraints_name_new()) == NULL ||
807 		    (vname->der = malloc(subject_name->canon_enclen)) == NULL) {
808 			*error = X509_V_ERR_OUT_OF_MEM;
809 			goto err;
810 		}
811 
812 		memcpy(vname->der, subject_name->canon_enc,
813 		    subject_name->canon_enclen);
814 		vname->der_len = subject_name->canon_enclen;
815 		vname->type = GEN_DIRNAME;
816 		if (!x509_constraints_names_add(names, vname)) {
817 			*error = X509_V_ERR_OUT_OF_MEM;
818 			goto err;
819 		}
820 		vname = NULL;
821 		/*
822 		 * Get any email addresses from the subject line, and
823 		 * add them as mbox names to be compared against any
824 		 * email constraints
825 		 */
826 		while (include_email &&
827 		    (i = X509_NAME_get_index_by_NID(subject_name,
828 		    NID_pkcs9_emailAddress, i)) >= 0) {
829 			ASN1_STRING *aname;
830 			if ((email = X509_NAME_get_entry(subject_name, i)) == NULL ||
831 			    (aname = X509_NAME_ENTRY_get_data(email)) == NULL) {
832 				*error = X509_V_ERR_OUT_OF_MEM;
833 				goto err;
834 			}
835 			if ((vname = x509_constraints_name_new()) == NULL) {
836 				*error = X509_V_ERR_OUT_OF_MEM;
837 				goto err;
838 			}
839 			if (!x509_constraints_parse_mailbox(aname->data,
840 			    aname->length, vname)) {
841 				*error = X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
842 				goto err;
843 			}
844 			vname->type = GEN_EMAIL;
845 			if (!x509_constraints_names_add(names, vname)) {
846 				*error = X509_V_ERR_OUT_OF_MEM;
847 				goto err;
848 			}
849 			vname = NULL;
850 		}
851 		/*
852 		 * Include the CN as a hostname to be checked againt
853 		 * name constraints if it looks like a hostname.
854 		 */
855 		while (include_cn &&
856 		    (i = X509_NAME_get_index_by_NID(subject_name,
857 		    NID_commonName, i)) >= 0) {
858 			ASN1_STRING *aname;
859 			if ((cn = X509_NAME_get_entry(subject_name, i)) == NULL ||
860 			    (aname = X509_NAME_ENTRY_get_data(cn)) == NULL) {
861 				*error = X509_V_ERR_OUT_OF_MEM;
862 				goto err;
863 			}
864 			if (!x509_constraints_valid_host(aname->data,
865 			    aname->length))
866 				continue; /* ignore it if not a hostname */
867 			if ((vname = x509_constraints_name_new()) == NULL) {
868 				*error = X509_V_ERR_OUT_OF_MEM;
869 				goto err;
870 			}
871 			if ((vname->name = strndup(aname->data,
872 			    aname->length)) == NULL) {
873 				*error = X509_V_ERR_OUT_OF_MEM;
874 				goto err;
875 			}
876 			vname->type = GEN_DNS;
877 			if (!x509_constraints_names_add(names, vname)) {
878 				*error = X509_V_ERR_OUT_OF_MEM;
879 				goto err;
880 			}
881 			vname = NULL;
882 		}
883 	}
884 	return 1;
885  err:
886 	x509_constraints_name_free(vname);
887 	return 0;
888 }
889 
890 /*
891  * Validate a constraint in a general name, putting the relevant data
892  * into "name" if valid. returns 0, and sets error if the constraint is
893  * not valid. returns 1 if the constraint validated. name->type will be
894  * set to a valid type if there is constraint data in name, or unmodified
895  * if the GENERAL_NAME had a valid type but was ignored.
896  */
897 int
898 x509_constraints_validate(GENERAL_NAME *constraint,
899     struct x509_constraints_name **out_name, int *out_error)
900 {
901 	uint8_t *bytes = NULL;
902 	size_t len = 0;
903 	struct x509_constraints_name *name;
904 	int error = X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX;
905 	int name_type;
906 
907 	if (out_name == NULL || *out_name != NULL)
908 		return 0;
909 
910 	if (out_error != NULL)
911 		*out_error = 0;
912 
913 	if ((name = x509_constraints_name_new()) == NULL) {
914 		error = X509_V_ERR_OUT_OF_MEM;
915 		goto err;
916 	}
917 
918 	name_type = x509_constraints_general_to_bytes(constraint, &bytes, &len);
919 	switch (name_type) {
920 	case GEN_DIRNAME:
921 		if (len == 0)
922 			goto err; /* XXX The RFCs are delightfully vague */
923 		if (bytes == NULL || (name->der = malloc(len)) == NULL) {
924 			error = X509_V_ERR_OUT_OF_MEM;
925 			goto err;
926 		}
927 		memcpy(name->der, bytes, len);
928 		name->der_len = len;
929 		name->type = GEN_DIRNAME;
930 		break;
931 	case GEN_DNS:
932 		if (!x509_constraints_valid_domain_constraint(bytes, len))
933 			goto err;
934 		if ((name->name = strdup(bytes)) == NULL) {
935 			error = X509_V_ERR_OUT_OF_MEM;
936 			goto err;
937 		}
938 		name->type = GEN_DNS;
939 		break;
940 	case GEN_EMAIL:
941 		if (len > 0 && memchr(bytes + 1, '@', len - 1) != NULL) {
942 			if (!x509_constraints_parse_mailbox(bytes, len, name))
943 				goto err;
944 			break;
945 		}
946 		/*
947 		 * Mail constraints of the form @domain.com are accepted by
948 		 * OpenSSL and Microsoft.
949 		 */
950 		if (len > 0 && bytes[0] == '@') {
951 			bytes++;
952 			len--;
953 		}
954 		if (!x509_constraints_valid_domain_constraint(bytes, len))
955 			goto err;
956 		if ((name->name = strdup(bytes)) == NULL) {
957 			error = X509_V_ERR_OUT_OF_MEM;
958 			goto err;
959 		}
960 		name->type = GEN_EMAIL;
961 		break;
962 	case GEN_IPADD:
963 		/* Constraints are ip then mask */
964 		if (len == 8)
965 			name->af = AF_INET;
966 		else if (len == 32)
967 			name->af = AF_INET6;
968 		else
969 			goto err;
970 		memcpy(&name->address[0], bytes, len);
971 		name->type = GEN_IPADD;
972 		break;
973 	case GEN_URI:
974 		if (!x509_constraints_valid_domain_constraint(bytes, len))
975 			goto err;
976 		if ((name->name = strdup(bytes)) == NULL) {
977 			error = X509_V_ERR_OUT_OF_MEM;
978 			goto err;
979 		}
980 		name->type = GEN_URI;
981 		break;
982 	default:
983 		break;
984 	}
985 
986 	*out_name = name;
987 
988 	return 1;
989 
990  err:
991 	x509_constraints_name_free(name);
992 	if (out_error != NULL)
993 		*out_error = error;
994 
995 	return 0;
996 }
997 
998 int
999 x509_constraints_extract_constraints(X509 *cert,
1000     struct x509_constraints_names *permitted,
1001     struct x509_constraints_names *excluded,
1002     int *error)
1003 {
1004 	struct x509_constraints_name *vname = NULL;
1005 	NAME_CONSTRAINTS *nc = cert->nc;
1006 	GENERAL_SUBTREE *subtree;
1007 	int i;
1008 
1009 	if (nc == NULL)
1010 		return 1;
1011 
1012 	for (i = 0; i < sk_GENERAL_SUBTREE_num(nc->permittedSubtrees); i++) {
1013 
1014 		subtree = sk_GENERAL_SUBTREE_value(nc->permittedSubtrees, i);
1015 		if (subtree->minimum || subtree->maximum) {
1016 			*error = X509_V_ERR_SUBTREE_MINMAX;
1017 			return 0;
1018 		}
1019 		if (!x509_constraints_validate(subtree->base, &vname, error))
1020 			return 0;
1021 		if (vname->type == 0) {
1022 			x509_constraints_name_free(vname);
1023 			vname = NULL;
1024 			continue;
1025 		}
1026 		if (!x509_constraints_names_add(permitted, vname)) {
1027 			x509_constraints_name_free(vname);
1028 			vname = NULL;
1029 			*error = X509_V_ERR_OUT_OF_MEM;
1030 			return 0;
1031 		}
1032 		vname = NULL;
1033 	}
1034 
1035 	for (i = 0; i < sk_GENERAL_SUBTREE_num(nc->excludedSubtrees); i++) {
1036 		subtree = sk_GENERAL_SUBTREE_value(nc->excludedSubtrees, i);
1037 		if (subtree->minimum || subtree->maximum) {
1038 			*error = X509_V_ERR_SUBTREE_MINMAX;
1039 			return 0;
1040 		}
1041 		if (!x509_constraints_validate(subtree->base, &vname, error))
1042 			return 0;
1043 		if (vname->type == 0) {
1044 			x509_constraints_name_free(vname);
1045 			vname = NULL;
1046 			continue;
1047 		}
1048 		if (!x509_constraints_names_add(excluded, vname)) {
1049 			x509_constraints_name_free(vname);
1050 			vname = NULL;
1051 			*error = X509_V_ERR_OUT_OF_MEM;
1052 			return 0;
1053 		}
1054 		vname = NULL;
1055 	}
1056 
1057 	return 1;
1058 }
1059 
1060 /*
1061  * Match a validated name in "name" against a validated constraint in
1062  * "constraint" return 1 if then name matches, 0 otherwise.
1063  */
1064 int
1065 x509_constraints_match(struct x509_constraints_name *name,
1066     struct x509_constraints_name *constraint)
1067 {
1068 	if (name->type != constraint->type)
1069 		return 0;
1070 	if (name->type == GEN_DNS)
1071 		return x509_constraints_sandns(name->name, strlen(name->name),
1072 		    constraint->name, strlen(constraint->name));
1073 	if (name->type == GEN_URI)
1074 		return x509_constraints_domain(name->name, strlen(name->name),
1075 		    constraint->name, strlen(constraint->name));
1076 	if (name->type == GEN_IPADD) {
1077 		size_t nlen = name->af == AF_INET ? 4 : 16;
1078 		size_t clen = name->af == AF_INET ? 8 : 32;
1079 		if (name->af != AF_INET && name->af != AF_INET6)
1080 			return 0;
1081 		if (constraint->af != AF_INET && constraint->af != AF_INET6)
1082 			return 0;
1083 		if (name->af != constraint->af)
1084 			return 0;
1085 		return x509_constraints_ipaddr(name->address, nlen,
1086 		    constraint->address, clen);
1087 	}
1088 	if (name->type == GEN_EMAIL) {
1089 		if (constraint->local) {
1090 			/* mailbox local and domain parts must exactly match */
1091 			return (strcmp(name->local, constraint->local) == 0 &&
1092 			    strcmp(name->name, constraint->name) == 0);
1093 		}
1094 		/* otherwise match the constraint to the domain part */
1095 		return x509_constraints_domain(name->name, strlen(name->name),
1096 		    constraint->name, strlen(constraint->name));
1097 	}
1098 	if (name->type == GEN_DIRNAME)
1099 		return x509_constraints_dirname(name->der, name->der_len,
1100 		    constraint->der, constraint->der_len);
1101 	return 0;
1102 }
1103 
1104 /*
1105  * Make sure every name in names does not match any excluded
1106  * constraints, and does match at least one permitted constraint if
1107  * any are present. Returns 1 if ok, 0, and sets error if not.
1108  */
1109 int
1110 x509_constraints_check(struct x509_constraints_names *names,
1111     struct x509_constraints_names *permitted,
1112     struct x509_constraints_names *excluded, int *error)
1113 {
1114 	size_t i, j;
1115 
1116 	for (i = 0; i < names->names_count; i++) {
1117 		int permitted_seen = 0;
1118 		int permitted_matched = 0;
1119 
1120 		for (j = 0; j < excluded->names_count; j++) {
1121 			if (x509_constraints_match(names->names[i],
1122 			    excluded->names[j])) {
1123 				*error = X509_V_ERR_EXCLUDED_VIOLATION;
1124 				return 0;
1125 			}
1126 		}
1127 		for (j = 0; j < permitted->names_count; j++) {
1128 			if (permitted->names[j]->type == names->names[i]->type)
1129 				permitted_seen++;
1130 			if (x509_constraints_match(names->names[i],
1131 			    permitted->names[j])) {
1132 				permitted_matched++;
1133 				break;
1134 			}
1135 		}
1136 		if (permitted_seen && !permitted_matched) {
1137 			*error = X509_V_ERR_PERMITTED_VIOLATION;
1138 			return 0;
1139 		}
1140 	}
1141 	return 1;
1142 }
1143 
1144 /*
1145  * Walk a validated chain of X509 certs, starting at the leaf, and
1146  * validate the name constraints in the chain. Intended for use with
1147  * the legacy X509 validtion code in x509_vfy.c
1148  *
1149  * returns 1 if the constraints are ok, 0 otherwise, setting error and
1150  * depth
1151  */
1152 int
1153 x509_constraints_chain(STACK_OF(X509) *chain, int *error, int *depth)
1154 {
1155 	int chain_length, verify_err = X509_V_ERR_UNSPECIFIED, i = 0;
1156 	struct x509_constraints_names *names = NULL;
1157 	struct x509_constraints_names *excluded = NULL;
1158 	struct x509_constraints_names *permitted = NULL;
1159 	size_t constraints_count = 0;
1160 	X509 *cert;
1161 
1162 	if (chain == NULL || (chain_length = sk_X509_num(chain)) == 0)
1163 		goto err;
1164 	if (chain_length == 1)
1165 		return 1;
1166 	if ((names = x509_constraints_names_new(
1167 	    X509_VERIFY_MAX_CHAIN_NAMES)) == NULL) {
1168 		verify_err = X509_V_ERR_OUT_OF_MEM;
1169 		goto err;
1170 	}
1171 
1172 	if ((cert = sk_X509_value(chain, 0)) == NULL)
1173 		goto err;
1174 	if (!x509_constraints_extract_names(names, cert, 1, &verify_err))
1175 		goto err;
1176 	for (i = 1; i < chain_length; i++) {
1177 		if ((cert = sk_X509_value(chain, i)) == NULL)
1178 			goto err;
1179 		if (cert->nc != NULL) {
1180 			if ((permitted = x509_constraints_names_new(
1181 			    X509_VERIFY_MAX_CHAIN_CONSTRAINTS)) == NULL) {
1182 				verify_err = X509_V_ERR_OUT_OF_MEM;
1183 				goto err;
1184 			}
1185 			if ((excluded = x509_constraints_names_new(
1186 			    X509_VERIFY_MAX_CHAIN_CONSTRAINTS)) == NULL) {
1187 				verify_err = X509_V_ERR_OUT_OF_MEM;
1188 				goto err;
1189 			}
1190 			if (!x509_constraints_extract_constraints(cert,
1191 			    permitted, excluded, &verify_err))
1192 				goto err;
1193 			constraints_count += permitted->names_count;
1194 			constraints_count += excluded->names_count;
1195 			if (constraints_count >
1196 			    X509_VERIFY_MAX_CHAIN_CONSTRAINTS) {
1197 				verify_err = X509_V_ERR_OUT_OF_MEM;
1198 				goto err;
1199 			}
1200 			if (!x509_constraints_check(names, permitted, excluded,
1201 			    &verify_err))
1202 				goto err;
1203 			x509_constraints_names_free(excluded);
1204 			excluded = NULL;
1205 			x509_constraints_names_free(permitted);
1206 			permitted = NULL;
1207 		}
1208 		if (!x509_constraints_extract_names(names, cert, 0,
1209 		    &verify_err))
1210 			goto err;
1211 	}
1212 
1213 	x509_constraints_names_free(names);
1214 	return 1;
1215 
1216  err:
1217 	*error = verify_err;
1218 	*depth = i;
1219 	x509_constraints_names_free(excluded);
1220 	x509_constraints_names_free(permitted);
1221 	x509_constraints_names_free(names);
1222 	return 0;
1223 }
1224