1/* $OpenBSD: x509_ncons.c,v 1.9 2023/02/16 08:38:17 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_local.h"
68
69static void *v2i_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method,
70    X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval);
71static int i2r_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method,
72    void *a, BIO *bp, int ind);
73static int do_i2r_name_constraints(const X509V3_EXT_METHOD *method,
74    STACK_OF(GENERAL_SUBTREE) *trees, BIO *bp, int ind, char *name);
75static int print_nc_ipadd(BIO *bp, ASN1_OCTET_STRING *ip);
76
77static int nc_match(GENERAL_NAME *gen, NAME_CONSTRAINTS *nc);
78static int nc_match_single(GENERAL_NAME *sub, GENERAL_NAME *gen);
79static int nc_dn(X509_NAME *sub, X509_NAME *nm);
80static int nc_dns(ASN1_IA5STRING *sub, ASN1_IA5STRING *dns);
81static int nc_email(ASN1_IA5STRING *sub, ASN1_IA5STRING *eml);
82static int nc_uri(ASN1_IA5STRING *uri, ASN1_IA5STRING *base);
83
84const 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
101static 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
125const 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
135static 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
152const 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
163GENERAL_SUBTREE *
164GENERAL_SUBTREE_new(void)
165{
166	return (GENERAL_SUBTREE*)ASN1_item_new(&GENERAL_SUBTREE_it);
167}
168LCRYPTO_ALIAS(GENERAL_SUBTREE_new);
169
170void
171GENERAL_SUBTREE_free(GENERAL_SUBTREE *a)
172{
173	ASN1_item_free((ASN1_VALUE *)a, &GENERAL_SUBTREE_it);
174}
175LCRYPTO_ALIAS(GENERAL_SUBTREE_free);
176
177NAME_CONSTRAINTS *
178NAME_CONSTRAINTS_new(void)
179{
180	return (NAME_CONSTRAINTS*)ASN1_item_new(&NAME_CONSTRAINTS_it);
181}
182LCRYPTO_ALIAS(NAME_CONSTRAINTS_new);
183
184void
185NAME_CONSTRAINTS_free(NAME_CONSTRAINTS *a)
186{
187	ASN1_item_free((ASN1_VALUE *)a, &NAME_CONSTRAINTS_it);
188}
189LCRYPTO_ALIAS(NAME_CONSTRAINTS_free);
190
191static void *
192v2i_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method, X509V3_CTX *ctx,
193    STACK_OF(CONF_VALUE) *nval)
194{
195	int i;
196	CONF_VALUE tval, *val;
197	STACK_OF(GENERAL_SUBTREE) **ptree = NULL;
198	NAME_CONSTRAINTS *ncons = NULL;
199	GENERAL_SUBTREE *sub = NULL;
200
201	ncons = NAME_CONSTRAINTS_new();
202	if (!ncons)
203		goto memerr;
204	for (i = 0; i < sk_CONF_VALUE_num(nval); i++) {
205		val = sk_CONF_VALUE_value(nval, i);
206		if (!strncmp(val->name, "permitted", 9) && val->name[9]) {
207			ptree = &ncons->permittedSubtrees;
208			tval.name = val->name + 10;
209		} else if (!strncmp(val->name, "excluded", 8) && val->name[8]) {
210			ptree = &ncons->excludedSubtrees;
211			tval.name = val->name + 9;
212		} else {
213			X509V3error(X509V3_R_INVALID_SYNTAX);
214			goto err;
215		}
216		tval.value = val->value;
217		sub = GENERAL_SUBTREE_new();
218		if (!v2i_GENERAL_NAME_ex(sub->base, method, ctx, &tval, 1))
219			goto err;
220		if (!*ptree)
221			*ptree = sk_GENERAL_SUBTREE_new_null();
222		if (!*ptree || !sk_GENERAL_SUBTREE_push(*ptree, sub))
223			goto memerr;
224		sub = NULL;
225	}
226
227	return ncons;
228
229memerr:
230	X509V3error(ERR_R_MALLOC_FAILURE);
231err:
232	NAME_CONSTRAINTS_free(ncons);
233	GENERAL_SUBTREE_free(sub);
234	return NULL;
235}
236
237static int
238i2r_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method, void *a, BIO *bp, int ind)
239{
240	NAME_CONSTRAINTS *ncons = a;
241
242	do_i2r_name_constraints(method, ncons->permittedSubtrees,
243	    bp, ind, "Permitted");
244	do_i2r_name_constraints(method, ncons->excludedSubtrees,
245	    bp, ind, "Excluded");
246	return 1;
247}
248
249static int
250do_i2r_name_constraints(const X509V3_EXT_METHOD *method,
251    STACK_OF(GENERAL_SUBTREE) *trees, BIO *bp, int ind, char *name)
252{
253	GENERAL_SUBTREE *tree;
254	int i;
255
256	if (sk_GENERAL_SUBTREE_num(trees) > 0)
257		BIO_printf(bp, "%*s%s:\n", ind, "", name);
258	for (i = 0; i < sk_GENERAL_SUBTREE_num(trees); i++) {
259		tree = sk_GENERAL_SUBTREE_value(trees, i);
260		BIO_printf(bp, "%*s", ind + 2, "");
261		if (tree->base->type == GEN_IPADD)
262			print_nc_ipadd(bp, tree->base->d.ip);
263		else
264			GENERAL_NAME_print(bp, tree->base);
265		BIO_puts(bp, "\n");
266	}
267	return 1;
268}
269
270static int
271print_nc_ipadd(BIO *bp, ASN1_OCTET_STRING *ip)
272{
273	int i, len;
274	unsigned char *p;
275
276	p = ip->data;
277	len = ip->length;
278	BIO_puts(bp, "IP:");
279	if (len == 8) {
280		BIO_printf(bp, "%d.%d.%d.%d/%d.%d.%d.%d",
281		    p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]);
282	} else if (len == 32) {
283		for (i = 0; i < 16; i++) {
284			BIO_printf(bp, "%X", p[0] << 8 | p[1]);
285			p += 2;
286			if (i == 7)
287				BIO_puts(bp, "/");
288			else if (i != 15)
289				BIO_puts(bp, ":");
290		}
291	} else
292		BIO_printf(bp, "IP Address:<invalid>");
293	return 1;
294}
295
296/* Check a certificate conforms to a specified set of constraints.
297 * Return values:
298 *  X509_V_OK: All constraints obeyed.
299 *  X509_V_ERR_PERMITTED_VIOLATION: Permitted subtree violation.
300 *  X509_V_ERR_EXCLUDED_VIOLATION: Excluded subtree violation.
301 *  X509_V_ERR_SUBTREE_MINMAX: Min or max values present and matching type.
302 *  X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE:  Unsupported constraint type.
303 *  X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX: bad unsupported constraint syntax.
304 *  X509_V_ERR_UNSUPPORTED_NAME_SYNTAX: bad or unsupported syntax of name
305 */
306
307int
308NAME_CONSTRAINTS_check(X509 *x, NAME_CONSTRAINTS *nc)
309{
310	int r, i;
311	X509_NAME *nm;
312
313	nm = X509_get_subject_name(x);
314
315	if (X509_NAME_entry_count(nm) > 0) {
316		GENERAL_NAME gntmp;
317		gntmp.type = GEN_DIRNAME;
318		gntmp.d.directoryName = nm;
319
320		r = nc_match(&gntmp, nc);
321
322		if (r != X509_V_OK)
323			return r;
324
325		gntmp.type = GEN_EMAIL;
326
327		/* Process any email address attributes in subject name */
328
329		for (i = -1;;) {
330			X509_NAME_ENTRY *ne;
331			i = X509_NAME_get_index_by_NID(nm,
332			    NID_pkcs9_emailAddress, i);
333			if (i == -1)
334				break;
335			ne = X509_NAME_get_entry(nm, i);
336			gntmp.d.rfc822Name = X509_NAME_ENTRY_get_data(ne);
337			if (gntmp.d.rfc822Name->type != V_ASN1_IA5STRING)
338				return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
339
340			r = nc_match(&gntmp, nc);
341
342			if (r != X509_V_OK)
343				return r;
344		}
345
346	}
347
348	for (i = 0; i < sk_GENERAL_NAME_num(x->altname); i++) {
349		GENERAL_NAME *gen = sk_GENERAL_NAME_value(x->altname, i);
350		r = nc_match(gen, nc);
351		if (r != X509_V_OK)
352			return r;
353	}
354	return X509_V_OK;
355}
356LCRYPTO_ALIAS(NAME_CONSTRAINTS_check);
357static int
358nc_match(GENERAL_NAME *gen, NAME_CONSTRAINTS *nc)
359{
360	GENERAL_SUBTREE *sub;
361	int i, r, match = 0;
362
363	/* Permitted subtrees: if any subtrees exist of matching the type
364	 * at least one subtree must match.
365	 */
366
367	for (i = 0; i < sk_GENERAL_SUBTREE_num(nc->permittedSubtrees); i++) {
368		sub = sk_GENERAL_SUBTREE_value(nc->permittedSubtrees, i);
369		if (gen->type != sub->base->type)
370			continue;
371		if (sub->minimum || sub->maximum)
372			return X509_V_ERR_SUBTREE_MINMAX;
373		/* If we already have a match don't bother trying any more */
374		if (match == 2)
375			continue;
376		if (match == 0)
377			match = 1;
378		r = nc_match_single(gen, sub->base);
379		if (r == X509_V_OK)
380			match = 2;
381		else if (r != X509_V_ERR_PERMITTED_VIOLATION)
382			return r;
383	}
384
385	if (match == 1)
386		return X509_V_ERR_PERMITTED_VIOLATION;
387
388	/* Excluded subtrees: must not match any of these */
389
390	for (i = 0; i < sk_GENERAL_SUBTREE_num(nc->excludedSubtrees); i++) {
391		sub = sk_GENERAL_SUBTREE_value(nc->excludedSubtrees, i);
392		if (gen->type != sub->base->type)
393			continue;
394		if (sub->minimum || sub->maximum)
395			return X509_V_ERR_SUBTREE_MINMAX;
396
397		r = nc_match_single(gen, sub->base);
398		if (r == X509_V_OK)
399			return X509_V_ERR_EXCLUDED_VIOLATION;
400		else if (r != X509_V_ERR_PERMITTED_VIOLATION)
401			return r;
402
403	}
404
405	return X509_V_OK;
406}
407
408static int
409nc_match_single(GENERAL_NAME *gen, GENERAL_NAME *base)
410{
411	switch (base->type) {
412	case GEN_DIRNAME:
413		return nc_dn(gen->d.directoryName, base->d.directoryName);
414
415	case GEN_DNS:
416		return nc_dns(gen->d.dNSName, base->d.dNSName);
417
418	case GEN_EMAIL:
419		return nc_email(gen->d.rfc822Name, base->d.rfc822Name);
420
421	case GEN_URI:
422		return nc_uri(gen->d.uniformResourceIdentifier,
423		    base->d.uniformResourceIdentifier);
424
425	default:
426		return X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE;
427	}
428}
429
430/* directoryName name constraint matching.
431 * The canonical encoding of X509_NAME makes this comparison easy. It is
432 * matched if the subtree is a subset of the name.
433 */
434
435static int
436nc_dn(X509_NAME *nm, X509_NAME *base)
437{
438	/* Ensure canonical encodings are up to date.  */
439	if (nm->modified && i2d_X509_NAME(nm, NULL) < 0)
440		return X509_V_ERR_OUT_OF_MEM;
441	if (base->modified && i2d_X509_NAME(base, NULL) < 0)
442		return X509_V_ERR_OUT_OF_MEM;
443	if (base->canon_enclen > nm->canon_enclen)
444		return X509_V_ERR_PERMITTED_VIOLATION;
445	if (memcmp(base->canon_enc, nm->canon_enc, base->canon_enclen))
446		return X509_V_ERR_PERMITTED_VIOLATION;
447	return X509_V_OK;
448}
449
450static int
451nc_dns(ASN1_IA5STRING *dns, ASN1_IA5STRING *base)
452{
453	char *baseptr = (char *)base->data;
454	char *dnsptr = (char *)dns->data;
455
456	/* Empty matches everything */
457	if (!*baseptr)
458		return X509_V_OK;
459	/* Otherwise can add zero or more components on the left so
460	 * compare RHS and if dns is longer and expect '.' as preceding
461	 * character.
462	 */
463	if (dns->length > base->length) {
464		dnsptr += dns->length - base->length;
465		if (baseptr[0] != '.' && dnsptr[-1] != '.')
466			return X509_V_ERR_PERMITTED_VIOLATION;
467	}
468
469	if (strcasecmp(baseptr, dnsptr))
470		return X509_V_ERR_PERMITTED_VIOLATION;
471
472	return X509_V_OK;
473}
474
475static int
476nc_email(ASN1_IA5STRING *eml, ASN1_IA5STRING *base)
477{
478	const char *baseptr = (char *)base->data;
479	const char *emlptr = (char *)eml->data;
480	const char *baseat = strchr(baseptr, '@');
481	const char *emlat = strchr(emlptr, '@');
482
483	if (!emlat)
484		return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
485	/* Special case: initial '.' is RHS match */
486	if (!baseat && (*baseptr == '.')) {
487		if (eml->length > base->length) {
488			emlptr += eml->length - base->length;
489			if (!strcasecmp(baseptr, emlptr))
490				return X509_V_OK;
491		}
492		return X509_V_ERR_PERMITTED_VIOLATION;
493	}
494
495	/* If we have anything before '@' match local part */
496
497	if (baseat) {
498		if (baseat != baseptr) {
499			if ((baseat - baseptr) != (emlat - emlptr))
500				return X509_V_ERR_PERMITTED_VIOLATION;
501			/* Case sensitive match of local part */
502			if (strncmp(baseptr, emlptr, emlat - emlptr))
503				return X509_V_ERR_PERMITTED_VIOLATION;
504		}
505		/* Position base after '@' */
506		baseptr = baseat + 1;
507	}
508	emlptr = emlat + 1;
509	/* Just have hostname left to match: case insensitive */
510	if (strcasecmp(baseptr, emlptr))
511		return X509_V_ERR_PERMITTED_VIOLATION;
512
513	return X509_V_OK;
514}
515
516static int
517nc_uri(ASN1_IA5STRING *uri, ASN1_IA5STRING *base)
518{
519	const char *baseptr = (char *)base->data;
520	const char *hostptr = (char *)uri->data;
521	const char *p = strchr(hostptr, ':');
522	int hostlen;
523
524	/* Check for foo:// and skip past it */
525	if (!p || (p[1] != '/') || (p[2] != '/'))
526		return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
527	hostptr = p + 3;
528
529	/* Determine length of hostname part of URI */
530
531	/* Look for a port indicator as end of hostname first */
532
533	p = strchr(hostptr, ':');
534	/* Otherwise look for trailing slash */
535	if (!p)
536		p = strchr(hostptr, '/');
537
538	if (!p)
539		hostlen = strlen(hostptr);
540	else
541		hostlen = p - hostptr;
542
543	if (hostlen == 0)
544		return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
545
546	/* Special case: initial '.' is RHS match */
547	if (*baseptr == '.') {
548		if (hostlen > base->length) {
549			p = hostptr + hostlen - base->length;
550			if (!strncasecmp(p, baseptr, base->length))
551				return X509_V_OK;
552		}
553		return X509_V_ERR_PERMITTED_VIOLATION;
554	}
555
556	if ((base->length != (int)hostlen) ||
557	    strncasecmp(hostptr, baseptr, hostlen))
558		return X509_V_ERR_PERMITTED_VIOLATION;
559
560	return X509_V_OK;
561}
562