xref: /freebsd/contrib/unbound/util/net_help.c (revision f3c5273d315a64826d2149ac453ff8c4583ddbe8)
1 /*
2  * util/net_help.c - implementation of the network helper code
3  *
4  * Copyright (c) 2007, NLnet Labs. All rights reserved.
5  *
6  * This software is open source.
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  * Redistributions of source code must retain the above copyright notice,
13  * this list of conditions and the following disclaimer.
14  *
15  * Redistributions in binary form must reproduce the above copyright notice,
16  * this list of conditions and the following disclaimer in the documentation
17  * and/or other materials provided with the distribution.
18  *
19  * Neither the name of the NLNET LABS nor the names of its contributors may
20  * be used to endorse or promote products derived from this software without
21  * specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27  * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
29  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
30  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
32  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  */
35 /**
36  * \file
37  * Implementation of net_help.h.
38  */
39 
40 #include "config.h"
41 #include "util/net_help.h"
42 #include "util/log.h"
43 #include "util/data/dname.h"
44 #include "util/module.h"
45 #include "util/regional.h"
46 #include "sldns/parseutil.h"
47 #include "sldns/wire2str.h"
48 #include <fcntl.h>
49 #ifdef HAVE_OPENSSL_SSL_H
50 #include <openssl/ssl.h>
51 #endif
52 #ifdef HAVE_OPENSSL_ERR_H
53 #include <openssl/err.h>
54 #endif
55 #ifdef USE_WINSOCK
56 #include <wincrypt.h>
57 #endif
58 
59 /** max length of an IP address (the address portion) that we allow */
60 #define MAX_ADDR_STRLEN 128 /* characters */
61 /** default value for EDNS ADVERTISED size */
62 uint16_t EDNS_ADVERTISED_SIZE = 4096;
63 
64 /** minimal responses when positive answer: default is no */
65 int MINIMAL_RESPONSES = 0;
66 
67 /** rrset order roundrobin: default is no */
68 int RRSET_ROUNDROBIN = 0;
69 
70 /* returns true is string addr is an ip6 specced address */
71 int
72 str_is_ip6(const char* str)
73 {
74 	if(strchr(str, ':'))
75 		return 1;
76 	else    return 0;
77 }
78 
79 int
80 fd_set_nonblock(int s)
81 {
82 #ifdef HAVE_FCNTL
83 	int flag;
84 	if((flag = fcntl(s, F_GETFL)) == -1) {
85 		log_err("can't fcntl F_GETFL: %s", strerror(errno));
86 		flag = 0;
87 	}
88 	flag |= O_NONBLOCK;
89 	if(fcntl(s, F_SETFL, flag) == -1) {
90 		log_err("can't fcntl F_SETFL: %s", strerror(errno));
91 		return 0;
92 	}
93 #elif defined(HAVE_IOCTLSOCKET)
94 	unsigned long on = 1;
95 	if(ioctlsocket(s, FIONBIO, &on) != 0) {
96 		log_err("can't ioctlsocket FIONBIO on: %s",
97 			wsa_strerror(WSAGetLastError()));
98 	}
99 #endif
100 	return 1;
101 }
102 
103 int
104 fd_set_block(int s)
105 {
106 #ifdef HAVE_FCNTL
107 	int flag;
108 	if((flag = fcntl(s, F_GETFL)) == -1) {
109 		log_err("cannot fcntl F_GETFL: %s", strerror(errno));
110 		flag = 0;
111 	}
112 	flag &= ~O_NONBLOCK;
113 	if(fcntl(s, F_SETFL, flag) == -1) {
114 		log_err("cannot fcntl F_SETFL: %s", strerror(errno));
115 		return 0;
116 	}
117 #elif defined(HAVE_IOCTLSOCKET)
118 	unsigned long off = 0;
119 	if(ioctlsocket(s, FIONBIO, &off) != 0) {
120 		if(WSAGetLastError() != WSAEINVAL || verbosity >= 4)
121 			log_err("can't ioctlsocket FIONBIO off: %s",
122 				wsa_strerror(WSAGetLastError()));
123 	}
124 #endif
125 	return 1;
126 }
127 
128 int
129 is_pow2(size_t num)
130 {
131 	if(num == 0) return 1;
132 	return (num & (num-1)) == 0;
133 }
134 
135 void*
136 memdup(void* data, size_t len)
137 {
138 	void* d;
139 	if(!data) return NULL;
140 	if(len == 0) return NULL;
141 	d = malloc(len);
142 	if(!d) return NULL;
143 	memcpy(d, data, len);
144 	return d;
145 }
146 
147 void
148 log_addr(enum verbosity_value v, const char* str,
149 	struct sockaddr_storage* addr, socklen_t addrlen)
150 {
151 	uint16_t port;
152 	const char* family = "unknown";
153 	char dest[100];
154 	int af = (int)((struct sockaddr_in*)addr)->sin_family;
155 	void* sinaddr = &((struct sockaddr_in*)addr)->sin_addr;
156 	if(verbosity < v)
157 		return;
158 	switch(af) {
159 		case AF_INET: family="ip4"; break;
160 		case AF_INET6: family="ip6";
161 			sinaddr = &((struct sockaddr_in6*)addr)->sin6_addr;
162 			break;
163 		case AF_LOCAL:
164 			dest[0]=0;
165 			(void)inet_ntop(af, sinaddr, dest,
166 				(socklen_t)sizeof(dest));
167 			verbose(v, "%s local %s", str, dest);
168 			return; /* do not continue and try to get port */
169 		default: break;
170 	}
171 	if(inet_ntop(af, sinaddr, dest, (socklen_t)sizeof(dest)) == 0) {
172 		(void)strlcpy(dest, "(inet_ntop error)", sizeof(dest));
173 	}
174 	dest[sizeof(dest)-1] = 0;
175 	port = ntohs(((struct sockaddr_in*)addr)->sin_port);
176 	if(verbosity >= 4)
177 		verbose(v, "%s %s %s port %d (len %d)", str, family, dest,
178 			(int)port, (int)addrlen);
179 	else	verbose(v, "%s %s port %d", str, dest, (int)port);
180 }
181 
182 int
183 extstrtoaddr(const char* str, struct sockaddr_storage* addr,
184 	socklen_t* addrlen)
185 {
186 	char* s;
187 	int port = UNBOUND_DNS_PORT;
188 	if((s=strchr(str, '@'))) {
189 		char buf[MAX_ADDR_STRLEN];
190 		if(s-str >= MAX_ADDR_STRLEN) {
191 			return 0;
192 		}
193 		(void)strlcpy(buf, str, sizeof(buf));
194 		buf[s-str] = 0;
195 		port = atoi(s+1);
196 		if(port == 0 && strcmp(s+1,"0")!=0) {
197 			return 0;
198 		}
199 		return ipstrtoaddr(buf, port, addr, addrlen);
200 	}
201 	return ipstrtoaddr(str, port, addr, addrlen);
202 }
203 
204 
205 int
206 ipstrtoaddr(const char* ip, int port, struct sockaddr_storage* addr,
207 	socklen_t* addrlen)
208 {
209 	uint16_t p;
210 	if(!ip) return 0;
211 	p = (uint16_t) port;
212 	if(str_is_ip6(ip)) {
213 		char buf[MAX_ADDR_STRLEN];
214 		char* s;
215 		struct sockaddr_in6* sa = (struct sockaddr_in6*)addr;
216 		*addrlen = (socklen_t)sizeof(struct sockaddr_in6);
217 		memset(sa, 0, *addrlen);
218 		sa->sin6_family = AF_INET6;
219 		sa->sin6_port = (in_port_t)htons(p);
220 		if((s=strchr(ip, '%'))) { /* ip6%interface, rfc 4007 */
221 			if(s-ip >= MAX_ADDR_STRLEN)
222 				return 0;
223 			(void)strlcpy(buf, ip, sizeof(buf));
224 			buf[s-ip]=0;
225 			sa->sin6_scope_id = (uint32_t)atoi(s+1);
226 			ip = buf;
227 		}
228 		if(inet_pton((int)sa->sin6_family, ip, &sa->sin6_addr) <= 0) {
229 			return 0;
230 		}
231 	} else { /* ip4 */
232 		struct sockaddr_in* sa = (struct sockaddr_in*)addr;
233 		*addrlen = (socklen_t)sizeof(struct sockaddr_in);
234 		memset(sa, 0, *addrlen);
235 		sa->sin_family = AF_INET;
236 		sa->sin_port = (in_port_t)htons(p);
237 		if(inet_pton((int)sa->sin_family, ip, &sa->sin_addr) <= 0) {
238 			return 0;
239 		}
240 	}
241 	return 1;
242 }
243 
244 int netblockstrtoaddr(const char* str, int port, struct sockaddr_storage* addr,
245         socklen_t* addrlen, int* net)
246 {
247 	char buf[64];
248 	char* s;
249 	*net = (str_is_ip6(str)?128:32);
250 	if((s=strchr(str, '/'))) {
251 		if(atoi(s+1) > *net) {
252 			log_err("netblock too large: %s", str);
253 			return 0;
254 		}
255 		*net = atoi(s+1);
256 		if(*net == 0 && strcmp(s+1, "0") != 0) {
257 			log_err("cannot parse netblock: '%s'", str);
258 			return 0;
259 		}
260 		strlcpy(buf, str, sizeof(buf));
261 		s = strchr(buf, '/');
262 		if(s) *s = 0;
263 		s = buf;
264 	}
265 	if(!ipstrtoaddr(s?s:str, port, addr, addrlen)) {
266 		log_err("cannot parse ip address: '%s'", str);
267 		return 0;
268 	}
269 	if(s) {
270 		addr_mask(addr, *addrlen, *net);
271 	}
272 	return 1;
273 }
274 
275 int authextstrtoaddr(char* str, struct sockaddr_storage* addr,
276 	socklen_t* addrlen, char** auth_name)
277 {
278 	char* s;
279 	int port = UNBOUND_DNS_PORT;
280 	if((s=strchr(str, '@'))) {
281 		char buf[MAX_ADDR_STRLEN];
282 		size_t len = (size_t)(s-str);
283 		char* hash = strchr(s+1, '#');
284 		if(hash) {
285 			*auth_name = hash+1;
286 		} else {
287 			*auth_name = NULL;
288 		}
289 		if(len >= MAX_ADDR_STRLEN) {
290 			return 0;
291 		}
292 		(void)strlcpy(buf, str, sizeof(buf));
293 		buf[len] = 0;
294 		port = atoi(s+1);
295 		if(port == 0) {
296 			if(!hash && strcmp(s+1,"0")!=0)
297 				return 0;
298 			if(hash && strncmp(s+1,"0#",2)!=0)
299 				return 0;
300 		}
301 		return ipstrtoaddr(buf, port, addr, addrlen);
302 	}
303 	if((s=strchr(str, '#'))) {
304 		char buf[MAX_ADDR_STRLEN];
305 		size_t len = (size_t)(s-str);
306 		if(len >= MAX_ADDR_STRLEN) {
307 			return 0;
308 		}
309 		(void)strlcpy(buf, str, sizeof(buf));
310 		buf[len] = 0;
311 		port = UNBOUND_DNS_OVER_TLS_PORT;
312 		*auth_name = s+1;
313 		return ipstrtoaddr(buf, port, addr, addrlen);
314 	}
315 	*auth_name = NULL;
316 	return ipstrtoaddr(str, port, addr, addrlen);
317 }
318 
319 /** store port number into sockaddr structure */
320 void
321 sockaddr_store_port(struct sockaddr_storage* addr, socklen_t addrlen, int port)
322 {
323 	if(addr_is_ip6(addr, addrlen)) {
324 		struct sockaddr_in6* sa = (struct sockaddr_in6*)addr;
325 		sa->sin6_port = (in_port_t)htons((uint16_t)port);
326 	} else {
327 		struct sockaddr_in* sa = (struct sockaddr_in*)addr;
328 		sa->sin_port = (in_port_t)htons((uint16_t)port);
329 	}
330 }
331 
332 void
333 log_nametypeclass(enum verbosity_value v, const char* str, uint8_t* name,
334 	uint16_t type, uint16_t dclass)
335 {
336 	char buf[LDNS_MAX_DOMAINLEN+1];
337 	char t[12], c[12];
338 	const char *ts, *cs;
339 	if(verbosity < v)
340 		return;
341 	dname_str(name, buf);
342 	if(type == LDNS_RR_TYPE_TSIG) ts = "TSIG";
343 	else if(type == LDNS_RR_TYPE_IXFR) ts = "IXFR";
344 	else if(type == LDNS_RR_TYPE_AXFR) ts = "AXFR";
345 	else if(type == LDNS_RR_TYPE_MAILB) ts = "MAILB";
346 	else if(type == LDNS_RR_TYPE_MAILA) ts = "MAILA";
347 	else if(type == LDNS_RR_TYPE_ANY) ts = "ANY";
348 	else if(sldns_rr_descript(type) && sldns_rr_descript(type)->_name)
349 		ts = sldns_rr_descript(type)->_name;
350 	else {
351 		snprintf(t, sizeof(t), "TYPE%d", (int)type);
352 		ts = t;
353 	}
354 	if(sldns_lookup_by_id(sldns_rr_classes, (int)dclass) &&
355 		sldns_lookup_by_id(sldns_rr_classes, (int)dclass)->name)
356 		cs = sldns_lookup_by_id(sldns_rr_classes, (int)dclass)->name;
357 	else {
358 		snprintf(c, sizeof(c), "CLASS%d", (int)dclass);
359 		cs = c;
360 	}
361 	log_info("%s %s %s %s", str, buf, ts, cs);
362 }
363 
364 void log_name_addr(enum verbosity_value v, const char* str, uint8_t* zone,
365 	struct sockaddr_storage* addr, socklen_t addrlen)
366 {
367 	uint16_t port;
368 	const char* family = "unknown_family ";
369 	char namebuf[LDNS_MAX_DOMAINLEN+1];
370 	char dest[100];
371 	int af = (int)((struct sockaddr_in*)addr)->sin_family;
372 	void* sinaddr = &((struct sockaddr_in*)addr)->sin_addr;
373 	if(verbosity < v)
374 		return;
375 	switch(af) {
376 		case AF_INET: family=""; break;
377 		case AF_INET6: family="";
378 			sinaddr = &((struct sockaddr_in6*)addr)->sin6_addr;
379 			break;
380 		case AF_LOCAL: family="local "; break;
381 		default: break;
382 	}
383 	if(inet_ntop(af, sinaddr, dest, (socklen_t)sizeof(dest)) == 0) {
384 		(void)strlcpy(dest, "(inet_ntop error)", sizeof(dest));
385 	}
386 	dest[sizeof(dest)-1] = 0;
387 	port = ntohs(((struct sockaddr_in*)addr)->sin_port);
388 	dname_str(zone, namebuf);
389 	if(af != AF_INET && af != AF_INET6)
390 		verbose(v, "%s <%s> %s%s#%d (addrlen %d)",
391 			str, namebuf, family, dest, (int)port, (int)addrlen);
392 	else	verbose(v, "%s <%s> %s%s#%d",
393 			str, namebuf, family, dest, (int)port);
394 }
395 
396 void log_err_addr(const char* str, const char* err,
397 	struct sockaddr_storage* addr, socklen_t addrlen)
398 {
399 	uint16_t port;
400 	char dest[100];
401 	int af = (int)((struct sockaddr_in*)addr)->sin_family;
402 	void* sinaddr = &((struct sockaddr_in*)addr)->sin_addr;
403 	if(af == AF_INET6)
404 		sinaddr = &((struct sockaddr_in6*)addr)->sin6_addr;
405 	if(inet_ntop(af, sinaddr, dest, (socklen_t)sizeof(dest)) == 0) {
406 		(void)strlcpy(dest, "(inet_ntop error)", sizeof(dest));
407 	}
408 	dest[sizeof(dest)-1] = 0;
409 	port = ntohs(((struct sockaddr_in*)addr)->sin_port);
410 	if(verbosity >= 4)
411 		log_err("%s: %s for %s port %d (len %d)", str, err, dest,
412 			(int)port, (int)addrlen);
413 	else	log_err("%s: %s for %s port %d", str, err, dest, (int)port);
414 }
415 
416 int
417 sockaddr_cmp(struct sockaddr_storage* addr1, socklen_t len1,
418 	struct sockaddr_storage* addr2, socklen_t len2)
419 {
420 	struct sockaddr_in* p1_in = (struct sockaddr_in*)addr1;
421 	struct sockaddr_in* p2_in = (struct sockaddr_in*)addr2;
422 	struct sockaddr_in6* p1_in6 = (struct sockaddr_in6*)addr1;
423 	struct sockaddr_in6* p2_in6 = (struct sockaddr_in6*)addr2;
424 	if(len1 < len2)
425 		return -1;
426 	if(len1 > len2)
427 		return 1;
428 	log_assert(len1 == len2);
429 	if( p1_in->sin_family < p2_in->sin_family)
430 		return -1;
431 	if( p1_in->sin_family > p2_in->sin_family)
432 		return 1;
433 	log_assert( p1_in->sin_family == p2_in->sin_family );
434 	/* compare ip4 */
435 	if( p1_in->sin_family == AF_INET ) {
436 		/* just order it, ntohs not required */
437 		if(p1_in->sin_port < p2_in->sin_port)
438 			return -1;
439 		if(p1_in->sin_port > p2_in->sin_port)
440 			return 1;
441 		log_assert(p1_in->sin_port == p2_in->sin_port);
442 		return memcmp(&p1_in->sin_addr, &p2_in->sin_addr, INET_SIZE);
443 	} else if (p1_in6->sin6_family == AF_INET6) {
444 		/* just order it, ntohs not required */
445 		if(p1_in6->sin6_port < p2_in6->sin6_port)
446 			return -1;
447 		if(p1_in6->sin6_port > p2_in6->sin6_port)
448 			return 1;
449 		log_assert(p1_in6->sin6_port == p2_in6->sin6_port);
450 		return memcmp(&p1_in6->sin6_addr, &p2_in6->sin6_addr,
451 			INET6_SIZE);
452 	} else {
453 		/* eek unknown type, perform this comparison for sanity. */
454 		return memcmp(addr1, addr2, len1);
455 	}
456 }
457 
458 int
459 sockaddr_cmp_addr(struct sockaddr_storage* addr1, socklen_t len1,
460 	struct sockaddr_storage* addr2, socklen_t len2)
461 {
462 	struct sockaddr_in* p1_in = (struct sockaddr_in*)addr1;
463 	struct sockaddr_in* p2_in = (struct sockaddr_in*)addr2;
464 	struct sockaddr_in6* p1_in6 = (struct sockaddr_in6*)addr1;
465 	struct sockaddr_in6* p2_in6 = (struct sockaddr_in6*)addr2;
466 	if(len1 < len2)
467 		return -1;
468 	if(len1 > len2)
469 		return 1;
470 	log_assert(len1 == len2);
471 	if( p1_in->sin_family < p2_in->sin_family)
472 		return -1;
473 	if( p1_in->sin_family > p2_in->sin_family)
474 		return 1;
475 	log_assert( p1_in->sin_family == p2_in->sin_family );
476 	/* compare ip4 */
477 	if( p1_in->sin_family == AF_INET ) {
478 		return memcmp(&p1_in->sin_addr, &p2_in->sin_addr, INET_SIZE);
479 	} else if (p1_in6->sin6_family == AF_INET6) {
480 		return memcmp(&p1_in6->sin6_addr, &p2_in6->sin6_addr,
481 			INET6_SIZE);
482 	} else {
483 		/* eek unknown type, perform this comparison for sanity. */
484 		return memcmp(addr1, addr2, len1);
485 	}
486 }
487 
488 int
489 addr_is_ip6(struct sockaddr_storage* addr, socklen_t len)
490 {
491 	if(len == (socklen_t)sizeof(struct sockaddr_in6) &&
492 		((struct sockaddr_in6*)addr)->sin6_family == AF_INET6)
493 		return 1;
494 	else    return 0;
495 }
496 
497 void
498 addr_mask(struct sockaddr_storage* addr, socklen_t len, int net)
499 {
500 	uint8_t mask[8] = {0x0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe};
501 	int i, max;
502 	uint8_t* s;
503 	if(addr_is_ip6(addr, len)) {
504 		s = (uint8_t*)&((struct sockaddr_in6*)addr)->sin6_addr;
505 		max = 128;
506 	} else {
507 		s = (uint8_t*)&((struct sockaddr_in*)addr)->sin_addr;
508 		max = 32;
509 	}
510 	if(net >= max)
511 		return;
512 	for(i=net/8+1; i<max/8; i++) {
513 		s[i] = 0;
514 	}
515 	s[net/8] &= mask[net&0x7];
516 }
517 
518 int
519 addr_in_common(struct sockaddr_storage* addr1, int net1,
520 	struct sockaddr_storage* addr2, int net2, socklen_t addrlen)
521 {
522 	int min = (net1<net2)?net1:net2;
523 	int i, to;
524 	int match = 0;
525 	uint8_t* s1, *s2;
526 	if(addr_is_ip6(addr1, addrlen)) {
527 		s1 = (uint8_t*)&((struct sockaddr_in6*)addr1)->sin6_addr;
528 		s2 = (uint8_t*)&((struct sockaddr_in6*)addr2)->sin6_addr;
529 		to = 16;
530 	} else {
531 		s1 = (uint8_t*)&((struct sockaddr_in*)addr1)->sin_addr;
532 		s2 = (uint8_t*)&((struct sockaddr_in*)addr2)->sin_addr;
533 		to = 4;
534 	}
535 	/* match = bits_in_common(s1, s2, to); */
536 	for(i=0; i<to; i++) {
537 		if(s1[i] == s2[i]) {
538 			match += 8;
539 		} else {
540 			uint8_t z = s1[i]^s2[i];
541 			log_assert(z);
542 			while(!(z&0x80)) {
543 				match++;
544 				z<<=1;
545 			}
546 			break;
547 		}
548 	}
549 	if(match > min) match = min;
550 	return match;
551 }
552 
553 void
554 addr_to_str(struct sockaddr_storage* addr, socklen_t addrlen,
555 	char* buf, size_t len)
556 {
557 	int af = (int)((struct sockaddr_in*)addr)->sin_family;
558 	void* sinaddr = &((struct sockaddr_in*)addr)->sin_addr;
559 	if(addr_is_ip6(addr, addrlen))
560 		sinaddr = &((struct sockaddr_in6*)addr)->sin6_addr;
561 	if(inet_ntop(af, sinaddr, buf, (socklen_t)len) == 0) {
562 		snprintf(buf, len, "(inet_ntop_error)");
563 	}
564 }
565 
566 int
567 addr_is_ip4mapped(struct sockaddr_storage* addr, socklen_t addrlen)
568 {
569 	/* prefix for ipv4 into ipv6 mapping is ::ffff:x.x.x.x */
570 	const uint8_t map_prefix[16] =
571 		{0,0,0,0,  0,0,0,0, 0,0,0xff,0xff, 0,0,0,0};
572 	uint8_t* s;
573 	if(!addr_is_ip6(addr, addrlen))
574 		return 0;
575 	/* s is 16 octet ipv6 address string */
576 	s = (uint8_t*)&((struct sockaddr_in6*)addr)->sin6_addr;
577 	return (memcmp(s, map_prefix, 12) == 0);
578 }
579 
580 int addr_is_broadcast(struct sockaddr_storage* addr, socklen_t addrlen)
581 {
582 	int af = (int)((struct sockaddr_in*)addr)->sin_family;
583 	void* sinaddr = &((struct sockaddr_in*)addr)->sin_addr;
584 	return af == AF_INET && addrlen>=(socklen_t)sizeof(struct sockaddr_in)
585 		&& memcmp(sinaddr, "\377\377\377\377", 4) == 0;
586 }
587 
588 int addr_is_any(struct sockaddr_storage* addr, socklen_t addrlen)
589 {
590 	int af = (int)((struct sockaddr_in*)addr)->sin_family;
591 	void* sinaddr = &((struct sockaddr_in*)addr)->sin_addr;
592 	void* sin6addr = &((struct sockaddr_in6*)addr)->sin6_addr;
593 	if(af == AF_INET && addrlen>=(socklen_t)sizeof(struct sockaddr_in)
594 		&& memcmp(sinaddr, "\000\000\000\000", 4) == 0)
595 		return 1;
596 	else if(af==AF_INET6 && addrlen>=(socklen_t)sizeof(struct sockaddr_in6)
597 		&& memcmp(sin6addr, "\000\000\000\000\000\000\000\000"
598 		"\000\000\000\000\000\000\000\000", 16) == 0)
599 		return 1;
600 	return 0;
601 }
602 
603 void sock_list_insert(struct sock_list** list, struct sockaddr_storage* addr,
604 	socklen_t len, struct regional* region)
605 {
606 	struct sock_list* add = (struct sock_list*)regional_alloc(region,
607 		sizeof(*add) - sizeof(add->addr) + (size_t)len);
608 	if(!add) {
609 		log_err("out of memory in socketlist insert");
610 		return;
611 	}
612 	log_assert(list);
613 	add->next = *list;
614 	add->len = len;
615 	*list = add;
616 	if(len) memmove(&add->addr, addr, len);
617 }
618 
619 void sock_list_prepend(struct sock_list** list, struct sock_list* add)
620 {
621 	struct sock_list* last = add;
622 	if(!last)
623 		return;
624 	while(last->next)
625 		last = last->next;
626 	last->next = *list;
627 	*list = add;
628 }
629 
630 int sock_list_find(struct sock_list* list, struct sockaddr_storage* addr,
631         socklen_t len)
632 {
633 	while(list) {
634 		if(len == list->len) {
635 			if(len == 0 || sockaddr_cmp_addr(addr, len,
636 				&list->addr, list->len) == 0)
637 				return 1;
638 		}
639 		list = list->next;
640 	}
641 	return 0;
642 }
643 
644 void sock_list_merge(struct sock_list** list, struct regional* region,
645 	struct sock_list* add)
646 {
647 	struct sock_list* p;
648 	for(p=add; p; p=p->next) {
649 		if(!sock_list_find(*list, &p->addr, p->len))
650 			sock_list_insert(list, &p->addr, p->len, region);
651 	}
652 }
653 
654 void
655 log_crypto_err(const char* str)
656 {
657 #ifdef HAVE_SSL
658 	/* error:[error code]:[library name]:[function name]:[reason string] */
659 	char buf[128];
660 	unsigned long e;
661 	ERR_error_string_n(ERR_get_error(), buf, sizeof(buf));
662 	log_err("%s crypto %s", str, buf);
663 	while( (e=ERR_get_error()) ) {
664 		ERR_error_string_n(e, buf, sizeof(buf));
665 		log_err("and additionally crypto %s", buf);
666 	}
667 #else
668 	(void)str;
669 #endif /* HAVE_SSL */
670 }
671 
672 int
673 listen_sslctx_setup(void* ctxt)
674 {
675 #ifdef HAVE_SSL
676 	SSL_CTX* ctx = (SSL_CTX*)ctxt;
677 	/* no SSLv2, SSLv3 because has defects */
678 	if((SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2) & SSL_OP_NO_SSLv2)
679 		!= SSL_OP_NO_SSLv2){
680 		log_crypto_err("could not set SSL_OP_NO_SSLv2");
681 		return 0;
682 	}
683 	if((SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv3) & SSL_OP_NO_SSLv3)
684 		!= SSL_OP_NO_SSLv3){
685 		log_crypto_err("could not set SSL_OP_NO_SSLv3");
686 		return 0;
687 	}
688 #if defined(SSL_OP_NO_TLSv1) && defined(SSL_OP_NO_TLSv1_1)
689 	/* if we have tls 1.1 disable 1.0 */
690 	if((SSL_CTX_set_options(ctx, SSL_OP_NO_TLSv1) & SSL_OP_NO_TLSv1)
691 		!= SSL_OP_NO_TLSv1){
692 		log_crypto_err("could not set SSL_OP_NO_TLSv1");
693 		return 0;
694 	}
695 #endif
696 #if defined(SSL_OP_NO_TLSv1_1) && defined(SSL_OP_NO_TLSv1_2)
697 	/* if we have tls 1.2 disable 1.1 */
698 	if((SSL_CTX_set_options(ctx, SSL_OP_NO_TLSv1_1) & SSL_OP_NO_TLSv1_1)
699 		!= SSL_OP_NO_TLSv1_1){
700 		log_crypto_err("could not set SSL_OP_NO_TLSv1_1");
701 		return 0;
702 	}
703 #endif
704 #if defined(SHA256_DIGEST_LENGTH) && defined(USE_ECDSA)
705 	/* if we have sha256, set the cipher list to have no known vulns */
706 	if(!SSL_CTX_set_cipher_list(ctx, "TLS13-CHACHA20-POLY1305-SHA256:TLS13-AES-256-GCM-SHA384:TLS13-AES-128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256"))
707 		log_crypto_err("could not set cipher list with SSL_CTX_set_cipher_list");
708 #endif
709 
710 	if((SSL_CTX_set_options(ctx, SSL_OP_CIPHER_SERVER_PREFERENCE) &
711 		SSL_OP_CIPHER_SERVER_PREFERENCE) !=
712 		SSL_OP_CIPHER_SERVER_PREFERENCE) {
713 		log_crypto_err("could not set SSL_OP_CIPHER_SERVER_PREFERENCE");
714 		return 0;
715 	}
716 
717 #ifdef HAVE_SSL_CTX_SET_SECURITY_LEVEL
718 	SSL_CTX_set_security_level(ctx, 0);
719 #endif
720 #else
721 	(void)ctxt;
722 #endif /* HAVE_SSL */
723 	return 1;
724 }
725 
726 void
727 listen_sslctx_setup_2(void* ctxt)
728 {
729 #ifdef HAVE_SSL
730 	SSL_CTX* ctx = (SSL_CTX*)ctxt;
731 	(void)ctx;
732 #if HAVE_DECL_SSL_CTX_SET_ECDH_AUTO
733 	if(!SSL_CTX_set_ecdh_auto(ctx,1)) {
734 		log_crypto_err("Error in SSL_CTX_ecdh_auto, not enabling ECDHE");
735 	}
736 #elif defined(USE_ECDSA)
737 	if(1) {
738 		EC_KEY *ecdh = EC_KEY_new_by_curve_name (NID_X9_62_prime256v1);
739 		if (!ecdh) {
740 			log_crypto_err("could not find p256, not enabling ECDHE");
741 		} else {
742 			if (1 != SSL_CTX_set_tmp_ecdh (ctx, ecdh)) {
743 				log_crypto_err("Error in SSL_CTX_set_tmp_ecdh, not enabling ECDHE");
744 			}
745 			EC_KEY_free (ecdh);
746 		}
747 	}
748 #endif
749 #else
750 	(void)ctxt;
751 #endif /* HAVE_SSL */
752 }
753 
754 void* listen_sslctx_create(char* key, char* pem, char* verifypem)
755 {
756 #ifdef HAVE_SSL
757 	SSL_CTX* ctx = SSL_CTX_new(SSLv23_server_method());
758 	if(!ctx) {
759 		log_crypto_err("could not SSL_CTX_new");
760 		return NULL;
761 	}
762 	if(!listen_sslctx_setup(ctx)) {
763 		SSL_CTX_free(ctx);
764 		return NULL;
765 	}
766 	if(!SSL_CTX_use_certificate_chain_file(ctx, pem)) {
767 		log_err("error for cert file: %s", pem);
768 		log_crypto_err("error in SSL_CTX use_certificate_chain_file");
769 		SSL_CTX_free(ctx);
770 		return NULL;
771 	}
772 	if(!SSL_CTX_use_PrivateKey_file(ctx, key, SSL_FILETYPE_PEM)) {
773 		log_err("error for private key file: %s", key);
774 		log_crypto_err("Error in SSL_CTX use_PrivateKey_file");
775 		SSL_CTX_free(ctx);
776 		return NULL;
777 	}
778 	if(!SSL_CTX_check_private_key(ctx)) {
779 		log_err("error for key file: %s", key);
780 		log_crypto_err("Error in SSL_CTX check_private_key");
781 		SSL_CTX_free(ctx);
782 		return NULL;
783 	}
784 	listen_sslctx_setup_2(ctx);
785 	if(verifypem && verifypem[0]) {
786 		if(!SSL_CTX_load_verify_locations(ctx, verifypem, NULL)) {
787 			log_crypto_err("Error in SSL_CTX verify locations");
788 			SSL_CTX_free(ctx);
789 			return NULL;
790 		}
791 		SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(
792 			verifypem));
793 		SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
794 	}
795 	return ctx;
796 #else
797 	(void)key; (void)pem; (void)verifypem;
798 	return NULL;
799 #endif
800 }
801 
802 #ifdef USE_WINSOCK
803 /* For windows, the CA trust store is not read by openssl.
804    Add code to open the trust store using wincrypt API and add
805    the root certs into openssl trust store */
806 static int
807 add_WIN_cacerts_to_openssl_store(SSL_CTX* tls_ctx)
808 {
809 	HCERTSTORE      hSystemStore;
810 	PCCERT_CONTEXT  pTargetCert = NULL;
811 	X509_STORE*	store;
812 
813 	verbose(VERB_ALGO, "Adding Windows certificates from system root store to CA store");
814 
815 	/* load just once per context lifetime for this version
816 	   TODO: dynamically update CA trust changes as they are available */
817 	if (!tls_ctx)
818 		return 0;
819 
820 	/* Call wincrypt's CertOpenStore to open the CA root store. */
821 
822 	if ((hSystemStore = CertOpenStore(
823 		CERT_STORE_PROV_SYSTEM,
824 		0,
825 		0,
826 		/* NOTE: mingw does not have this const: replace with 1 << 16 from code
827 		   CERT_SYSTEM_STORE_CURRENT_USER, */
828 		1 << 16,
829 		L"root")) == 0)
830 	{
831 		return 0;
832 	}
833 
834 	store = SSL_CTX_get_cert_store(tls_ctx);
835 	if (!store)
836 		return 0;
837 
838 	/* failure if the CA store is empty or the call fails */
839 	if ((pTargetCert = CertEnumCertificatesInStore(
840 		hSystemStore, pTargetCert)) == 0) {
841 		verbose(VERB_ALGO, "CA certificate store for Windows is empty.");
842 		return 0;
843 	}
844 	/* iterate over the windows cert store and add to openssl store */
845 	do
846 	{
847 		X509 *cert1 = d2i_X509(NULL,
848 			(const unsigned char **)&pTargetCert->pbCertEncoded,
849 			pTargetCert->cbCertEncoded);
850 		if (!cert1) {
851 			/* return error if a cert fails */
852 			verbose(VERB_ALGO, "%s %d:%s",
853 				"Unable to parse certificate in memory",
854 				(int)ERR_get_error(), ERR_error_string(ERR_get_error(), NULL));
855 			return 0;
856 		}
857 		else {
858 			/* return error if a cert add to store fails */
859 			if (X509_STORE_add_cert(store, cert1) == 0) {
860 				unsigned long error = ERR_peek_last_error();
861 
862 				/* Ignore error X509_R_CERT_ALREADY_IN_HASH_TABLE which means the
863 				* certificate is already in the store.  */
864 				if(ERR_GET_LIB(error) != ERR_LIB_X509 ||
865 				   ERR_GET_REASON(error) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
866 					verbose(VERB_ALGO, "%s %d:%s\n",
867 					    "Error adding certificate", (int)ERR_get_error(),
868 					     ERR_error_string(ERR_get_error(), NULL));
869 					X509_free(cert1);
870 					return 0;
871 				}
872 			}
873 			X509_free(cert1);
874 		}
875 	} while ((pTargetCert = CertEnumCertificatesInStore(
876 		hSystemStore, pTargetCert)) != 0);
877 
878 	/* Clean up memory and quit. */
879 	if (pTargetCert)
880 		CertFreeCertificateContext(pTargetCert);
881 	if (hSystemStore)
882 	{
883 		if (!CertCloseStore(
884 			hSystemStore, 0))
885 			return 0;
886 	}
887 	verbose(VERB_ALGO, "Completed adding Windows certificates to CA store successfully");
888 	return 1;
889 }
890 #endif /* USE_WINSOCK */
891 
892 void* connect_sslctx_create(char* key, char* pem, char* verifypem, int wincert)
893 {
894 #ifdef HAVE_SSL
895 	SSL_CTX* ctx = SSL_CTX_new(SSLv23_client_method());
896 	if(!ctx) {
897 		log_crypto_err("could not allocate SSL_CTX pointer");
898 		return NULL;
899 	}
900 	if((SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2) & SSL_OP_NO_SSLv2)
901 		!= SSL_OP_NO_SSLv2) {
902 		log_crypto_err("could not set SSL_OP_NO_SSLv2");
903 		SSL_CTX_free(ctx);
904 		return NULL;
905 	}
906 	if((SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv3) & SSL_OP_NO_SSLv3)
907 		!= SSL_OP_NO_SSLv3) {
908 		log_crypto_err("could not set SSL_OP_NO_SSLv3");
909 		SSL_CTX_free(ctx);
910 		return NULL;
911 	}
912 	if(key && key[0]) {
913 		if(!SSL_CTX_use_certificate_chain_file(ctx, pem)) {
914 			log_err("error in client certificate %s", pem);
915 			log_crypto_err("error in certificate file");
916 			SSL_CTX_free(ctx);
917 			return NULL;
918 		}
919 		if(!SSL_CTX_use_PrivateKey_file(ctx, key, SSL_FILETYPE_PEM)) {
920 			log_err("error in client private key %s", key);
921 			log_crypto_err("error in key file");
922 			SSL_CTX_free(ctx);
923 			return NULL;
924 		}
925 		if(!SSL_CTX_check_private_key(ctx)) {
926 			log_err("error in client key %s", key);
927 			log_crypto_err("error in SSL_CTX_check_private_key");
928 			SSL_CTX_free(ctx);
929 			return NULL;
930 		}
931 	}
932 	if((verifypem && verifypem[0]) || wincert) {
933 		if(verifypem && verifypem[0]) {
934 			if(!SSL_CTX_load_verify_locations(ctx, verifypem, NULL)) {
935 				log_crypto_err("error in SSL_CTX verify");
936 				SSL_CTX_free(ctx);
937 				return NULL;
938 			}
939 		}
940 #ifdef USE_WINSOCK
941 		if(wincert) {
942 			if(!add_WIN_cacerts_to_openssl_store(ctx)) {
943 				log_crypto_err("error in add_WIN_cacerts_to_openssl_store");
944 				SSL_CTX_free(ctx);
945 				return NULL;
946 			}
947 		}
948 #else
949 		(void)wincert;
950 #endif
951 		SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
952 	}
953 	return ctx;
954 #else
955 	(void)key; (void)pem; (void)verifypem; (void)wincert;
956 	return NULL;
957 #endif
958 }
959 
960 void* incoming_ssl_fd(void* sslctx, int fd)
961 {
962 #ifdef HAVE_SSL
963 	SSL* ssl = SSL_new((SSL_CTX*)sslctx);
964 	if(!ssl) {
965 		log_crypto_err("could not SSL_new");
966 		return NULL;
967 	}
968 	SSL_set_accept_state(ssl);
969 	(void)SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
970 	if(!SSL_set_fd(ssl, fd)) {
971 		log_crypto_err("could not SSL_set_fd");
972 		SSL_free(ssl);
973 		return NULL;
974 	}
975 	return ssl;
976 #else
977 	(void)sslctx; (void)fd;
978 	return NULL;
979 #endif
980 }
981 
982 void* outgoing_ssl_fd(void* sslctx, int fd)
983 {
984 #ifdef HAVE_SSL
985 	SSL* ssl = SSL_new((SSL_CTX*)sslctx);
986 	if(!ssl) {
987 		log_crypto_err("could not SSL_new");
988 		return NULL;
989 	}
990 	SSL_set_connect_state(ssl);
991 	(void)SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
992 	if(!SSL_set_fd(ssl, fd)) {
993 		log_crypto_err("could not SSL_set_fd");
994 		SSL_free(ssl);
995 		return NULL;
996 	}
997 	return ssl;
998 #else
999 	(void)sslctx; (void)fd;
1000 	return NULL;
1001 #endif
1002 }
1003 
1004 #if defined(HAVE_SSL) && defined(OPENSSL_THREADS) && !defined(THREADS_DISABLED) && defined(CRYPTO_LOCK) && OPENSSL_VERSION_NUMBER < 0x10100000L
1005 /** global lock list for openssl locks */
1006 static lock_basic_type *ub_openssl_locks = NULL;
1007 
1008 /** callback that gets thread id for openssl */
1009 static unsigned long
1010 ub_crypto_id_cb(void)
1011 {
1012 	return (unsigned long)log_thread_get();
1013 }
1014 
1015 static void
1016 ub_crypto_lock_cb(int mode, int type, const char *ATTR_UNUSED(file),
1017 	int ATTR_UNUSED(line))
1018 {
1019 	if((mode&CRYPTO_LOCK)) {
1020 		lock_basic_lock(&ub_openssl_locks[type]);
1021 	} else {
1022 		lock_basic_unlock(&ub_openssl_locks[type]);
1023 	}
1024 }
1025 #endif /* OPENSSL_THREADS */
1026 
1027 int ub_openssl_lock_init(void)
1028 {
1029 #if defined(HAVE_SSL) && defined(OPENSSL_THREADS) && !defined(THREADS_DISABLED) && defined(CRYPTO_LOCK) && OPENSSL_VERSION_NUMBER < 0x10100000L
1030 	int i;
1031 	ub_openssl_locks = (lock_basic_type*)reallocarray(
1032 		NULL, (size_t)CRYPTO_num_locks(), sizeof(lock_basic_type));
1033 	if(!ub_openssl_locks)
1034 		return 0;
1035 	for(i=0; i<CRYPTO_num_locks(); i++) {
1036 		lock_basic_init(&ub_openssl_locks[i]);
1037 	}
1038 	CRYPTO_set_id_callback(&ub_crypto_id_cb);
1039 	CRYPTO_set_locking_callback(&ub_crypto_lock_cb);
1040 #endif /* OPENSSL_THREADS */
1041 	return 1;
1042 }
1043 
1044 void ub_openssl_lock_delete(void)
1045 {
1046 #if defined(HAVE_SSL) && defined(OPENSSL_THREADS) && !defined(THREADS_DISABLED) && defined(CRYPTO_LOCK) && OPENSSL_VERSION_NUMBER < 0x10100000L
1047 	int i;
1048 	if(!ub_openssl_locks)
1049 		return;
1050 	CRYPTO_set_id_callback(NULL);
1051 	CRYPTO_set_locking_callback(NULL);
1052 	for(i=0; i<CRYPTO_num_locks(); i++) {
1053 		lock_basic_destroy(&ub_openssl_locks[i]);
1054 	}
1055 	free(ub_openssl_locks);
1056 #endif /* OPENSSL_THREADS */
1057 }
1058 
1059