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