1 /* $OpenBSD: x509_ncons.c,v 1.5 2021/11/01 20:53:08 tb Exp $ */
2 /* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
3  * project.
4  */
5 /* ====================================================================
6  * Copyright (c) 2003 The OpenSSL Project.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in
17  *    the documentation and/or other materials provided with the
18  *    distribution.
19  *
20  * 3. All advertising materials mentioning features or use of this
21  *    software must display the following acknowledgment:
22  *    "This product includes software developed by the OpenSSL Project
23  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24  *
25  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26  *    endorse or promote products derived from this software without
27  *    prior written permission. For written permission, please contact
28  *    licensing@OpenSSL.org.
29  *
30  * 5. Products derived from this software may not be called "OpenSSL"
31  *    nor may "OpenSSL" appear in their names without prior written
32  *    permission of the OpenSSL Project.
33  *
34  * 6. Redistributions of any form whatsoever must retain the following
35  *    acknowledgment:
36  *    "This product includes software developed by the OpenSSL Project
37  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38  *
39  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
43  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50  * OF THE POSSIBILITY OF SUCH DAMAGE.
51  * ====================================================================
52  *
53  * This product includes cryptographic software written by Eric Young
54  * (eay@cryptsoft.com).  This product includes software written by Tim
55  * Hudson (tjh@cryptsoft.com).
56  *
57  */
58 
59 #include <stdio.h>
60 #include <string.h>
61 
62 #include <openssl/asn1t.h>
63 #include <openssl/conf.h>
64 #include <openssl/err.h>
65 #include <openssl/x509v3.h>
66 
67 #include "x509_lcl.h"
68 
69 static void *v2i_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method,
70     X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval);
71 static int i2r_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method,
72     void *a, BIO *bp, int ind);
73 static int do_i2r_name_constraints(const X509V3_EXT_METHOD *method,
74     STACK_OF(GENERAL_SUBTREE) *trees, BIO *bp, int ind, char *name);
75 static int print_nc_ipadd(BIO *bp, ASN1_OCTET_STRING *ip);
76 
77 static int nc_match(GENERAL_NAME *gen, NAME_CONSTRAINTS *nc);
78 static int nc_match_single(GENERAL_NAME *sub, GENERAL_NAME *gen);
79 static int nc_dn(X509_NAME *sub, X509_NAME *nm);
80 static int nc_dns(ASN1_IA5STRING *sub, ASN1_IA5STRING *dns);
81 static int nc_email(ASN1_IA5STRING *sub, ASN1_IA5STRING *eml);
82 static int nc_uri(ASN1_IA5STRING *uri, ASN1_IA5STRING *base);
83 
84 const X509V3_EXT_METHOD v3_name_constraints = {
85 	.ext_nid = NID_name_constraints,
86 	.ext_flags = 0,
87 	.it = &NAME_CONSTRAINTS_it,
88 	.ext_new = NULL,
89 	.ext_free = NULL,
90 	.d2i = NULL,
91 	.i2d = NULL,
92 	.i2s = NULL,
93 	.s2i = NULL,
94 	.i2v = NULL,
95 	.v2i = v2i_NAME_CONSTRAINTS,
96 	.i2r = i2r_NAME_CONSTRAINTS,
97 	.r2i = NULL,
98 	.usr_data = NULL,
99 };
100 
101 static const ASN1_TEMPLATE GENERAL_SUBTREE_seq_tt[] = {
102 	{
103 		.flags = 0,
104 		.tag = 0,
105 		.offset = offsetof(GENERAL_SUBTREE, base),
106 		.field_name = "base",
107 		.item = &GENERAL_NAME_it,
108 	},
109 	{
110 		.flags = ASN1_TFLG_IMPLICIT | ASN1_TFLG_OPTIONAL,
111 		.tag = 0,
112 		.offset = offsetof(GENERAL_SUBTREE, minimum),
113 		.field_name = "minimum",
114 		.item = &ASN1_INTEGER_it,
115 	},
116 	{
117 		.flags = ASN1_TFLG_IMPLICIT | ASN1_TFLG_OPTIONAL,
118 		.tag = 1,
119 		.offset = offsetof(GENERAL_SUBTREE, maximum),
120 		.field_name = "maximum",
121 		.item = &ASN1_INTEGER_it,
122 	},
123 };
124 
125 const ASN1_ITEM GENERAL_SUBTREE_it = {
126 	.itype = ASN1_ITYPE_SEQUENCE,
127 	.utype = V_ASN1_SEQUENCE,
128 	.templates = GENERAL_SUBTREE_seq_tt,
129 	.tcount = sizeof(GENERAL_SUBTREE_seq_tt) / sizeof(ASN1_TEMPLATE),
130 	.funcs = NULL,
131 	.size = sizeof(GENERAL_SUBTREE),
132 	.sname = "GENERAL_SUBTREE",
133 };
134 
135 static const ASN1_TEMPLATE NAME_CONSTRAINTS_seq_tt[] = {
136 	{
137 		.flags = ASN1_TFLG_IMPLICIT | ASN1_TFLG_SEQUENCE_OF | ASN1_TFLG_OPTIONAL,
138 		.tag = 0,
139 		.offset = offsetof(NAME_CONSTRAINTS, permittedSubtrees),
140 		.field_name = "permittedSubtrees",
141 		.item = &GENERAL_SUBTREE_it,
142 	},
143 	{
144 		.flags = ASN1_TFLG_IMPLICIT | ASN1_TFLG_SEQUENCE_OF | ASN1_TFLG_OPTIONAL,
145 		.tag = 1,
146 		.offset = offsetof(NAME_CONSTRAINTS, excludedSubtrees),
147 		.field_name = "excludedSubtrees",
148 		.item = &GENERAL_SUBTREE_it,
149 	},
150 };
151 
152 const ASN1_ITEM NAME_CONSTRAINTS_it = {
153 	.itype = ASN1_ITYPE_SEQUENCE,
154 	.utype = V_ASN1_SEQUENCE,
155 	.templates = NAME_CONSTRAINTS_seq_tt,
156 	.tcount = sizeof(NAME_CONSTRAINTS_seq_tt) / sizeof(ASN1_TEMPLATE),
157 	.funcs = NULL,
158 	.size = sizeof(NAME_CONSTRAINTS),
159 	.sname = "NAME_CONSTRAINTS",
160 };
161 
162 
163 GENERAL_SUBTREE *
164 GENERAL_SUBTREE_new(void)
165 {
166 	return (GENERAL_SUBTREE*)ASN1_item_new(&GENERAL_SUBTREE_it);
167 }
168 
169 void
170 GENERAL_SUBTREE_free(GENERAL_SUBTREE *a)
171 {
172 	ASN1_item_free((ASN1_VALUE *)a, &GENERAL_SUBTREE_it);
173 }
174 
175 NAME_CONSTRAINTS *
176 NAME_CONSTRAINTS_new(void)
177 {
178 	return (NAME_CONSTRAINTS*)ASN1_item_new(&NAME_CONSTRAINTS_it);
179 }
180 
181 void
182 NAME_CONSTRAINTS_free(NAME_CONSTRAINTS *a)
183 {
184 	ASN1_item_free((ASN1_VALUE *)a, &NAME_CONSTRAINTS_it);
185 }
186 
187 static void *
188 v2i_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method, X509V3_CTX *ctx,
189     STACK_OF(CONF_VALUE) *nval)
190 {
191 	int i;
192 	CONF_VALUE tval, *val;
193 	STACK_OF(GENERAL_SUBTREE) **ptree = NULL;
194 	NAME_CONSTRAINTS *ncons = NULL;
195 	GENERAL_SUBTREE *sub = NULL;
196 
197 	ncons = NAME_CONSTRAINTS_new();
198 	if (!ncons)
199 		goto memerr;
200 	for (i = 0; i < sk_CONF_VALUE_num(nval); i++) {
201 		val = sk_CONF_VALUE_value(nval, i);
202 		if (!strncmp(val->name, "permitted", 9) && val->name[9]) {
203 			ptree = &ncons->permittedSubtrees;
204 			tval.name = val->name + 10;
205 		} else if (!strncmp(val->name, "excluded", 8) && val->name[8]) {
206 			ptree = &ncons->excludedSubtrees;
207 			tval.name = val->name + 9;
208 		} else {
209 			X509V3error(X509V3_R_INVALID_SYNTAX);
210 			goto err;
211 		}
212 		tval.value = val->value;
213 		sub = GENERAL_SUBTREE_new();
214 		if (!v2i_GENERAL_NAME_ex(sub->base, method, ctx, &tval, 1))
215 			goto err;
216 		if (!*ptree)
217 			*ptree = sk_GENERAL_SUBTREE_new_null();
218 		if (!*ptree || !sk_GENERAL_SUBTREE_push(*ptree, sub))
219 			goto memerr;
220 		sub = NULL;
221 	}
222 
223 	return ncons;
224 
225 memerr:
226 	X509V3error(ERR_R_MALLOC_FAILURE);
227 err:
228 	NAME_CONSTRAINTS_free(ncons);
229 	GENERAL_SUBTREE_free(sub);
230 	return NULL;
231 }
232 
233 static int
234 i2r_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method, void *a, BIO *bp, int ind)
235 {
236 	NAME_CONSTRAINTS *ncons = a;
237 
238 	do_i2r_name_constraints(method, ncons->permittedSubtrees,
239 	    bp, ind, "Permitted");
240 	do_i2r_name_constraints(method, ncons->excludedSubtrees,
241 	    bp, ind, "Excluded");
242 	return 1;
243 }
244 
245 static int
246 do_i2r_name_constraints(const X509V3_EXT_METHOD *method,
247     STACK_OF(GENERAL_SUBTREE) *trees, BIO *bp, int ind, char *name)
248 {
249 	GENERAL_SUBTREE *tree;
250 	int i;
251 
252 	if (sk_GENERAL_SUBTREE_num(trees) > 0)
253 		BIO_printf(bp, "%*s%s:\n", ind, "", name);
254 	for (i = 0; i < sk_GENERAL_SUBTREE_num(trees); i++) {
255 		tree = sk_GENERAL_SUBTREE_value(trees, i);
256 		BIO_printf(bp, "%*s", ind + 2, "");
257 		if (tree->base->type == GEN_IPADD)
258 			print_nc_ipadd(bp, tree->base->d.ip);
259 		else
260 			GENERAL_NAME_print(bp, tree->base);
261 		BIO_puts(bp, "\n");
262 	}
263 	return 1;
264 }
265 
266 static int
267 print_nc_ipadd(BIO *bp, ASN1_OCTET_STRING *ip)
268 {
269 	int i, len;
270 	unsigned char *p;
271 
272 	p = ip->data;
273 	len = ip->length;
274 	BIO_puts(bp, "IP:");
275 	if (len == 8) {
276 		BIO_printf(bp, "%d.%d.%d.%d/%d.%d.%d.%d",
277 		    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);
278 	} else if (len == 32) {
279 		for (i = 0; i < 16; i++) {
280 			BIO_printf(bp, "%X", p[0] << 8 | p[1]);
281 			p += 2;
282 			if (i == 7)
283 				BIO_puts(bp, "/");
284 			else if (i != 15)
285 				BIO_puts(bp, ":");
286 		}
287 	} else
288 		BIO_printf(bp, "IP Address:<invalid>");
289 	return 1;
290 }
291 
292 /* Check a certificate conforms to a specified set of constraints.
293  * Return values:
294  *  X509_V_OK: All constraints obeyed.
295  *  X509_V_ERR_PERMITTED_VIOLATION: Permitted subtree violation.
296  *  X509_V_ERR_EXCLUDED_VIOLATION: Excluded subtree violation.
297  *  X509_V_ERR_SUBTREE_MINMAX: Min or max values present and matching type.
298  *  X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE:  Unsupported constraint type.
299  *  X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX: bad unsupported constraint syntax.
300  *  X509_V_ERR_UNSUPPORTED_NAME_SYNTAX: bad or unsupported syntax of name
301  */
302 
303 int
304 NAME_CONSTRAINTS_check(X509 *x, NAME_CONSTRAINTS *nc)
305 {
306 	int r, i;
307 	X509_NAME *nm;
308 
309 	nm = X509_get_subject_name(x);
310 
311 	if (X509_NAME_entry_count(nm) > 0) {
312 		GENERAL_NAME gntmp;
313 		gntmp.type = GEN_DIRNAME;
314 		gntmp.d.directoryName = nm;
315 
316 		r = nc_match(&gntmp, nc);
317 
318 		if (r != X509_V_OK)
319 			return r;
320 
321 		gntmp.type = GEN_EMAIL;
322 
323 		/* Process any email address attributes in subject name */
324 
325 		for (i = -1;;) {
326 			X509_NAME_ENTRY *ne;
327 			i = X509_NAME_get_index_by_NID(nm,
328 			    NID_pkcs9_emailAddress, i);
329 			if (i == -1)
330 				break;
331 			ne = X509_NAME_get_entry(nm, i);
332 			gntmp.d.rfc822Name = X509_NAME_ENTRY_get_data(ne);
333 			if (gntmp.d.rfc822Name->type != V_ASN1_IA5STRING)
334 				return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
335 
336 			r = nc_match(&gntmp, nc);
337 
338 			if (r != X509_V_OK)
339 				return r;
340 		}
341 
342 	}
343 
344 	for (i = 0; i < sk_GENERAL_NAME_num(x->altname); i++) {
345 		GENERAL_NAME *gen = sk_GENERAL_NAME_value(x->altname, i);
346 		r = nc_match(gen, nc);
347 		if (r != X509_V_OK)
348 			return r;
349 	}
350 	return X509_V_OK;
351 }
352 static int
353 nc_match(GENERAL_NAME *gen, NAME_CONSTRAINTS *nc)
354 {
355 	GENERAL_SUBTREE *sub;
356 	int i, r, match = 0;
357 
358 	/* Permitted subtrees: if any subtrees exist of matching the type
359 	 * at least one subtree must match.
360 	 */
361 
362 	for (i = 0; i < sk_GENERAL_SUBTREE_num(nc->permittedSubtrees); i++) {
363 		sub = sk_GENERAL_SUBTREE_value(nc->permittedSubtrees, i);
364 		if (gen->type != sub->base->type)
365 			continue;
366 		if (sub->minimum || sub->maximum)
367 			return X509_V_ERR_SUBTREE_MINMAX;
368 		/* If we already have a match don't bother trying any more */
369 		if (match == 2)
370 			continue;
371 		if (match == 0)
372 			match = 1;
373 		r = nc_match_single(gen, sub->base);
374 		if (r == X509_V_OK)
375 			match = 2;
376 		else if (r != X509_V_ERR_PERMITTED_VIOLATION)
377 			return r;
378 	}
379 
380 	if (match == 1)
381 		return X509_V_ERR_PERMITTED_VIOLATION;
382 
383 	/* Excluded subtrees: must not match any of these */
384 
385 	for (i = 0; i < sk_GENERAL_SUBTREE_num(nc->excludedSubtrees); i++) {
386 		sub = sk_GENERAL_SUBTREE_value(nc->excludedSubtrees, i);
387 		if (gen->type != sub->base->type)
388 			continue;
389 		if (sub->minimum || sub->maximum)
390 			return X509_V_ERR_SUBTREE_MINMAX;
391 
392 		r = nc_match_single(gen, sub->base);
393 		if (r == X509_V_OK)
394 			return X509_V_ERR_EXCLUDED_VIOLATION;
395 		else if (r != X509_V_ERR_PERMITTED_VIOLATION)
396 			return r;
397 
398 	}
399 
400 	return X509_V_OK;
401 }
402 
403 static int
404 nc_match_single(GENERAL_NAME *gen, GENERAL_NAME *base)
405 {
406 	switch (base->type) {
407 	case GEN_DIRNAME:
408 		return nc_dn(gen->d.directoryName, base->d.directoryName);
409 
410 	case GEN_DNS:
411 		return nc_dns(gen->d.dNSName, base->d.dNSName);
412 
413 	case GEN_EMAIL:
414 		return nc_email(gen->d.rfc822Name, base->d.rfc822Name);
415 
416 	case GEN_URI:
417 		return nc_uri(gen->d.uniformResourceIdentifier,
418 		    base->d.uniformResourceIdentifier);
419 
420 	default:
421 		return X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE;
422 	}
423 }
424 
425 /* directoryName name constraint matching.
426  * The canonical encoding of X509_NAME makes this comparison easy. It is
427  * matched if the subtree is a subset of the name.
428  */
429 
430 static int
431 nc_dn(X509_NAME *nm, X509_NAME *base)
432 {
433 	/* Ensure canonical encodings are up to date.  */
434 	if (nm->modified && i2d_X509_NAME(nm, NULL) < 0)
435 		return X509_V_ERR_OUT_OF_MEM;
436 	if (base->modified && i2d_X509_NAME(base, NULL) < 0)
437 		return X509_V_ERR_OUT_OF_MEM;
438 	if (base->canon_enclen > nm->canon_enclen)
439 		return X509_V_ERR_PERMITTED_VIOLATION;
440 	if (memcmp(base->canon_enc, nm->canon_enc, base->canon_enclen))
441 		return X509_V_ERR_PERMITTED_VIOLATION;
442 	return X509_V_OK;
443 }
444 
445 static int
446 nc_dns(ASN1_IA5STRING *dns, ASN1_IA5STRING *base)
447 {
448 	char *baseptr = (char *)base->data;
449 	char *dnsptr = (char *)dns->data;
450 
451 	/* Empty matches everything */
452 	if (!*baseptr)
453 		return X509_V_OK;
454 	/* Otherwise can add zero or more components on the left so
455 	 * compare RHS and if dns is longer and expect '.' as preceding
456 	 * character.
457 	 */
458 	if (dns->length > base->length) {
459 		dnsptr += dns->length - base->length;
460 		if (baseptr[0] != '.' && dnsptr[-1] != '.')
461 			return X509_V_ERR_PERMITTED_VIOLATION;
462 	}
463 
464 	if (strcasecmp(baseptr, dnsptr))
465 		return X509_V_ERR_PERMITTED_VIOLATION;
466 
467 	return X509_V_OK;
468 }
469 
470 static int
471 nc_email(ASN1_IA5STRING *eml, ASN1_IA5STRING *base)
472 {
473 	const char *baseptr = (char *)base->data;
474 	const char *emlptr = (char *)eml->data;
475 	const char *baseat = strchr(baseptr, '@');
476 	const char *emlat = strchr(emlptr, '@');
477 
478 	if (!emlat)
479 		return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
480 	/* Special case: inital '.' is RHS match */
481 	if (!baseat && (*baseptr == '.')) {
482 		if (eml->length > base->length) {
483 			emlptr += eml->length - base->length;
484 			if (!strcasecmp(baseptr, emlptr))
485 				return X509_V_OK;
486 		}
487 		return X509_V_ERR_PERMITTED_VIOLATION;
488 	}
489 
490 	/* If we have anything before '@' match local part */
491 
492 	if (baseat) {
493 		if (baseat != baseptr) {
494 			if ((baseat - baseptr) != (emlat - emlptr))
495 				return X509_V_ERR_PERMITTED_VIOLATION;
496 			/* Case sensitive match of local part */
497 			if (strncmp(baseptr, emlptr, emlat - emlptr))
498 				return X509_V_ERR_PERMITTED_VIOLATION;
499 		}
500 		/* Position base after '@' */
501 		baseptr = baseat + 1;
502 	}
503 	emlptr = emlat + 1;
504 	/* Just have hostname left to match: case insensitive */
505 	if (strcasecmp(baseptr, emlptr))
506 		return X509_V_ERR_PERMITTED_VIOLATION;
507 
508 	return X509_V_OK;
509 }
510 
511 static int
512 nc_uri(ASN1_IA5STRING *uri, ASN1_IA5STRING *base)
513 {
514 	const char *baseptr = (char *)base->data;
515 	const char *hostptr = (char *)uri->data;
516 	const char *p = strchr(hostptr, ':');
517 	int hostlen;
518 
519 	/* Check for foo:// and skip past it */
520 	if (!p || (p[1] != '/') || (p[2] != '/'))
521 		return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
522 	hostptr = p + 3;
523 
524 	/* Determine length of hostname part of URI */
525 
526 	/* Look for a port indicator as end of hostname first */
527 
528 	p = strchr(hostptr, ':');
529 	/* Otherwise look for trailing slash */
530 	if (!p)
531 		p = strchr(hostptr, '/');
532 
533 	if (!p)
534 		hostlen = strlen(hostptr);
535 	else
536 		hostlen = p - hostptr;
537 
538 	if (hostlen == 0)
539 		return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
540 
541 	/* Special case: inital '.' is RHS match */
542 	if (*baseptr == '.') {
543 		if (hostlen > base->length) {
544 			p = hostptr + hostlen - base->length;
545 			if (!strncasecmp(p, baseptr, base->length))
546 				return X509_V_OK;
547 		}
548 		return X509_V_ERR_PERMITTED_VIOLATION;
549 	}
550 
551 	if ((base->length != (int)hostlen) ||
552 	    strncasecmp(hostptr, baseptr, hostlen))
553 		return X509_V_ERR_PERMITTED_VIOLATION;
554 
555 	return X509_V_OK;
556 }
557