xref: /openbsd/lib/libcrypto/x509/x509_addr.c (revision 8b5faa71)
1 /*	$OpenBSD: x509_addr.c,v 1.93 2024/07/13 15:08:58 tb Exp $ */
2 /*
3  * Contributed to the OpenSSL Project by the American Registry for
4  * Internet Numbers ("ARIN").
5  */
6 /* ====================================================================
7  * Copyright (c) 2006-2016 The OpenSSL Project.  All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in
18  *    the documentation and/or other materials provided with the
19  *    distribution.
20  *
21  * 3. All advertising materials mentioning features or use of this
22  *    software must display the following acknowledgment:
23  *    "This product includes software developed by the OpenSSL Project
24  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
25  *
26  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
27  *    endorse or promote products derived from this software without
28  *    prior written permission. For written permission, please contact
29  *    licensing@OpenSSL.org.
30  *
31  * 5. Products derived from this software may not be called "OpenSSL"
32  *    nor may "OpenSSL" appear in their names without prior written
33  *    permission of the OpenSSL Project.
34  *
35  * 6. Redistributions of any form whatsoever must retain the following
36  *    acknowledgment:
37  *    "This product includes software developed by the OpenSSL Project
38  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
41  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
43  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
44  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
45  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
46  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
47  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
49  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
50  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
51  * OF THE POSSIBILITY OF SUCH DAMAGE.
52  * ====================================================================
53  *
54  * This product includes cryptographic software written by Eric Young
55  * (eay@cryptsoft.com).  This product includes software written by Tim
56  * Hudson (tjh@cryptsoft.com).
57  */
58 
59 /*
60  * Implementation of RFC 3779 section 2.2.
61  */
62 
63 #include <limits.h>
64 #include <stdio.h>
65 #include <stdlib.h>
66 #include <string.h>
67 
68 #include <openssl/asn1.h>
69 #include <openssl/asn1t.h>
70 #include <openssl/buffer.h>
71 #include <openssl/conf.h>
72 #include <openssl/err.h>
73 #include <openssl/x509.h>
74 #include <openssl/x509v3.h>
75 
76 #include "asn1_local.h"
77 #include "bytestring.h"
78 #include "x509_local.h"
79 
80 #ifndef OPENSSL_NO_RFC3779
81 
82 /*
83  * OpenSSL ASN.1 template translation of RFC 3779 2.2.3.
84  */
85 
86 static const ASN1_TEMPLATE IPAddressRange_seq_tt[] = {
87 	{
88 		.flags = 0,
89 		.tag = 0,
90 		.offset = offsetof(IPAddressRange, min),
91 		.field_name = "min",
92 		.item = &ASN1_BIT_STRING_it,
93 	},
94 	{
95 		.flags = 0,
96 		.tag = 0,
97 		.offset = offsetof(IPAddressRange, max),
98 		.field_name = "max",
99 		.item = &ASN1_BIT_STRING_it,
100 	},
101 };
102 
103 const ASN1_ITEM IPAddressRange_it = {
104 	.itype = ASN1_ITYPE_SEQUENCE,
105 	.utype = V_ASN1_SEQUENCE,
106 	.templates = IPAddressRange_seq_tt,
107 	.tcount = sizeof(IPAddressRange_seq_tt) / sizeof(ASN1_TEMPLATE),
108 	.funcs = NULL,
109 	.size = sizeof(IPAddressRange),
110 	.sname = "IPAddressRange",
111 };
112 LCRYPTO_ALIAS(IPAddressRange_it);
113 
114 static const ASN1_TEMPLATE IPAddressOrRange_ch_tt[] = {
115 	{
116 		.flags = 0,
117 		.tag = 0,
118 		.offset = offsetof(IPAddressOrRange, u.addressPrefix),
119 		.field_name = "u.addressPrefix",
120 		.item = &ASN1_BIT_STRING_it,
121 	},
122 	{
123 		.flags = 0,
124 		.tag = 0,
125 		.offset = offsetof(IPAddressOrRange, u.addressRange),
126 		.field_name = "u.addressRange",
127 		.item = &IPAddressRange_it,
128 	},
129 };
130 
131 const ASN1_ITEM IPAddressOrRange_it = {
132 	.itype = ASN1_ITYPE_CHOICE,
133 	.utype = offsetof(IPAddressOrRange, type),
134 	.templates = IPAddressOrRange_ch_tt,
135 	.tcount = sizeof(IPAddressOrRange_ch_tt) / sizeof(ASN1_TEMPLATE),
136 	.funcs = NULL,
137 	.size = sizeof(IPAddressOrRange),
138 	.sname = "IPAddressOrRange",
139 };
140 LCRYPTO_ALIAS(IPAddressOrRange_it);
141 
142 static const ASN1_TEMPLATE IPAddressChoice_ch_tt[] = {
143 	{
144 		.flags = 0,
145 		.tag = 0,
146 		.offset = offsetof(IPAddressChoice, u.inherit),
147 		.field_name = "u.inherit",
148 		.item = &ASN1_NULL_it,
149 	},
150 	{
151 		.flags = ASN1_TFLG_SEQUENCE_OF,
152 		.tag = 0,
153 		.offset = offsetof(IPAddressChoice, u.addressesOrRanges),
154 		.field_name = "u.addressesOrRanges",
155 		.item = &IPAddressOrRange_it,
156 	},
157 };
158 
159 const ASN1_ITEM IPAddressChoice_it = {
160 	.itype = ASN1_ITYPE_CHOICE,
161 	.utype = offsetof(IPAddressChoice, type),
162 	.templates = IPAddressChoice_ch_tt,
163 	.tcount = sizeof(IPAddressChoice_ch_tt) / sizeof(ASN1_TEMPLATE),
164 	.funcs = NULL,
165 	.size = sizeof(IPAddressChoice),
166 	.sname = "IPAddressChoice",
167 };
168 LCRYPTO_ALIAS(IPAddressChoice_it);
169 
170 static const ASN1_TEMPLATE IPAddressFamily_seq_tt[] = {
171 	{
172 		.flags = 0,
173 		.tag = 0,
174 		.offset = offsetof(IPAddressFamily, addressFamily),
175 		.field_name = "addressFamily",
176 		.item = &ASN1_OCTET_STRING_it,
177 	},
178 	{
179 		.flags = 0,
180 		.tag = 0,
181 		.offset = offsetof(IPAddressFamily, ipAddressChoice),
182 		.field_name = "ipAddressChoice",
183 		.item = &IPAddressChoice_it,
184 	},
185 };
186 
187 const ASN1_ITEM IPAddressFamily_it = {
188 	.itype = ASN1_ITYPE_SEQUENCE,
189 	.utype = V_ASN1_SEQUENCE,
190 	.templates = IPAddressFamily_seq_tt,
191 	.tcount = sizeof(IPAddressFamily_seq_tt) / sizeof(ASN1_TEMPLATE),
192 	.funcs = NULL,
193 	.size = sizeof(IPAddressFamily),
194 	.sname = "IPAddressFamily",
195 };
196 LCRYPTO_ALIAS(IPAddressFamily_it);
197 
198 static const ASN1_TEMPLATE IPAddrBlocks_item_tt = {
199 	.flags = ASN1_TFLG_SEQUENCE_OF,
200 	.tag = 0,
201 	.offset = 0,
202 	.field_name = "IPAddrBlocks",
203 	.item = &IPAddressFamily_it,
204 };
205 
206 static const ASN1_ITEM IPAddrBlocks_it = {
207 	.itype = ASN1_ITYPE_PRIMITIVE,
208 	.utype = -1,
209 	.templates = &IPAddrBlocks_item_tt,
210 	.tcount = 0,
211 	.funcs = NULL,
212 	.size = 0,
213 	.sname = "IPAddrBlocks",
214 };
215 
216 IPAddressRange *
d2i_IPAddressRange(IPAddressRange ** a,const unsigned char ** in,long len)217 d2i_IPAddressRange(IPAddressRange **a, const unsigned char **in, long len)
218 {
219 	return (IPAddressRange *)ASN1_item_d2i((ASN1_VALUE **)a, in, len,
220 	    &IPAddressRange_it);
221 }
222 LCRYPTO_ALIAS(d2i_IPAddressRange);
223 
224 int
i2d_IPAddressRange(IPAddressRange * a,unsigned char ** out)225 i2d_IPAddressRange(IPAddressRange *a, unsigned char **out)
226 {
227 	return ASN1_item_i2d((ASN1_VALUE *)a, out, &IPAddressRange_it);
228 }
229 LCRYPTO_ALIAS(i2d_IPAddressRange);
230 
231 IPAddressRange *
IPAddressRange_new(void)232 IPAddressRange_new(void)
233 {
234 	return (IPAddressRange *)ASN1_item_new(&IPAddressRange_it);
235 }
236 LCRYPTO_ALIAS(IPAddressRange_new);
237 
238 void
IPAddressRange_free(IPAddressRange * a)239 IPAddressRange_free(IPAddressRange *a)
240 {
241 	ASN1_item_free((ASN1_VALUE *)a, &IPAddressRange_it);
242 }
243 LCRYPTO_ALIAS(IPAddressRange_free);
244 
245 IPAddressOrRange *
d2i_IPAddressOrRange(IPAddressOrRange ** a,const unsigned char ** in,long len)246 d2i_IPAddressOrRange(IPAddressOrRange **a, const unsigned char **in, long len)
247 {
248 	return (IPAddressOrRange *)ASN1_item_d2i((ASN1_VALUE **)a, in, len,
249 	    &IPAddressOrRange_it);
250 }
251 LCRYPTO_ALIAS(d2i_IPAddressOrRange);
252 
253 int
i2d_IPAddressOrRange(IPAddressOrRange * a,unsigned char ** out)254 i2d_IPAddressOrRange(IPAddressOrRange *a, unsigned char **out)
255 {
256 	return ASN1_item_i2d((ASN1_VALUE *)a, out, &IPAddressOrRange_it);
257 }
258 LCRYPTO_ALIAS(i2d_IPAddressOrRange);
259 
260 IPAddressOrRange *
IPAddressOrRange_new(void)261 IPAddressOrRange_new(void)
262 {
263 	return (IPAddressOrRange *)ASN1_item_new(&IPAddressOrRange_it);
264 }
265 LCRYPTO_ALIAS(IPAddressOrRange_new);
266 
267 void
IPAddressOrRange_free(IPAddressOrRange * a)268 IPAddressOrRange_free(IPAddressOrRange *a)
269 {
270 	ASN1_item_free((ASN1_VALUE *)a, &IPAddressOrRange_it);
271 }
272 LCRYPTO_ALIAS(IPAddressOrRange_free);
273 
274 IPAddressChoice *
d2i_IPAddressChoice(IPAddressChoice ** a,const unsigned char ** in,long len)275 d2i_IPAddressChoice(IPAddressChoice **a, const unsigned char **in, long len)
276 {
277 	return (IPAddressChoice *)ASN1_item_d2i((ASN1_VALUE **)a, in, len,
278 	    &IPAddressChoice_it);
279 }
280 LCRYPTO_ALIAS(d2i_IPAddressChoice);
281 
282 int
i2d_IPAddressChoice(IPAddressChoice * a,unsigned char ** out)283 i2d_IPAddressChoice(IPAddressChoice *a, unsigned char **out)
284 {
285 	return ASN1_item_i2d((ASN1_VALUE *)a, out, &IPAddressChoice_it);
286 }
287 LCRYPTO_ALIAS(i2d_IPAddressChoice);
288 
289 IPAddressChoice *
IPAddressChoice_new(void)290 IPAddressChoice_new(void)
291 {
292 	return (IPAddressChoice *)ASN1_item_new(&IPAddressChoice_it);
293 }
294 LCRYPTO_ALIAS(IPAddressChoice_new);
295 
296 void
IPAddressChoice_free(IPAddressChoice * a)297 IPAddressChoice_free(IPAddressChoice *a)
298 {
299 	ASN1_item_free((ASN1_VALUE *)a, &IPAddressChoice_it);
300 }
301 LCRYPTO_ALIAS(IPAddressChoice_free);
302 
303 IPAddressFamily *
d2i_IPAddressFamily(IPAddressFamily ** a,const unsigned char ** in,long len)304 d2i_IPAddressFamily(IPAddressFamily **a, const unsigned char **in, long len)
305 {
306 	return (IPAddressFamily *)ASN1_item_d2i((ASN1_VALUE **)a, in, len,
307 	    &IPAddressFamily_it);
308 }
309 LCRYPTO_ALIAS(d2i_IPAddressFamily);
310 
311 int
i2d_IPAddressFamily(IPAddressFamily * a,unsigned char ** out)312 i2d_IPAddressFamily(IPAddressFamily *a, unsigned char **out)
313 {
314 	return ASN1_item_i2d((ASN1_VALUE *)a, out, &IPAddressFamily_it);
315 }
316 LCRYPTO_ALIAS(i2d_IPAddressFamily);
317 
318 IPAddressFamily *
IPAddressFamily_new(void)319 IPAddressFamily_new(void)
320 {
321 	return (IPAddressFamily *)ASN1_item_new(&IPAddressFamily_it);
322 }
323 LCRYPTO_ALIAS(IPAddressFamily_new);
324 
325 void
IPAddressFamily_free(IPAddressFamily * a)326 IPAddressFamily_free(IPAddressFamily *a)
327 {
328 	ASN1_item_free((ASN1_VALUE *)a, &IPAddressFamily_it);
329 }
330 LCRYPTO_ALIAS(IPAddressFamily_free);
331 
332 /*
333  * Convenience accessors for IPAddressFamily.
334  */
335 
336 static int
IPAddressFamily_type(IPAddressFamily * af)337 IPAddressFamily_type(IPAddressFamily *af)
338 {
339 	/* XXX - can af->ipAddressChoice == NULL actually happen? */
340 	if (af == NULL || af->ipAddressChoice == NULL)
341 		return -1;
342 
343 	switch (af->ipAddressChoice->type) {
344 	case IPAddressChoice_inherit:
345 	case IPAddressChoice_addressesOrRanges:
346 		return af->ipAddressChoice->type;
347 	default:
348 		return -1;
349 	}
350 }
351 
352 static IPAddressOrRanges *
IPAddressFamily_addressesOrRanges(IPAddressFamily * af)353 IPAddressFamily_addressesOrRanges(IPAddressFamily *af)
354 {
355 	if (IPAddressFamily_type(af) == IPAddressChoice_addressesOrRanges)
356 		return af->ipAddressChoice->u.addressesOrRanges;
357 
358 	return NULL;
359 }
360 
361 static ASN1_NULL *
IPAddressFamily_inheritance(IPAddressFamily * af)362 IPAddressFamily_inheritance(IPAddressFamily *af)
363 {
364 	if (IPAddressFamily_type(af) == IPAddressChoice_inherit)
365 		return af->ipAddressChoice->u.inherit;
366 
367 	return NULL;
368 }
369 
370 static int
IPAddressFamily_set_inheritance(IPAddressFamily * af)371 IPAddressFamily_set_inheritance(IPAddressFamily *af)
372 {
373 	if (IPAddressFamily_addressesOrRanges(af) != NULL)
374 		return 0;
375 
376 	if (IPAddressFamily_inheritance(af) != NULL)
377 		return 1;
378 
379 	if ((af->ipAddressChoice->u.inherit = ASN1_NULL_new()) == NULL)
380 		return 0;
381 	af->ipAddressChoice->type = IPAddressChoice_inherit;
382 
383 	return 1;
384 }
385 
386 /*
387  * How much buffer space do we need for a raw address?
388  */
389 #define ADDR_RAW_BUF_LEN        16
390 
391 /*
392  * What's the address length associated with this AFI?
393  */
394 static int
length_from_afi(const unsigned afi,int * length)395 length_from_afi(const unsigned afi, int *length)
396 {
397 	switch (afi) {
398 	case IANA_AFI_IPV4:
399 		*length = 4;
400 		return 1;
401 	case IANA_AFI_IPV6:
402 		*length = 16;
403 		return 1;
404 	default:
405 		*length = 0;
406 		return 0;
407 	}
408 }
409 
410 /*
411  * Get AFI and optional SAFI from an IPAddressFamily. All three out arguments
412  * are optional; if |out_safi| is non-NULL, |safi_is_set| must be non-NULL.
413  */
414 static int
IPAddressFamily_afi_safi(const IPAddressFamily * af,uint16_t * out_afi,uint8_t * out_safi,int * safi_is_set)415 IPAddressFamily_afi_safi(const IPAddressFamily *af, uint16_t *out_afi,
416     uint8_t *out_safi, int *safi_is_set)
417 {
418 	CBS cbs;
419 	uint16_t afi;
420 	uint8_t safi = 0;
421 	int got_safi = 0;
422 
423 	if (out_afi != NULL)
424 		*out_afi = 0;
425 	if (out_safi != NULL) {
426 		*out_safi = 0;
427 		*safi_is_set = 0;
428 	}
429 
430 	CBS_init(&cbs, af->addressFamily->data, af->addressFamily->length);
431 
432 	if (!CBS_get_u16(&cbs, &afi))
433 		return 0;
434 
435 	if (afi != IANA_AFI_IPV4 && afi != IANA_AFI_IPV6)
436 		return 0;
437 
438 	/* Fetch the optional SAFI. */
439 	if (CBS_len(&cbs) != 0) {
440 		if (!CBS_get_u8(&cbs, &safi))
441 			return 0;
442 		got_safi = 1;
443 	}
444 
445 	/* If there's anything left, it's garbage. */
446 	if (CBS_len(&cbs) != 0)
447 		return 0;
448 
449 	/* XXX - error on reserved AFI/SAFI? */
450 
451 	if (out_afi != NULL)
452 		*out_afi = afi;
453 
454 	if (out_safi != NULL) {
455 		*out_safi = safi;
456 		*safi_is_set = got_safi;
457 	}
458 
459 	return 1;
460 }
461 
462 static int
IPAddressFamily_afi(const IPAddressFamily * af,uint16_t * out_afi)463 IPAddressFamily_afi(const IPAddressFamily *af, uint16_t *out_afi)
464 {
465 	return IPAddressFamily_afi_safi(af, out_afi, NULL, NULL);
466 }
467 
468 static int
IPAddressFamily_afi_is_valid(const IPAddressFamily * af)469 IPAddressFamily_afi_is_valid(const IPAddressFamily *af)
470 {
471 	return IPAddressFamily_afi_safi(af, NULL, NULL, NULL);
472 }
473 
474 static int
IPAddressFamily_afi_length(const IPAddressFamily * af,int * out_length)475 IPAddressFamily_afi_length(const IPAddressFamily *af, int *out_length)
476 {
477 	uint16_t afi;
478 
479 	*out_length = 0;
480 
481 	if (!IPAddressFamily_afi(af, &afi))
482 		return 0;
483 
484 	return length_from_afi(afi, out_length);
485 }
486 
487 #define MINIMUM(a, b) (((a) < (b)) ? (a) : (b))
488 
489 /*
490  * Sort comparison function for a sequence of IPAddressFamily.
491  *
492  * The last paragraph of RFC 3779 2.2.3.3 is slightly ambiguous about
493  * the ordering: I can read it as meaning that IPv6 without a SAFI
494  * comes before IPv4 with a SAFI, which seems pretty weird.  The
495  * examples in appendix B suggest that the author intended the
496  * null-SAFI rule to apply only within a single AFI, which is what I
497  * would have expected and is what the following code implements.
498  */
499 static int
IPAddressFamily_cmp(const IPAddressFamily * const * a_,const IPAddressFamily * const * b_)500 IPAddressFamily_cmp(const IPAddressFamily *const *a_,
501     const IPAddressFamily *const *b_)
502 {
503 	const ASN1_OCTET_STRING *a = (*a_)->addressFamily;
504 	const ASN1_OCTET_STRING *b = (*b_)->addressFamily;
505 	int len, cmp;
506 
507 	len = MINIMUM(a->length, b->length);
508 
509 	if ((cmp = memcmp(a->data, b->data, len)) != 0)
510 		return cmp;
511 
512 	return a->length - b->length;
513 }
514 
515 static IPAddressFamily *
IPAddressFamily_find_in_parent(IPAddrBlocks * parent,IPAddressFamily * child_af)516 IPAddressFamily_find_in_parent(IPAddrBlocks *parent, IPAddressFamily *child_af)
517 {
518 	int index;
519 
520 	(void)sk_IPAddressFamily_set_cmp_func(parent, IPAddressFamily_cmp);
521 
522 	if ((index = sk_IPAddressFamily_find(parent, child_af)) < 0)
523 		return NULL;
524 
525 	return sk_IPAddressFamily_value(parent, index);
526 }
527 
528 /*
529  * Extract the AFI from an IPAddressFamily.
530  *
531  * This is public API. It uses the reserved AFI 0 as an in-band error
532  * while it doesn't care about the reserved AFI 65535...
533  */
534 unsigned int
X509v3_addr_get_afi(const IPAddressFamily * af)535 X509v3_addr_get_afi(const IPAddressFamily *af)
536 {
537 	uint16_t afi;
538 
539 	/*
540 	 * XXX are these NULL checks really sensible? If af is non-NULL, it
541 	 * should have both addressFamily and ipAddressChoice...
542 	 */
543 	if (af == NULL || af->addressFamily == NULL ||
544 	    af->addressFamily->data == NULL)
545 		return 0;
546 
547 	if (!IPAddressFamily_afi(af, &afi))
548 		return 0;
549 
550 	return afi;
551 }
552 LCRYPTO_ALIAS(X509v3_addr_get_afi);
553 
554 /*
555  * Expand the bitstring form (RFC 3779, section 2.1.2) of an address into
556  * a raw byte array.  At the moment this is coded for simplicity, not speed.
557  *
558  * Unused bits in the last octet of |bs| and all bits in subsequent bytes
559  * of |addr| are set to 0 or 1 depending on whether |fill| is 0 or not.
560  */
561 static int
addr_expand(unsigned char * addr,const ASN1_BIT_STRING * bs,const int length,uint8_t fill)562 addr_expand(unsigned char *addr, const ASN1_BIT_STRING *bs, const int length,
563     uint8_t fill)
564 {
565 	if (bs->length < 0 || bs->length > length)
566 		return 0;
567 
568 	if (fill != 0)
569 		fill = 0xff;
570 
571 	if (bs->length > 0) {
572 		/* XXX - shouldn't this check ASN1_STRING_FLAG_BITS_LEFT? */
573 		uint8_t unused_bits = bs->flags & 7;
574 		uint8_t mask = (1 << unused_bits) - 1;
575 
576 		memcpy(addr, bs->data, bs->length);
577 
578 		if (fill == 0)
579 			addr[bs->length - 1] &= ~mask;
580 		else
581 			addr[bs->length - 1] |= mask;
582 	}
583 
584 	memset(addr + bs->length, fill, length - bs->length);
585 
586 	return 1;
587 }
588 
589 /*
590  * Extract the prefix length from a bitstring: 8 * length - unused bits.
591  */
592 #define addr_prefix_len(bs) ((int) ((bs)->length * 8 - ((bs)->flags & 7)))
593 
594 /*
595  * i2r handler for one address bitstring.
596  */
597 static int
i2r_address(BIO * out,const unsigned afi,const unsigned char fill,const ASN1_BIT_STRING * bs)598 i2r_address(BIO *out, const unsigned afi, const unsigned char fill,
599     const ASN1_BIT_STRING *bs)
600 {
601 	unsigned char addr[ADDR_RAW_BUF_LEN];
602 	int i, n;
603 
604 	if (bs->length < 0)
605 		return 0;
606 	switch (afi) {
607 	case IANA_AFI_IPV4:
608 		if (!addr_expand(addr, bs, 4, fill))
609 			return 0;
610 		BIO_printf(out, "%d.%d.%d.%d", addr[0], addr[1], addr[2],
611 		    addr[3]);
612 		break;
613 	case IANA_AFI_IPV6:
614 		if (!addr_expand(addr, bs, 16, fill))
615 			return 0;
616 		for (n = 16;
617 		    n > 1 && addr[n - 1] == 0x00 && addr[n - 2] == 0x00; n -= 2)
618 			continue;
619 		for (i = 0; i < n; i += 2)
620 			BIO_printf(out, "%x%s", (addr[i] << 8) | addr[i + 1],
621 			    (i < 14 ? ":" : ""));
622 		if (i < 16)
623 			BIO_puts(out, ":");
624 		if (i == 0)
625 			BIO_puts(out, ":");
626 		break;
627 	default:
628 		for (i = 0; i < bs->length; i++)
629 			BIO_printf(out, "%s%02x", (i > 0 ? ":" : ""),
630 			    bs->data[i]);
631 		BIO_printf(out, "[%d]", (int)(bs->flags & 7));
632 		break;
633 	}
634 	return 1;
635 }
636 
637 /*
638  * i2r handler for a sequence of addresses and ranges.
639  */
640 static int
i2r_IPAddressOrRanges(BIO * out,const int indent,const IPAddressOrRanges * aors,const unsigned afi)641 i2r_IPAddressOrRanges(BIO *out, const int indent,
642     const IPAddressOrRanges *aors, const unsigned afi)
643 {
644 	const IPAddressOrRange *aor;
645 	const ASN1_BIT_STRING *prefix;
646 	const IPAddressRange *range;
647 	int i;
648 
649 	for (i = 0; i < sk_IPAddressOrRange_num(aors); i++) {
650 		aor = sk_IPAddressOrRange_value(aors, i);
651 
652 		BIO_printf(out, "%*s", indent, "");
653 
654 		switch (aor->type) {
655 		case IPAddressOrRange_addressPrefix:
656 			prefix = aor->u.addressPrefix;
657 
658 			if (!i2r_address(out, afi, 0x00, prefix))
659 				return 0;
660 			BIO_printf(out, "/%d\n", addr_prefix_len(prefix));
661 			continue;
662 		case IPAddressOrRange_addressRange:
663 			range = aor->u.addressRange;
664 
665 			if (!i2r_address(out, afi, 0x00, range->min))
666 				return 0;
667 			BIO_puts(out, "-");
668 			if (!i2r_address(out, afi, 0xff, range->max))
669 				return 0;
670 			BIO_puts(out, "\n");
671 			continue;
672 		}
673 	}
674 
675 	return 1;
676 }
677 
678 /*
679  * i2r handler for an IPAddrBlocks extension.
680  */
681 static int
i2r_IPAddrBlocks(const X509V3_EXT_METHOD * method,void * ext,BIO * out,int indent)682 i2r_IPAddrBlocks(const X509V3_EXT_METHOD *method, void *ext, BIO *out,
683     int indent)
684 {
685 	const IPAddrBlocks *addr = ext;
686 	IPAddressFamily *af;
687 	uint16_t afi;
688 	uint8_t safi;
689 	int i, safi_is_set;
690 
691 	for (i = 0; i < sk_IPAddressFamily_num(addr); i++) {
692 		af = sk_IPAddressFamily_value(addr, i);
693 
694 		if (!IPAddressFamily_afi_safi(af, &afi, &safi, &safi_is_set))
695 			goto print_addresses;
696 
697 		switch (afi) {
698 		case IANA_AFI_IPV4:
699 			BIO_printf(out, "%*sIPv4", indent, "");
700 			break;
701 		case IANA_AFI_IPV6:
702 			BIO_printf(out, "%*sIPv6", indent, "");
703 			break;
704 		default:
705 			BIO_printf(out, "%*sUnknown AFI %u", indent, "", afi);
706 			break;
707 		}
708 		if (safi_is_set) {
709 			switch (safi) {
710 			case 1:
711 				BIO_puts(out, " (Unicast)");
712 				break;
713 			case 2:
714 				BIO_puts(out, " (Multicast)");
715 				break;
716 			case 3:
717 				BIO_puts(out, " (Unicast/Multicast)");
718 				break;
719 			case 4:
720 				BIO_puts(out, " (MPLS)");
721 				break;
722 			case 64:
723 				BIO_puts(out, " (Tunnel)");
724 				break;
725 			case 65:
726 				BIO_puts(out, " (VPLS)");
727 				break;
728 			case 66:
729 				BIO_puts(out, " (BGP MDT)");
730 				break;
731 			case 128:
732 				BIO_puts(out, " (MPLS-labeled VPN)");
733 				break;
734 			default:
735 				BIO_printf(out, " (Unknown SAFI %u)", safi);
736 				break;
737 			}
738 		}
739 
740  print_addresses:
741 		switch (IPAddressFamily_type(af)) {
742 		case IPAddressChoice_inherit:
743 			BIO_puts(out, ": inherit\n");
744 			break;
745 		case IPAddressChoice_addressesOrRanges:
746 			BIO_puts(out, ":\n");
747 			if (!i2r_IPAddressOrRanges(out, indent + 2,
748 			    IPAddressFamily_addressesOrRanges(af), afi))
749 				return 0;
750 			break;
751 		/* XXX - how should we handle -1 here? */
752 		}
753 	}
754 	return 1;
755 }
756 
757 /*
758  * Sort comparison function for a sequence of IPAddressOrRange
759  * elements.
760  *
761  * There's no sane answer we can give if addr_expand() fails, and an
762  * assertion failure on externally supplied data is seriously uncool,
763  * so we just arbitrarily declare that if given invalid inputs this
764  * function returns -1.  If this messes up your preferred sort order
765  * for garbage input, tough noogies.
766  */
767 static int
IPAddressOrRange_cmp(const IPAddressOrRange * a,const IPAddressOrRange * b,const int length)768 IPAddressOrRange_cmp(const IPAddressOrRange *a, const IPAddressOrRange *b,
769     const int length)
770 {
771 	unsigned char addr_a[ADDR_RAW_BUF_LEN], addr_b[ADDR_RAW_BUF_LEN];
772 	int prefix_len_a = 0, prefix_len_b = 0;
773 	int r;
774 
775 	switch (a->type) {
776 	case IPAddressOrRange_addressPrefix:
777 		if (!addr_expand(addr_a, a->u.addressPrefix, length, 0x00))
778 			return -1;
779 		prefix_len_a = addr_prefix_len(a->u.addressPrefix);
780 		break;
781 	case IPAddressOrRange_addressRange:
782 		if (!addr_expand(addr_a, a->u.addressRange->min, length, 0x00))
783 			return -1;
784 		prefix_len_a = length * 8;
785 		break;
786 	}
787 
788 	switch (b->type) {
789 	case IPAddressOrRange_addressPrefix:
790 		if (!addr_expand(addr_b, b->u.addressPrefix, length, 0x00))
791 			return -1;
792 		prefix_len_b = addr_prefix_len(b->u.addressPrefix);
793 		break;
794 	case IPAddressOrRange_addressRange:
795 		if (!addr_expand(addr_b, b->u.addressRange->min, length, 0x00))
796 			return -1;
797 		prefix_len_b = length * 8;
798 		break;
799 	}
800 
801 	if ((r = memcmp(addr_a, addr_b, length)) != 0)
802 		return r;
803 	else
804 		return prefix_len_a - prefix_len_b;
805 }
806 
807 /*
808  * IPv4-specific closure over IPAddressOrRange_cmp, since sk_sort()
809  * comparison routines are only allowed two arguments.
810  */
811 static int
v4IPAddressOrRange_cmp(const IPAddressOrRange * const * a,const IPAddressOrRange * const * b)812 v4IPAddressOrRange_cmp(const IPAddressOrRange *const *a,
813     const IPAddressOrRange *const *b)
814 {
815 	return IPAddressOrRange_cmp(*a, *b, 4);
816 }
817 
818 /*
819  * IPv6-specific closure over IPAddressOrRange_cmp, since sk_sort()
820  * comparison routines are only allowed two arguments.
821  */
822 static int
v6IPAddressOrRange_cmp(const IPAddressOrRange * const * a,const IPAddressOrRange * const * b)823 v6IPAddressOrRange_cmp(const IPAddressOrRange *const *a,
824     const IPAddressOrRange *const *b)
825 {
826 	return IPAddressOrRange_cmp(*a, *b, 16);
827 }
828 
829 /*
830  * Calculate whether a range collapses to a prefix.
831  * See last paragraph of RFC 3779 2.2.3.7.
832  *
833  * It's the caller's responsibility to ensure that min <= max.
834  */
835 static int
range_should_be_prefix(const unsigned char * min,const unsigned char * max,const int length)836 range_should_be_prefix(const unsigned char *min, const unsigned char *max,
837     const int length)
838 {
839 	unsigned char mask;
840 	int i, j;
841 
842 	for (i = 0; i < length && min[i] == max[i]; i++)
843 		continue;
844 	for (j = length - 1; j >= 0 && min[j] == 0x00 && max[j] == 0xff; j--)
845 		continue;
846 	if (i < j)
847 		return -1;
848 	if (i > j)
849 		return i * 8;
850 	mask = min[i] ^ max[i];
851 	switch (mask) {
852 	case 0x01:
853 		j = 7;
854 		break;
855 	case 0x03:
856 		j = 6;
857 		break;
858 	case 0x07:
859 		j = 5;
860 		break;
861 	case 0x0f:
862 		j = 4;
863 		break;
864 	case 0x1f:
865 		j = 3;
866 		break;
867 	case 0x3f:
868 		j = 2;
869 		break;
870 	case 0x7f:
871 		j = 1;
872 		break;
873 	default:
874 		return -1;
875 	}
876 	if ((min[i] & mask) != 0 || (max[i] & mask) != mask)
877 		return -1;
878 	else
879 		return i * 8 + j;
880 }
881 
882 /*
883  * Fill IPAddressOrRange with bit string encoding of a prefix - RFC 3779, 2.1.1.
884  */
885 static int
make_addressPrefix(IPAddressOrRange ** out_aor,uint8_t * addr,uint32_t afi,int prefix_len)886 make_addressPrefix(IPAddressOrRange **out_aor, uint8_t *addr, uint32_t afi,
887     int prefix_len)
888 {
889 	IPAddressOrRange *aor = NULL;
890 	int afi_len, num_bits, num_octets;
891 	uint8_t unused_bits;
892 
893 	if (prefix_len < 0)
894 		goto err;
895 
896 	if (!length_from_afi(afi, &afi_len))
897 		goto err;
898 	if (prefix_len > 8 * afi_len)
899 		goto err;
900 
901 	num_octets = (prefix_len + 7) / 8;
902 	num_bits = prefix_len % 8;
903 
904 	unused_bits = 0;
905 	if (num_bits > 0)
906 		unused_bits = 8 - num_bits;
907 
908 	if ((aor = IPAddressOrRange_new()) == NULL)
909 		goto err;
910 
911 	aor->type = IPAddressOrRange_addressPrefix;
912 
913 	if ((aor->u.addressPrefix = ASN1_BIT_STRING_new()) == NULL)
914 		goto err;
915 	if (!ASN1_BIT_STRING_set(aor->u.addressPrefix, addr, num_octets))
916 		goto err;
917 	if (!asn1_abs_set_unused_bits(aor->u.addressPrefix, unused_bits))
918 		goto err;
919 
920 	*out_aor = aor;
921 	return 1;
922 
923  err:
924 	IPAddressOrRange_free(aor);
925 	return 0;
926 }
927 
928 static uint8_t
count_trailing_zeroes(uint8_t octet)929 count_trailing_zeroes(uint8_t octet)
930 {
931 	uint8_t count = 0;
932 
933 	if (octet == 0)
934 		return 8;
935 
936 	while ((octet & (1 << count)) == 0)
937 		count++;
938 
939 	return count;
940 }
941 
942 static int
trim_end_u8(CBS * cbs,uint8_t trim)943 trim_end_u8(CBS *cbs, uint8_t trim)
944 {
945 	uint8_t octet;
946 
947 	while (CBS_len(cbs) > 0) {
948 		if (!CBS_peek_last_u8(cbs, &octet))
949 			return 0;
950 		if (octet != trim)
951 			return 1;
952 		if (!CBS_get_last_u8(cbs, &octet))
953 			return 0;
954 	}
955 
956 	return 1;
957 }
958 
959 /*
960  * Populate IPAddressOrRange with bit string encoding of a range, see
961  * RFC 3779, 2.1.2.
962  */
963 static int
make_addressRange(IPAddressOrRange ** out_aor,uint8_t * min,uint8_t * max,uint32_t afi,int length)964 make_addressRange(IPAddressOrRange **out_aor, uint8_t *min, uint8_t *max,
965     uint32_t afi, int length)
966 {
967 	IPAddressOrRange *aor = NULL;
968 	IPAddressRange *range;
969 	int prefix_len;
970 	CBS cbs;
971 	size_t max_len, min_len;
972 	uint8_t unused_bits_min, unused_bits_max;
973 	uint8_t octet;
974 
975 	if (memcmp(min, max, length) > 0)
976 		goto err;
977 
978 	/*
979 	 * RFC 3779, 2.2.3.6 - a range that can be expressed as a prefix
980 	 * must be encoded as a prefix.
981 	 */
982 
983 	if ((prefix_len = range_should_be_prefix(min, max, length)) >= 0)
984 		return make_addressPrefix(out_aor, min, afi, prefix_len);
985 
986 	/*
987 	 * The bit string representing min is formed by removing all its
988 	 * trailing zero bits, so remove all trailing zero octets and count
989 	 * the trailing zero bits of the last octet.
990 	 */
991 
992 	CBS_init(&cbs, min, length);
993 
994 	if (!trim_end_u8(&cbs, 0x00))
995 		goto err;
996 
997 	unused_bits_min = 0;
998 	if ((min_len = CBS_len(&cbs)) > 0) {
999 		if (!CBS_peek_last_u8(&cbs, &octet))
1000 			goto err;
1001 
1002 		unused_bits_min = count_trailing_zeroes(octet);
1003 	}
1004 
1005 	/*
1006 	 * The bit string representing max is formed by removing all its
1007 	 * trailing one bits, so remove all trailing 0xff octets and count
1008 	 * the trailing ones of the last octet.
1009 	 */
1010 
1011 	CBS_init(&cbs, max, length);
1012 
1013 	if (!trim_end_u8(&cbs, 0xff))
1014 		goto err;
1015 
1016 	unused_bits_max = 0;
1017 	if ((max_len = CBS_len(&cbs)) > 0) {
1018 		if (!CBS_peek_last_u8(&cbs, &octet))
1019 			goto err;
1020 
1021 		unused_bits_max = count_trailing_zeroes(octet + 1);
1022 	}
1023 
1024 	/*
1025 	 * Populate IPAddressOrRange.
1026 	 */
1027 
1028 	if ((aor = IPAddressOrRange_new()) == NULL)
1029 		goto err;
1030 
1031 	aor->type = IPAddressOrRange_addressRange;
1032 
1033 	if ((range = aor->u.addressRange = IPAddressRange_new()) == NULL)
1034 		goto err;
1035 
1036 	if (!ASN1_BIT_STRING_set(range->min, min, min_len))
1037 		goto err;
1038 	if (!asn1_abs_set_unused_bits(range->min, unused_bits_min))
1039 		goto err;
1040 
1041 	if (!ASN1_BIT_STRING_set(range->max, max, max_len))
1042 		goto err;
1043 	if (!asn1_abs_set_unused_bits(range->max, unused_bits_max))
1044 		goto err;
1045 
1046 	*out_aor = aor;
1047 
1048 	return 1;
1049 
1050  err:
1051 	IPAddressOrRange_free(aor);
1052 	return 0;
1053 }
1054 
1055 /*
1056  * Construct a new address family or find an existing one.
1057  */
1058 static IPAddressFamily *
make_IPAddressFamily(IPAddrBlocks * addr,const unsigned afi,const unsigned * safi)1059 make_IPAddressFamily(IPAddrBlocks *addr, const unsigned afi,
1060     const unsigned *safi)
1061 {
1062 	IPAddressFamily *af = NULL;
1063 	CBB cbb;
1064 	CBS cbs;
1065 	uint8_t *key = NULL;
1066 	size_t keylen;
1067 	int i;
1068 
1069 	if (!CBB_init(&cbb, 0))
1070 		goto err;
1071 
1072 	if (afi != IANA_AFI_IPV4 && afi != IANA_AFI_IPV6)
1073 		goto err;
1074 	if (!CBB_add_u16(&cbb, afi))
1075 		goto err;
1076 
1077 	if (safi != NULL) {
1078 		if (*safi > 255)
1079 			goto err;
1080 		if (!CBB_add_u8(&cbb, *safi))
1081 			goto err;
1082 	}
1083 
1084 	if (!CBB_finish(&cbb, &key, &keylen))
1085 		goto err;
1086 
1087 	for (i = 0; i < sk_IPAddressFamily_num(addr); i++) {
1088 		af = sk_IPAddressFamily_value(addr, i);
1089 
1090 		CBS_init(&cbs, af->addressFamily->data,
1091 		    af->addressFamily->length);
1092 		if (CBS_mem_equal(&cbs, key, keylen))
1093 			goto done;
1094 	}
1095 
1096 	if ((af = IPAddressFamily_new()) == NULL)
1097 		goto err;
1098 	if (!ASN1_OCTET_STRING_set(af->addressFamily, key, keylen))
1099 		goto err;
1100 	if (!sk_IPAddressFamily_push(addr, af))
1101 		goto err;
1102 
1103  done:
1104 	free(key);
1105 
1106 	return af;
1107 
1108  err:
1109 	CBB_cleanup(&cbb);
1110 	free(key);
1111 	IPAddressFamily_free(af);
1112 
1113 	return NULL;
1114 }
1115 
1116 /*
1117  * Add an inheritance element.
1118  */
1119 int
X509v3_addr_add_inherit(IPAddrBlocks * addr,const unsigned afi,const unsigned * safi)1120 X509v3_addr_add_inherit(IPAddrBlocks *addr, const unsigned afi,
1121     const unsigned *safi)
1122 {
1123 	IPAddressFamily *af;
1124 
1125 	if ((af = make_IPAddressFamily(addr, afi, safi)) == NULL)
1126 		return 0;
1127 
1128 	return IPAddressFamily_set_inheritance(af);
1129 }
1130 LCRYPTO_ALIAS(X509v3_addr_add_inherit);
1131 
1132 /*
1133  * Construct an IPAddressOrRange sequence, or return an existing one.
1134  */
1135 static IPAddressOrRanges *
make_prefix_or_range(IPAddrBlocks * addr,const unsigned afi,const unsigned * safi)1136 make_prefix_or_range(IPAddrBlocks *addr, const unsigned afi,
1137     const unsigned *safi)
1138 {
1139 	IPAddressFamily *af;
1140 	IPAddressOrRanges *aors = NULL;
1141 
1142 	if ((af = make_IPAddressFamily(addr, afi, safi)) == NULL)
1143 		return NULL;
1144 
1145 	if (IPAddressFamily_inheritance(af) != NULL)
1146 		return NULL;
1147 
1148 	if ((aors = IPAddressFamily_addressesOrRanges(af)) != NULL)
1149 		return aors;
1150 
1151 	if ((aors = sk_IPAddressOrRange_new_null()) == NULL)
1152 		return NULL;
1153 
1154 	switch (afi) {
1155 	case IANA_AFI_IPV4:
1156 		(void)sk_IPAddressOrRange_set_cmp_func(aors,
1157 		    v4IPAddressOrRange_cmp);
1158 		break;
1159 	case IANA_AFI_IPV6:
1160 		(void)sk_IPAddressOrRange_set_cmp_func(aors,
1161 		    v6IPAddressOrRange_cmp);
1162 		break;
1163 	}
1164 
1165 	af->ipAddressChoice->type = IPAddressChoice_addressesOrRanges;
1166 	af->ipAddressChoice->u.addressesOrRanges = aors;
1167 
1168 	return aors;
1169 }
1170 
1171 /*
1172  * Add a prefix.
1173  */
1174 int
X509v3_addr_add_prefix(IPAddrBlocks * addr,const unsigned afi,const unsigned * safi,unsigned char * a,const int prefix_len)1175 X509v3_addr_add_prefix(IPAddrBlocks *addr, const unsigned afi,
1176     const unsigned *safi, unsigned char *a, const int prefix_len)
1177 {
1178 	IPAddressOrRanges *aors;
1179 	IPAddressOrRange *aor;
1180 
1181 	if ((aors = make_prefix_or_range(addr, afi, safi)) == NULL)
1182 		return 0;
1183 
1184 	if (!make_addressPrefix(&aor, a, afi, prefix_len))
1185 		return 0;
1186 
1187 	if (sk_IPAddressOrRange_push(aors, aor) <= 0) {
1188 		IPAddressOrRange_free(aor);
1189 		return 0;
1190 	}
1191 
1192 	return 1;
1193 }
1194 LCRYPTO_ALIAS(X509v3_addr_add_prefix);
1195 
1196 /*
1197  * Add a range.
1198  */
1199 int
X509v3_addr_add_range(IPAddrBlocks * addr,const unsigned afi,const unsigned * safi,unsigned char * min,unsigned char * max)1200 X509v3_addr_add_range(IPAddrBlocks *addr, const unsigned afi,
1201     const unsigned *safi, unsigned char *min, unsigned char *max)
1202 {
1203 	IPAddressOrRanges *aors;
1204 	IPAddressOrRange *aor;
1205 	int length;
1206 
1207 	if ((aors = make_prefix_or_range(addr, afi, safi)) == NULL)
1208 		return 0;
1209 
1210 	if (!length_from_afi(afi, &length))
1211 		return 0;
1212 
1213 	if (!make_addressRange(&aor, min, max, afi, length))
1214 		return 0;
1215 
1216 	if (sk_IPAddressOrRange_push(aors, aor) <= 0) {
1217 		IPAddressOrRange_free(aor);
1218 		return 0;
1219 	}
1220 
1221 	return 1;
1222 }
1223 LCRYPTO_ALIAS(X509v3_addr_add_range);
1224 
1225 static int
extract_min_max_bitstr(IPAddressOrRange * aor,ASN1_BIT_STRING ** out_min,ASN1_BIT_STRING ** out_max)1226 extract_min_max_bitstr(IPAddressOrRange *aor, ASN1_BIT_STRING **out_min,
1227     ASN1_BIT_STRING **out_max)
1228 {
1229 	switch (aor->type) {
1230 	case IPAddressOrRange_addressPrefix:
1231 		*out_min = *out_max = aor->u.addressPrefix;
1232 		return 1;
1233 	case IPAddressOrRange_addressRange:
1234 		*out_min = aor->u.addressRange->min;
1235 		*out_max = aor->u.addressRange->max;
1236 		return 1;
1237 	default:
1238 		return 0;
1239 	}
1240 }
1241 
1242 /*
1243  * Extract min and max values from an IPAddressOrRange.
1244  */
1245 static int
extract_min_max(IPAddressOrRange * aor,unsigned char * min,unsigned char * max,int length)1246 extract_min_max(IPAddressOrRange *aor, unsigned char *min, unsigned char *max,
1247     int length)
1248 {
1249 	ASN1_BIT_STRING *min_bitstr, *max_bitstr;
1250 
1251 	if (aor == NULL || min == NULL || max == NULL)
1252 		return 0;
1253 
1254 	if (!extract_min_max_bitstr(aor, &min_bitstr, &max_bitstr))
1255 		return 0;
1256 
1257 	if (!addr_expand(min, min_bitstr, length, 0))
1258 		return 0;
1259 
1260 	return addr_expand(max, max_bitstr, length, 1);
1261 }
1262 
1263 /*
1264  * Public wrapper for extract_min_max().
1265  */
1266 int
X509v3_addr_get_range(IPAddressOrRange * aor,const unsigned afi,unsigned char * min,unsigned char * max,const int length)1267 X509v3_addr_get_range(IPAddressOrRange *aor, const unsigned afi,
1268     unsigned char *min, unsigned char *max, const int length)
1269 {
1270 	int afi_len;
1271 
1272 	if (!length_from_afi(afi, &afi_len))
1273 		return 0;
1274 
1275 	if (length < afi_len)
1276 		return 0;
1277 
1278 	if (!extract_min_max(aor, min, max, afi_len))
1279 		return 0;
1280 
1281 	return afi_len;
1282 }
1283 LCRYPTO_ALIAS(X509v3_addr_get_range);
1284 
1285 /*
1286  * Check whether an IPAddrBLocks is in canonical form.
1287  */
1288 int
X509v3_addr_is_canonical(IPAddrBlocks * addr)1289 X509v3_addr_is_canonical(IPAddrBlocks *addr)
1290 {
1291 	unsigned char a_min[ADDR_RAW_BUF_LEN], a_max[ADDR_RAW_BUF_LEN];
1292 	unsigned char b_min[ADDR_RAW_BUF_LEN], b_max[ADDR_RAW_BUF_LEN];
1293 	IPAddressFamily *af;
1294 	IPAddressOrRanges *aors;
1295 	IPAddressOrRange *aor, *aor_a, *aor_b;
1296 	int i, j, k, length;
1297 
1298 	/*
1299 	 * Empty extension is canonical.
1300 	 */
1301 	if (addr == NULL)
1302 		return 1;
1303 
1304 	/*
1305 	 * Check whether the top-level list is in order.
1306 	 */
1307 	for (i = 0; i < sk_IPAddressFamily_num(addr) - 1; i++) {
1308 		const IPAddressFamily *a = sk_IPAddressFamily_value(addr, i);
1309 		const IPAddressFamily *b = sk_IPAddressFamily_value(addr, i + 1);
1310 
1311 		/* Check that both have valid AFIs before comparing them. */
1312 		if (!IPAddressFamily_afi_is_valid(a))
1313 			return 0;
1314 		if (!IPAddressFamily_afi_is_valid(b))
1315 			return 0;
1316 
1317 		if (IPAddressFamily_cmp(&a, &b) >= 0)
1318 			return 0;
1319 	}
1320 
1321 	/*
1322 	 * Top level's ok, now check each address family.
1323 	 */
1324 	for (i = 0; i < sk_IPAddressFamily_num(addr); i++) {
1325 		af = sk_IPAddressFamily_value(addr, i);
1326 
1327 		if (!IPAddressFamily_afi_length(af, &length))
1328 			return 0;
1329 
1330 		/*
1331 		 * If this family has an inheritance element, it is canonical.
1332 		 */
1333 		if (IPAddressFamily_inheritance(af) != NULL)
1334 			continue;
1335 
1336 		/*
1337 		 * If this family has neither an inheritance element nor an
1338 		 * addressesOrRanges, we don't know what this is.
1339 		 */
1340 		if ((aors = IPAddressFamily_addressesOrRanges(af)) == NULL)
1341 			return 0;
1342 
1343 		if (sk_IPAddressOrRange_num(aors) == 0)
1344 			return 0;
1345 
1346 		for (j = 0; j < sk_IPAddressOrRange_num(aors) - 1; j++) {
1347 			aor_a = sk_IPAddressOrRange_value(aors, j);
1348 			aor_b = sk_IPAddressOrRange_value(aors, j + 1);
1349 
1350 			if (!extract_min_max(aor_a, a_min, a_max, length) ||
1351 			    !extract_min_max(aor_b, b_min, b_max, length))
1352 				return 0;
1353 
1354 			/*
1355 			 * Punt misordered list, overlapping start, or inverted
1356 			 * range.
1357 			 */
1358 			if (memcmp(a_min, b_min, length) >= 0 ||
1359 			    memcmp(a_min, a_max, length) > 0 ||
1360 			    memcmp(b_min, b_max, length) > 0)
1361 				return 0;
1362 
1363 			/*
1364 			 * Punt if adjacent or overlapping.  Check for adjacency
1365 			 * by subtracting one from b_min first.
1366 			 */
1367 			for (k = length - 1; k >= 0 && b_min[k]-- == 0x00; k--)
1368 				continue;
1369 			if (memcmp(a_max, b_min, length) >= 0)
1370 				return 0;
1371 
1372 			/*
1373 			 * Check for range that should be expressed as a prefix.
1374 			 */
1375 			if (aor_a->type == IPAddressOrRange_addressPrefix)
1376 				continue;
1377 
1378 			if (range_should_be_prefix(a_min, a_max, length) >= 0)
1379 				return 0;
1380 		}
1381 
1382 		/*
1383 		 * Check final range to see if it's inverted or should be a
1384 		 * prefix.
1385 		 */
1386 		aor = sk_IPAddressOrRange_value(aors, j);
1387 		if (aor->type == IPAddressOrRange_addressRange) {
1388 			if (!extract_min_max(aor, a_min, a_max, length))
1389 				return 0;
1390 			if (memcmp(a_min, a_max, length) > 0)
1391 				return 0;
1392 			if (range_should_be_prefix(a_min, a_max, length) >= 0)
1393 				return 0;
1394 		}
1395 	}
1396 
1397 	/*
1398 	 * If we made it through all that, we're happy.
1399 	 */
1400 	return 1;
1401 }
1402 LCRYPTO_ALIAS(X509v3_addr_is_canonical);
1403 
1404 /*
1405  * Whack an IPAddressOrRanges into canonical form.
1406  */
1407 static int
IPAddressOrRanges_canonize(IPAddressOrRanges * aors,const unsigned afi)1408 IPAddressOrRanges_canonize(IPAddressOrRanges *aors, const unsigned afi)
1409 {
1410 	IPAddressOrRange *a, *b, *merged;
1411 	unsigned char a_min[ADDR_RAW_BUF_LEN], a_max[ADDR_RAW_BUF_LEN];
1412 	unsigned char b_min[ADDR_RAW_BUF_LEN], b_max[ADDR_RAW_BUF_LEN];
1413 	int i, j, length;
1414 
1415 	if (!length_from_afi(afi, &length))
1416 		return 0;
1417 
1418 	/*
1419 	 * Sort the IPAddressOrRanges sequence.
1420 	 */
1421 	sk_IPAddressOrRange_sort(aors);
1422 
1423 	/*
1424 	 * Clean up representation issues, punt on duplicates or overlaps.
1425 	 */
1426 	for (i = 0; i < sk_IPAddressOrRange_num(aors) - 1; i++) {
1427 		a = sk_IPAddressOrRange_value(aors, i);
1428 		b = sk_IPAddressOrRange_value(aors, i + 1);
1429 
1430 		if (!extract_min_max(a, a_min, a_max, length) ||
1431 		    !extract_min_max(b, b_min, b_max, length))
1432 			return 0;
1433 
1434 		/*
1435 		 * Punt inverted ranges.
1436 		 */
1437 		if (memcmp(a_min, a_max, length) > 0 ||
1438 		    memcmp(b_min, b_max, length) > 0)
1439 			return 0;
1440 
1441 		/*
1442 		 * Punt overlaps.
1443 		 */
1444 		if (memcmp(a_max, b_min, length) >= 0)
1445 			return 0;
1446 
1447 		/*
1448 		 * Merge if a and b are adjacent.  We check for
1449 		 * adjacency by subtracting one from b_min first.
1450 		 */
1451 		for (j = length - 1; j >= 0 && b_min[j]-- == 0x00; j--)
1452 			continue;
1453 
1454 		if (memcmp(a_max, b_min, length) != 0)
1455 			continue;
1456 
1457 		if (!make_addressRange(&merged, a_min, b_max, afi, length))
1458 			return 0;
1459 		sk_IPAddressOrRange_set(aors, i, merged);
1460 		(void)sk_IPAddressOrRange_delete(aors, i + 1);
1461 		IPAddressOrRange_free(a);
1462 		IPAddressOrRange_free(b);
1463 		i--;
1464 	}
1465 
1466 	/*
1467 	 * Check for inverted final range.
1468 	 */
1469 	a = sk_IPAddressOrRange_value(aors, i);
1470 	if (a != NULL && a->type == IPAddressOrRange_addressRange) {
1471 		if (!extract_min_max(a, a_min, a_max, length))
1472 			return 0;
1473 		if (memcmp(a_min, a_max, length) > 0)
1474 			return 0;
1475 	}
1476 
1477 	return 1;
1478 }
1479 
1480 /*
1481  * Whack an IPAddrBlocks extension into canonical form.
1482  */
1483 int
X509v3_addr_canonize(IPAddrBlocks * addr)1484 X509v3_addr_canonize(IPAddrBlocks *addr)
1485 {
1486 	IPAddressFamily *af;
1487 	IPAddressOrRanges *aors;
1488 	uint16_t afi;
1489 	int i;
1490 
1491 	for (i = 0; i < sk_IPAddressFamily_num(addr); i++) {
1492 		af = sk_IPAddressFamily_value(addr, i);
1493 
1494 		/* Check AFI/SAFI here - IPAddressFamily_cmp() can't error. */
1495 		if (!IPAddressFamily_afi(af, &afi))
1496 			return 0;
1497 
1498 		if ((aors = IPAddressFamily_addressesOrRanges(af)) == NULL)
1499 			continue;
1500 
1501 		if (!IPAddressOrRanges_canonize(aors, afi))
1502 			return 0;
1503 	}
1504 
1505 	(void)sk_IPAddressFamily_set_cmp_func(addr, IPAddressFamily_cmp);
1506 	sk_IPAddressFamily_sort(addr);
1507 
1508 	return X509v3_addr_is_canonical(addr);
1509 }
1510 LCRYPTO_ALIAS(X509v3_addr_canonize);
1511 
1512 /*
1513  * v2i handler for the IPAddrBlocks extension.
1514  */
1515 static void *
v2i_IPAddrBlocks(const struct v3_ext_method * method,struct v3_ext_ctx * ctx,STACK_OF (CONF_VALUE)* values)1516 v2i_IPAddrBlocks(const struct v3_ext_method *method, struct v3_ext_ctx *ctx,
1517     STACK_OF(CONF_VALUE)*values)
1518 {
1519 	static const char v4addr_chars[] = "0123456789.";
1520 	static const char v6addr_chars[] = "0123456789.:abcdefABCDEF";
1521 	IPAddrBlocks *addr = NULL;
1522 	char *s = NULL, *t;
1523 	int i;
1524 
1525 	if ((addr = sk_IPAddressFamily_new(IPAddressFamily_cmp)) == NULL) {
1526 		X509V3error(ERR_R_MALLOC_FAILURE);
1527 		return NULL;
1528 	}
1529 
1530 	for (i = 0; i < sk_CONF_VALUE_num(values); i++) {
1531 		CONF_VALUE *val = sk_CONF_VALUE_value(values, i);
1532 		unsigned char min[ADDR_RAW_BUF_LEN], max[ADDR_RAW_BUF_LEN];
1533 		unsigned afi, *safi = NULL, safi_;
1534 		const char *addr_chars = NULL;
1535 		const char *errstr;
1536 		int prefix_len, i1, i2, delim, length;
1537 
1538 		if (!name_cmp(val->name, "IPv4")) {
1539 			afi = IANA_AFI_IPV4;
1540 		} else if (!name_cmp(val->name, "IPv6")) {
1541 			afi = IANA_AFI_IPV6;
1542 		} else if (!name_cmp(val->name, "IPv4-SAFI")) {
1543 			afi = IANA_AFI_IPV4;
1544 			safi = &safi_;
1545 		} else if (!name_cmp(val->name, "IPv6-SAFI")) {
1546 			afi = IANA_AFI_IPV6;
1547 			safi = &safi_;
1548 		} else {
1549 			X509V3error(X509V3_R_EXTENSION_NAME_ERROR);
1550 			X509V3_conf_err(val);
1551 			goto err;
1552 		}
1553 
1554 		switch (afi) {
1555 		case IANA_AFI_IPV4:
1556 			addr_chars = v4addr_chars;
1557 			break;
1558 		case IANA_AFI_IPV6:
1559 			addr_chars = v6addr_chars;
1560 			break;
1561 		}
1562 
1563 		if (!length_from_afi(afi, &length))
1564 			goto err;
1565 
1566 		/*
1567 		 * Handle SAFI, if any, and strdup() so we can null-terminate
1568 		 * the other input values.
1569 		 */
1570 		if (safi != NULL) {
1571 			unsigned long parsed_safi;
1572 			int saved_errno = errno;
1573 
1574 			errno = 0;
1575 			parsed_safi = strtoul(val->value, &t, 0);
1576 
1577 			/* Value must be present, then a tab, space or colon. */
1578 			if (val->value[0] == '\0' ||
1579 			    (*t != '\t' && *t != ' ' && *t != ':')) {
1580 				X509V3error(X509V3_R_INVALID_SAFI);
1581 				X509V3_conf_err(val);
1582 				goto err;
1583 			}
1584 			/* Range and overflow check. */
1585 			if ((errno == ERANGE && parsed_safi == ULONG_MAX) ||
1586 			    parsed_safi > 0xff) {
1587 				X509V3error(X509V3_R_INVALID_SAFI);
1588 				X509V3_conf_err(val);
1589 				goto err;
1590 			}
1591 			errno = saved_errno;
1592 
1593 			*safi = parsed_safi;
1594 
1595 			/* Check possible whitespace is followed by a colon. */
1596 			t += strspn(t, " \t");
1597 			if (*t != ':') {
1598 				X509V3error(X509V3_R_INVALID_SAFI);
1599 				X509V3_conf_err(val);
1600 				goto err;
1601 			}
1602 
1603 			/* Skip over colon. */
1604 			t++;
1605 
1606 			/* Then over any trailing whitespace. */
1607 			t += strspn(t, " \t");
1608 
1609 			s = strdup(t);
1610 		} else {
1611 			s = strdup(val->value);
1612 		}
1613 		if (s == NULL) {
1614 			X509V3error(ERR_R_MALLOC_FAILURE);
1615 			goto err;
1616 		}
1617 
1618 		/*
1619 		 * Check for inheritance. Not worth additional complexity to
1620 		 * optimize this (seldom-used) case.
1621 		 */
1622 		if (strcmp(s, "inherit") == 0) {
1623 			if (!X509v3_addr_add_inherit(addr, afi, safi)) {
1624 				X509V3error(X509V3_R_INVALID_INHERITANCE);
1625 				X509V3_conf_err(val);
1626 				goto err;
1627 			}
1628 			free(s);
1629 			s = NULL;
1630 			continue;
1631 		}
1632 
1633 		i1 = strspn(s, addr_chars);
1634 		i2 = i1 + strspn(s + i1, " \t");
1635 		delim = s[i2++];
1636 		s[i1] = '\0';
1637 
1638 		if (a2i_ipadd(min, s) != length) {
1639 			X509V3error(X509V3_R_INVALID_IPADDRESS);
1640 			X509V3_conf_err(val);
1641 			goto err;
1642 		}
1643 
1644 		switch (delim) {
1645 		case '/':
1646 			/* length contains the size of the address in bytes. */
1647 			if (length != 4 && length != 16)
1648 				goto err;
1649 			prefix_len = strtonum(s + i2, 0, 8 * length, &errstr);
1650 			if (errstr != NULL) {
1651 				X509V3error(X509V3_R_EXTENSION_VALUE_ERROR);
1652 				X509V3_conf_err(val);
1653 				goto err;
1654 			}
1655 			if (!X509v3_addr_add_prefix(addr, afi, safi, min,
1656 			    prefix_len)) {
1657 				X509V3error(ERR_R_MALLOC_FAILURE);
1658 				goto err;
1659 			}
1660 			break;
1661 		case '-':
1662 			i1 = i2 + strspn(s + i2, " \t");
1663 			i2 = i1 + strspn(s + i1, addr_chars);
1664 			if (i1 == i2 || s[i2] != '\0') {
1665 				X509V3error(X509V3_R_EXTENSION_VALUE_ERROR);
1666 				X509V3_conf_err(val);
1667 				goto err;
1668 			}
1669 			if (a2i_ipadd(max, s + i1) != length) {
1670 				X509V3error(X509V3_R_INVALID_IPADDRESS);
1671 				X509V3_conf_err(val);
1672 				goto err;
1673 			}
1674 			if (memcmp(min, max, length) > 0) {
1675 				X509V3error(X509V3_R_EXTENSION_VALUE_ERROR);
1676 				X509V3_conf_err(val);
1677 				goto err;
1678 			}
1679 			if (!X509v3_addr_add_range(addr, afi, safi, min, max)) {
1680 				X509V3error(ERR_R_MALLOC_FAILURE);
1681 				goto err;
1682 			}
1683 			break;
1684 		case '\0':
1685 			if (!X509v3_addr_add_prefix(addr, afi, safi, min,
1686 			    length * 8)) {
1687 				X509V3error(ERR_R_MALLOC_FAILURE);
1688 				goto err;
1689 			}
1690 			break;
1691 		default:
1692 			X509V3error(X509V3_R_EXTENSION_VALUE_ERROR);
1693 			X509V3_conf_err(val);
1694 			goto err;
1695 		}
1696 
1697 		free(s);
1698 		s = NULL;
1699 	}
1700 
1701 	/*
1702 	 * Canonize the result, then we're done.
1703 	 */
1704 	if (!X509v3_addr_canonize(addr))
1705 		goto err;
1706 	return addr;
1707 
1708  err:
1709 	free(s);
1710 	sk_IPAddressFamily_pop_free(addr, IPAddressFamily_free);
1711 	return NULL;
1712 }
1713 
1714 /*
1715  * OpenSSL dispatch
1716  */
1717 static const X509V3_EXT_METHOD x509v3_ext_sbgp_ipAddrBlock = {
1718 	.ext_nid = NID_sbgp_ipAddrBlock,
1719 	.ext_flags = 0,
1720 	.it = &IPAddrBlocks_it,
1721 	.ext_new = NULL,
1722 	.ext_free = NULL,
1723 	.d2i = NULL,
1724 	.i2d = NULL,
1725 	.i2s = NULL,
1726 	.s2i = NULL,
1727 	.i2v = NULL,
1728 	.v2i = v2i_IPAddrBlocks,
1729 	.i2r = i2r_IPAddrBlocks,
1730 	.r2i = NULL,
1731 	.usr_data = NULL,
1732 };
1733 
1734 const X509V3_EXT_METHOD *
x509v3_ext_method_sbgp_ipAddrBlock(void)1735 x509v3_ext_method_sbgp_ipAddrBlock(void)
1736 {
1737 	return &x509v3_ext_sbgp_ipAddrBlock;
1738 }
1739 
1740 /*
1741  * Figure out whether extension uses inheritance.
1742  */
1743 int
X509v3_addr_inherits(IPAddrBlocks * addr)1744 X509v3_addr_inherits(IPAddrBlocks *addr)
1745 {
1746 	IPAddressFamily *af;
1747 	int i;
1748 
1749 	if (addr == NULL)
1750 		return 0;
1751 
1752 	for (i = 0; i < sk_IPAddressFamily_num(addr); i++) {
1753 		af = sk_IPAddressFamily_value(addr, i);
1754 
1755 		if (IPAddressFamily_inheritance(af) != NULL)
1756 			return 1;
1757 	}
1758 
1759 	return 0;
1760 }
1761 LCRYPTO_ALIAS(X509v3_addr_inherits);
1762 
1763 /*
1764  * Figure out whether parent contains child.
1765  *
1766  * This only works correctly if both parent and child are in canonical form.
1767  */
1768 static int
addr_contains(IPAddressOrRanges * parent,IPAddressOrRanges * child,int length)1769 addr_contains(IPAddressOrRanges *parent, IPAddressOrRanges *child, int length)
1770 {
1771 	IPAddressOrRange *child_aor, *parent_aor;
1772 	uint8_t parent_min[ADDR_RAW_BUF_LEN], parent_max[ADDR_RAW_BUF_LEN];
1773 	uint8_t child_min[ADDR_RAW_BUF_LEN], child_max[ADDR_RAW_BUF_LEN];
1774 	int p, c;
1775 
1776 	if (child == NULL || parent == child)
1777 		return 1;
1778 	if (parent == NULL)
1779 		return 0;
1780 
1781 	p = 0;
1782 	for (c = 0; c < sk_IPAddressOrRange_num(child); c++) {
1783 		child_aor = sk_IPAddressOrRange_value(child, c);
1784 
1785 		if (!extract_min_max(child_aor, child_min, child_max, length))
1786 			return 0;
1787 
1788 		for (;; p++) {
1789 			if (p >= sk_IPAddressOrRange_num(parent))
1790 				return 0;
1791 
1792 			parent_aor = sk_IPAddressOrRange_value(parent, p);
1793 
1794 			if (!extract_min_max(parent_aor, parent_min, parent_max,
1795 			    length))
1796 				return 0;
1797 
1798 			if (memcmp(parent_max, child_max, length) < 0)
1799 				continue;
1800 			if (memcmp(parent_min, child_min, length) > 0)
1801 				return 0;
1802 			break;
1803 		}
1804 	}
1805 
1806 	return 1;
1807 }
1808 
1809 /*
1810  * Test whether |child| is a subset of |parent|.
1811  */
1812 int
X509v3_addr_subset(IPAddrBlocks * child,IPAddrBlocks * parent)1813 X509v3_addr_subset(IPAddrBlocks *child, IPAddrBlocks *parent)
1814 {
1815 	IPAddressFamily *child_af, *parent_af;
1816 	IPAddressOrRanges *child_aor, *parent_aor;
1817 	int i, length;
1818 
1819 	if (child == NULL || child == parent)
1820 		return 1;
1821 	if (parent == NULL)
1822 		return 0;
1823 
1824 	if (X509v3_addr_inherits(child) || X509v3_addr_inherits(parent))
1825 		return 0;
1826 
1827 	for (i = 0; i < sk_IPAddressFamily_num(child); i++) {
1828 		child_af = sk_IPAddressFamily_value(child, i);
1829 
1830 		parent_af = IPAddressFamily_find_in_parent(parent, child_af);
1831 		if (parent_af == NULL)
1832 			return 0;
1833 
1834 		if (!IPAddressFamily_afi_length(parent_af, &length))
1835 			return 0;
1836 
1837 		child_aor = IPAddressFamily_addressesOrRanges(child_af);
1838 		parent_aor = IPAddressFamily_addressesOrRanges(parent_af);
1839 
1840 		if (!addr_contains(parent_aor, child_aor, length))
1841 			return 0;
1842 	}
1843 	return 1;
1844 }
1845 LCRYPTO_ALIAS(X509v3_addr_subset);
1846 
1847 static int
verify_error(X509_STORE_CTX * ctx,X509 * cert,int error,int depth)1848 verify_error(X509_STORE_CTX *ctx, X509 *cert, int error, int depth)
1849 {
1850 	if (ctx == NULL)
1851 		return 0;
1852 
1853 	ctx->current_cert = cert;
1854 	ctx->error = error;
1855 	ctx->error_depth = depth;
1856 
1857 	return ctx->verify_cb(0, ctx);
1858 }
1859 
1860 /*
1861  * Core code for RFC 3779 2.3 path validation.
1862  *
1863  * Returns 1 for success, 0 on error.
1864  *
1865  * When returning 0, ctx->error MUST be set to an appropriate value other than
1866  * X509_V_OK.
1867  */
1868 static int
addr_validate_path_internal(X509_STORE_CTX * ctx,STACK_OF (X509)* chain,IPAddrBlocks * ext)1869 addr_validate_path_internal(X509_STORE_CTX *ctx, STACK_OF(X509) *chain,
1870     IPAddrBlocks *ext)
1871 {
1872 	IPAddrBlocks *child = NULL, *parent = NULL;
1873 	IPAddressFamily *child_af, *parent_af;
1874 	IPAddressOrRanges *child_aor, *parent_aor;
1875 	X509 *cert = NULL;
1876 	int depth = -1;
1877 	int i;
1878 	unsigned int length;
1879 	int ret = 1;
1880 
1881 	/* We need a non-empty chain to test against. */
1882 	if (sk_X509_num(chain) <= 0)
1883 		goto err;
1884 	/* We need either a store ctx or an extension to work with. */
1885 	if (ctx == NULL && ext == NULL)
1886 		goto err;
1887 	/* If there is a store ctx, it needs a verify_cb. */
1888 	if (ctx != NULL && ctx->verify_cb == NULL)
1889 		goto err;
1890 
1891 	/*
1892 	 * Figure out where to start. If we don't have an extension to check,
1893 	 * (either extracted from the leaf or passed by the caller), we're done.
1894 	 * Otherwise, check canonical form and set up for walking up the chain.
1895 	 */
1896 	if (ext == NULL) {
1897 		depth = 0;
1898 		cert = sk_X509_value(chain, depth);
1899 		if ((X509_get_extension_flags(cert) & EXFLAG_INVALID) != 0) {
1900 			if ((ret = verify_error(ctx, cert,
1901 			    X509_V_ERR_INVALID_EXTENSION, depth)) == 0)
1902 				goto done;
1903 		}
1904 		if ((ext = cert->rfc3779_addr) == NULL)
1905 			goto done;
1906 	} else if (!X509v3_addr_is_canonical(ext)) {
1907 		if ((ret = verify_error(ctx, cert,
1908 		    X509_V_ERR_INVALID_EXTENSION, depth)) == 0)
1909 			goto done;
1910 	}
1911 
1912 	(void)sk_IPAddressFamily_set_cmp_func(ext, IPAddressFamily_cmp);
1913 	if ((child = sk_IPAddressFamily_dup(ext)) == NULL) {
1914 		X509V3error(ERR_R_MALLOC_FAILURE);
1915 		if (ctx != NULL)
1916 			ctx->error = X509_V_ERR_OUT_OF_MEM;
1917 		ret = 0;
1918 		goto done;
1919 	}
1920 
1921 	/*
1922 	 * Now walk up the chain. No cert may list resources that its parent
1923 	 * doesn't list.
1924 	 */
1925 	for (depth++; depth < sk_X509_num(chain); depth++) {
1926 		cert = sk_X509_value(chain, depth);
1927 
1928 		if ((X509_get_extension_flags(cert) & EXFLAG_INVALID) != 0) {
1929 			if ((ret = verify_error(ctx, cert,
1930 			    X509_V_ERR_INVALID_EXTENSION, depth)) == 0)
1931 				goto done;
1932 		}
1933 
1934 		if ((parent = cert->rfc3779_addr) == NULL) {
1935 			for (i = 0; i < sk_IPAddressFamily_num(child); i++) {
1936 				child_af = sk_IPAddressFamily_value(child, i);
1937 
1938 				if (IPAddressFamily_inheritance(child_af) !=
1939 				    NULL)
1940 					continue;
1941 
1942 				if ((ret = verify_error(ctx, cert,
1943 				    X509_V_ERR_UNNESTED_RESOURCE, depth)) == 0)
1944 					goto done;
1945 				break;
1946 			}
1947 			continue;
1948 		}
1949 
1950 		/*
1951 		 * Check that the child's resources are covered by the parent.
1952 		 * Each covered resource is replaced with the parent's resource
1953 		 * covering it, so the next iteration will check that the
1954 		 * parent's resources are covered by the grandparent.
1955 		 */
1956 		for (i = 0; i < sk_IPAddressFamily_num(child); i++) {
1957 			child_af = sk_IPAddressFamily_value(child, i);
1958 
1959 			if ((parent_af = IPAddressFamily_find_in_parent(parent,
1960 			    child_af)) == NULL) {
1961 				/*
1962 				 * If we have no match in the parent and the
1963 				 * child inherits, that's fine.
1964 				 */
1965 				if (IPAddressFamily_inheritance(child_af) !=
1966 				    NULL)
1967 					continue;
1968 
1969 				/* Otherwise the child isn't covered. */
1970 				if ((ret = verify_error(ctx, cert,
1971 				    X509_V_ERR_UNNESTED_RESOURCE, depth)) == 0)
1972 					goto done;
1973 				break;
1974 			}
1975 
1976 			/* Parent inherits, nothing to do. */
1977 			if (IPAddressFamily_inheritance(parent_af) != NULL)
1978 				continue;
1979 
1980 			/* Child inherits. Use parent's address family. */
1981 			if (IPAddressFamily_inheritance(child_af) != NULL) {
1982 				sk_IPAddressFamily_set(child, i, parent_af);
1983 				continue;
1984 			}
1985 
1986 			child_aor = IPAddressFamily_addressesOrRanges(child_af);
1987 			parent_aor =
1988 			    IPAddressFamily_addressesOrRanges(parent_af);
1989 
1990 			/*
1991 			 * Child and parent are canonical and neither inherits.
1992 			 * If either addressesOrRanges is NULL, something's
1993 			 * very wrong.
1994 			 */
1995 			if (child_aor == NULL || parent_aor == NULL)
1996 				goto err;
1997 
1998 			if (!IPAddressFamily_afi_length(child_af, &length))
1999 				goto err;
2000 
2001 			/* Now check containment and replace or error. */
2002 			if (addr_contains(parent_aor, child_aor, length)) {
2003 				sk_IPAddressFamily_set(child, i, parent_af);
2004 				continue;
2005 			}
2006 
2007 			if ((ret = verify_error(ctx, cert,
2008 			    X509_V_ERR_UNNESTED_RESOURCE, depth)) == 0)
2009 				goto done;
2010 		}
2011 	}
2012 
2013 	/*
2014 	 * Trust anchor can't inherit.
2015 	 */
2016 	if ((parent = cert->rfc3779_addr) != NULL) {
2017 		for (i = 0; i < sk_IPAddressFamily_num(parent); i++) {
2018 			parent_af = sk_IPAddressFamily_value(parent, i);
2019 
2020 			if (IPAddressFamily_inheritance(parent_af) == NULL)
2021 				continue;
2022 
2023 			if ((ret = verify_error(ctx, cert,
2024 			    X509_V_ERR_UNNESTED_RESOURCE, depth)) == 0)
2025 				goto done;
2026 		}
2027 	}
2028 
2029  done:
2030 	sk_IPAddressFamily_free(child);
2031 	return ret;
2032 
2033  err:
2034 	sk_IPAddressFamily_free(child);
2035 
2036 	if (ctx != NULL)
2037 		ctx->error = X509_V_ERR_UNSPECIFIED;
2038 
2039 	return 0;
2040 }
2041 
2042 /*
2043  * RFC 3779 2.3 path validation -- called from X509_verify_cert().
2044  */
2045 int
X509v3_addr_validate_path(X509_STORE_CTX * ctx)2046 X509v3_addr_validate_path(X509_STORE_CTX *ctx)
2047 {
2048 	if (sk_X509_num(ctx->chain) <= 0 || ctx->verify_cb == NULL) {
2049 		ctx->error = X509_V_ERR_UNSPECIFIED;
2050 		return 0;
2051 	}
2052 	return addr_validate_path_internal(ctx, ctx->chain, NULL);
2053 }
2054 LCRYPTO_ALIAS(X509v3_addr_validate_path);
2055 
2056 /*
2057  * RFC 3779 2.3 path validation of an extension.
2058  * Test whether chain covers extension.
2059  */
2060 int
X509v3_addr_validate_resource_set(STACK_OF (X509)* chain,IPAddrBlocks * ext,int allow_inheritance)2061 X509v3_addr_validate_resource_set(STACK_OF(X509) *chain, IPAddrBlocks *ext,
2062     int allow_inheritance)
2063 {
2064 	if (ext == NULL)
2065 		return 1;
2066 	if (sk_X509_num(chain) <= 0)
2067 		return 0;
2068 	if (!allow_inheritance && X509v3_addr_inherits(ext))
2069 		return 0;
2070 	return addr_validate_path_internal(NULL, chain, ext);
2071 }
2072 LCRYPTO_ALIAS(X509v3_addr_validate_resource_set);
2073 
2074 #endif /* OPENSSL_NO_RFC3779 */
2075