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