ip.c revision 1.1
1/*	$Id: ip.c,v 1.1 2019/06/17 14:31:30 job Exp $ */
2/*
3 * Copyright (c) 2019 Kristaps Dzonsons <kristaps@bsd.lv>
4 *
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
8 *
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 */
17#include "config.h"
18
19#include <arpa/inet.h>
20#include <sys/socket.h>
21
22#include <assert.h>
23#include <err.h>
24#include <stdarg.h>
25#include <stdlib.h>
26#include <string.h>
27#include <unistd.h>
28
29#include <openssl/ssl.h>
30
31#include "extern.h"
32
33/*
34 * Parse an IP address family.
35 * This is defined in different places in the ROA/X509 standards, but
36 * it's the same thing.
37 * We prohibit all but IPv4 and IPv6, without SAFI.
38 * Return zero on failure, non-zero on success.
39 */
40int
41ip_addr_afi_parse(const char *fn,
42	const ASN1_OCTET_STRING *p, enum afi *afi)
43{
44	char	 buf[2];
45	short	 v;
46
47	if (p->length == 0 || p->length > 3) {
48		warnx("%s: invalid field length, "
49			"want 1--3, have %d", fn, p->length);
50		return 0;
51	}
52
53	memcpy(buf, p->data, sizeof(uint16_t));
54	v = ntohs(*(uint16_t *)buf);
55
56	/* Only accept IPv4 and IPv6 AFIs. */
57
58	if (v != 1 && v != 2) {
59		warnx("%s: only AFI for IPV4 (1) and "
60			"IPV6 (2) allowed: have %hd", fn, v);
61		return 0;
62	}
63
64	/* Disallow the optional SAFI. */
65
66	if (p->length == 3) {
67		warnx("%s: SAFI not allowed", fn);
68		return 0;
69	}
70
71	*afi = (v == 1) ? AFI_IPV4 : AFI_IPV6;
72	return 1;
73}
74
75/*
76 * See if a given IP prefix is covered by the IP prefixes or ranges
77 * specified in the "ips" array.
78 * This means that the IP prefix must be strictly within the ranges or
79 * singletons given in the array.
80 * Return 0 if we're inheriting from the parent, >0 if we're covered,
81 * or <0 if we're not covered.
82 */
83int
84ip_addr_check_covered(enum afi afi,
85	const unsigned char *min, const unsigned char *max,
86	const struct cert_ip *ips, size_t ipsz)
87{
88	size_t	 i, sz = AFI_IPV4 == afi ? 4 : 16;
89
90	for (i = 0; i < ipsz; i++) {
91		if (ips[i].afi != afi)
92			continue;
93		if (ips[i].type == CERT_IP_INHERIT)
94			return 0;
95		if (memcmp(ips[i].min, min, sz) <= 0 &&
96	  	    memcmp(ips[i].max, max, sz) >= 0)
97			return 1;
98	}
99
100	return -1;
101}
102
103/*
104 * Given a newly-parsed IP address or range "ip", make sure that "ip"
105 * does not overlap with any addresses or ranges in the "ips" array.
106 * This is defined by RFC 3779 section 2.2.3.6.
107 * Returns zero on failure, non-zero on success.
108 */
109int
110ip_addr_check_overlap(const struct cert_ip *ip, const char *fn,
111	const struct cert_ip *ips, size_t ipsz)
112{
113	size_t	 i, sz = AFI_IPV4 == ip->afi ? 4 : 16;
114	int	 inherit_v4 = 0, inherit_v6 = 0,
115		 has_v4 = 0, has_v6 = 0, socktype;
116	char	 buf[64];
117
118	/*
119	 * FIXME: cache this by having a flag on the cert_ip, else we're
120	 * going to need to do a lot of scanning for big allocations.
121	 */
122
123	for (i = 0; i < ipsz; i++)
124		if (ips[i].type == CERT_IP_INHERIT) {
125			if (ips[i].afi == AFI_IPV4)
126				inherit_v4 = 1;
127			else
128				inherit_v6 = 1;
129		} else {
130			if (ips[i].afi == AFI_IPV4)
131				has_v4 = 1;
132			else
133				has_v6 = 1;
134		}
135
136	/* Disallow multiple inheritence per type. */
137
138	if ((inherit_v4 && ip->afi == AFI_IPV4) ||
139	    (inherit_v6 && ip->afi == AFI_IPV6) ||
140	    (has_v4 && ip->afi == AFI_IPV4 &&
141	     ip->type == CERT_IP_INHERIT) ||
142	    (has_v6 && ip->afi == AFI_IPV6 &&
143	     ip->type == CERT_IP_INHERIT)) {
144		warnx("%s: RFC 3779 section 2.2.3.5: cannot have "
145			"multiple inheritence or inheritence and "
146			"addresses of the same class", fn);
147		return 0;
148	}
149
150	/* Check our ranges. */
151
152	for (i = 0; i < ipsz; i++) {
153		if (ips[i].afi != ip->afi)
154			continue;
155		if (memcmp(ips[i].max, ip->min, sz) <= 0 ||
156	  	    memcmp(ips[i].min, ip->max, sz) >= 0)
157			continue;
158		socktype = (ips[i].afi == AFI_IPV4) ? AF_INET : AF_INET6,
159		warnx("%s: RFC 3779 section 2.2.3.5: "
160			"cannot have overlapping IP addresses", fn);
161		ip_addr_print(&ip->ip, ip->afi, buf, sizeof(buf));
162		warnx("%s: certificate IP: %s", fn, buf);
163		inet_ntop(socktype, ip->min, buf, sizeof(buf));
164		warnx("%s: certificate IP minimum: %s", fn, buf);
165		inet_ntop(socktype, ip->max, buf, sizeof(buf));
166		warnx("%s: certificate IP maximum: %s", fn, buf);
167		inet_ntop(socktype, ips[i].min, buf, sizeof(buf));
168		warnx("%s: offending IP minimum: %s", fn, buf);
169		inet_ntop(socktype, ips[i].max, buf, sizeof(buf));
170		warnx("%s: offending IP maximum: %s", fn, buf);
171		return 0;
172	}
173
174	return 1;
175}
176
177/*
178 * Parse an IP address, RFC 3779, 2.2.3.8.
179 * Return zero on failure, non-zero on success.
180 */
181int
182ip_addr_parse(const ASN1_BIT_STRING *p,
183	enum afi afi, const char *fn, struct ip_addr *addr)
184{
185	long	 unused = 0;
186
187	/* Weird OpenSSL-ism to get unused bit count. */
188
189	if ((ASN1_STRING_FLAG_BITS_LEFT & p->flags))
190		unused = ~ASN1_STRING_FLAG_BITS_LEFT & p->flags;
191
192	if (unused < 0) {
193		warnx("%s: RFC 3779 section 2.2.3.8: unused "
194			"bit count must be non-negative", fn);
195		return 0;
196	} else if (unused > 8) {
197		warnx("%s: RFC 3779 section 2.2.3.8: unused "
198			"bit count must mask an unsigned char", fn);
199		return 0;
200	}
201
202	/*
203	 * Check that the unused bits are set to zero.
204	 * If we don't do this, stray bits will corrupt our composition
205	 * of the [minimum] address ranges.
206	 */
207
208	if (p->length &&
209	    (p->data[p->length - 1] & ((1 << unused) - 1))) {
210		warnx("%s: RFC 3779 section 2.2.3.8: unused "
211			"bits must be set to zero", fn);
212		return 0;
213	}
214
215	/* Limit possible sizes of addresses. */
216
217	if ((afi == AFI_IPV4 && p->length > 4) ||
218	    (afi == AFI_IPV6 && p->length > 16)) {
219		warnx("%s: RFC 3779 section 2.2.3.8: "
220			"IP address too long", fn);
221		return 0;
222	}
223
224	addr->unused = unused;
225	addr->sz = p->length;
226	memcpy(addr->addr, p->data, p->length);
227	return 1;
228}
229
230/*
231 * Convert the IPv4 address into CIDR notation conforming to RFC 4632.
232 * Buffer should be able to hold xxx.yyy.zzz.www/nn.
233 */
234static void
235ip4_addr2str(const struct ip_addr *addr, char *b, size_t bsz)
236{
237	size_t	 pos = 0, i;
238
239	assert(bsz >= addr->sz * 4);
240
241	b[0] = '\0';
242
243	for (i = 0; i < addr->sz; i++)
244		pos += snprintf(b + pos, bsz - pos, "%u.", addr->addr[i]);
245	for ( ; i < 4; i++)
246		pos = strlcat(b, "0.", bsz);
247
248	assert(pos > 1);
249	b[--pos] = '\0';
250
251	/* Prefix mask only if we don't have all bits set. */
252
253	snprintf(b + pos, bsz - pos, "/%zu", addr->sz * 8 - addr->unused);
254}
255
256/*
257 * Convert the IPv6 address into CIDR notation conforming to RFC 4291.
258 * See also RFC 5952.
259 * Must hold 0000:0000:0000:0000:0000:0000:0000:0000/nn.
260 */
261static void
262ip6_addr2str(const struct ip_addr *addr, char *b, size_t bsz)
263{
264	size_t	 i, sz, pos = 0;
265	char	 buf[16];
266	uint16_t v;
267
268	/*
269	 * Address is grouped into pairs of bytes and we may have an odd
270	 * number of bytes, so fill into a well-sized buffer to avoid
271	 * complexities of handling the odd man out.
272	 */
273
274	assert(addr->sz <= sizeof(buf));
275	memset(buf, 0, sizeof(buf));
276	memcpy(buf, addr->addr, addr->sz);
277	sz = addr->sz;
278	if ((sz % 2))
279		sz++;
280	assert(sz <= sizeof(buf));
281
282	/* Don't print trailing zeroes. */
283
284	if (sz >= 2) {
285		for (i = sz - 2; i > 0; i -= 2)
286			if ((v = htons(*(uint16_t *)&buf[i])) == 0)
287				sz -= 2;
288			else
289				break;
290	}
291
292	b[0] = '\0';
293	for (i = 0; i < sz; i += 2) {
294		v = htons(*(uint16_t *)&buf[i]);
295		pos += snprintf(b + pos, bsz - pos, "%hx:", v);
296	}
297
298	/*
299	 * If we have nothing, just use "0::".
300	 * If we have a remaining 4+ octets that weren't specified and
301	 * are thus zero, compress them into "::".
302	 * Otherwise, truncate the last ":" as above.
303	 */
304
305	if (sz == 0)
306		pos = strlcat(b, "0::", bsz);
307	else if (sz < 12)
308		pos = strlcat(b, ":", bsz);
309	else
310		b[--pos] = '\0';
311
312	snprintf(b + pos, bsz - pos, "/%zu", addr->sz * 8 - addr->unused);
313}
314
315/*
316 * Convert a ip_addr into a NUL-terminated CIDR notation string
317 * conforming to RFC 4632 or 4291.
318 * The size of the buffer must be at least 64 (inclusive).
319 */
320void
321ip_addr_print(const struct ip_addr *addr,
322	enum afi afi, char *buf, size_t bufsz)
323{
324
325	if (afi == AFI_IPV4)
326		ip4_addr2str(addr, buf, bufsz);
327	else
328		ip6_addr2str(addr, buf, bufsz);
329}
330
331/*
332 * Serialise an ip_addr for sending over the wire.
333 * Matched with ip_addr_read().
334 */
335void
336ip_addr_buffer(char **b, size_t *bsz,
337	size_t *bmax, const struct ip_addr *p)
338{
339
340	io_simple_buffer(b, bsz, bmax, &p->sz, sizeof(size_t));
341	assert(p->sz <= 16);
342	io_simple_buffer(b, bsz, bmax, p->addr, p->sz);
343	io_simple_buffer(b, bsz, bmax, &p->unused, sizeof(size_t));
344}
345
346/*
347 * Serialise an ip_addr_range for sending over the wire.
348 * Matched with ip_addr_range_read().
349 */
350void
351ip_addr_range_buffer(char **b, size_t *bsz,
352	size_t *bmax, const struct ip_addr_range *p)
353{
354
355	ip_addr_buffer(b, bsz, bmax, &p->min);
356	ip_addr_buffer(b, bsz, bmax, &p->max);
357}
358
359/*
360 * Read an ip_addr from the wire.
361 * Matched with ip_addr_buffer().
362 */
363void
364ip_addr_read(int fd, struct ip_addr *p)
365{
366
367	io_simple_read(fd, &p->sz, sizeof(size_t));
368	assert(p->sz <= 16);
369	io_simple_read(fd, p->addr, p->sz);
370	io_simple_read(fd, &p->unused, sizeof(size_t));
371}
372
373/*
374 * Read an ip_addr_range from the wire.
375 * Matched with ip_addr_range_buffer().
376 */
377void
378ip_addr_range_read(int fd, struct ip_addr_range *p)
379{
380
381	ip_addr_read(fd, &p->min);
382	ip_addr_read(fd, &p->max);
383}
384
385/*
386 * Given the addresses (range or IP) in cert_ip, fill in the "min" and
387 * "max" fields with the minimum and maximum possible IP addresses given
388 * those ranges (or singleton prefixed range).
389 * This does nothing if CERT_IP_INHERIT.
390 * Returns zero on failure (misordered ranges), non-zero on success.
391 */
392int
393ip_cert_compose_ranges(struct cert_ip *p)
394{
395	size_t	 sz = AFI_IPV4 == p->afi ? 4 : 16;
396
397	switch (p->type) {
398	case CERT_IP_ADDR:
399		memset(p->min, 0x00, sizeof(p->min));
400		memcpy(p->min, p->ip.addr, p->ip.sz);
401		assert(p->ip.unused <= 8);
402		memset(p->max, 0xff, sizeof(p->max));
403		memcpy(p->max, p->ip.addr, p->ip.sz);
404		p->max[p->ip.sz - 1] |= (1 << p->ip.unused) - 1;
405		break;
406	case CERT_IP_RANGE:
407		memset(p->min, 0x00, sizeof(p->min));
408		memcpy(p->min, p->range.min.addr, p->range.min.sz);
409		assert(p->range.max.unused <= 8);
410		memset(p->max, 0xff, sizeof(p->max));
411		memcpy(p->max, p->range.max.addr, p->range.max.sz);
412		p->max[p->range.max.sz - 1] |= (1 << p->range.max.unused) - 1;
413		break;
414	default:
415		return 1;
416	}
417
418	return memcmp(p->min, p->max, sz) <= 0;
419}
420
421/*
422 * Given the ROA's acceptable prefix, compute the minimum and maximum
423 * address accepted by the prefix.
424 */
425void
426ip_roa_compose_ranges(struct roa_ip *p)
427{
428
429	memset(p->min, 0x00, sizeof(p->min));
430	memcpy(p->min, p->addr.addr, p->addr.sz);
431	assert(p->addr.unused <= 8);
432	memset(p->max, 0xff, sizeof(p->max));
433	memcpy(p->max, p->addr.addr, p->addr.sz);
434	p->max[p->addr.sz - 1] |= (1 << p->addr.unused) - 1;
435}
436