xref: /freebsd/contrib/unbound/util/net_help.c (revision 7ef62cebc2f965b0f640263e179276928885e33d)
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 #ifdef HAVE_SYS_TYPES_H
42 #  include <sys/types.h>
43 #endif
44 #ifdef HAVE_NET_IF_H
45 #include <net/if.h>
46 #endif
47 #ifdef HAVE_NETIOAPI_H
48 #include <netioapi.h>
49 #endif
50 #include "util/net_help.h"
51 #include "util/log.h"
52 #include "util/data/dname.h"
53 #include "util/module.h"
54 #include "util/regional.h"
55 #include "util/config_file.h"
56 #include "sldns/parseutil.h"
57 #include "sldns/wire2str.h"
58 #include "sldns/str2wire.h"
59 #include <fcntl.h>
60 #ifdef HAVE_OPENSSL_SSL_H
61 #include <openssl/ssl.h>
62 #include <openssl/evp.h>
63 #include <openssl/rand.h>
64 #endif
65 #ifdef HAVE_OPENSSL_ERR_H
66 #include <openssl/err.h>
67 #endif
68 #ifdef HAVE_OPENSSL_CORE_NAMES_H
69 #include <openssl/core_names.h>
70 #endif
71 #ifdef USE_WINSOCK
72 #include <wincrypt.h>
73 #endif
74 #ifdef HAVE_NGHTTP2_NGHTTP2_H
75 #include <nghttp2/nghttp2.h>
76 #endif
77 
78 /** max length of an IP address (the address portion) that we allow */
79 #define MAX_ADDR_STRLEN 128 /* characters */
80 /** default value for EDNS ADVERTISED size */
81 uint16_t EDNS_ADVERTISED_SIZE = 4096;
82 
83 /** minimal responses when positive answer: default is no */
84 int MINIMAL_RESPONSES = 0;
85 
86 /** rrset order roundrobin: default is yes */
87 int RRSET_ROUNDROBIN = 1;
88 
89 /** log tag queries with name instead of 'info' for filtering */
90 int LOG_TAG_QUERYREPLY = 0;
91 
92 static struct tls_session_ticket_key {
93 	unsigned char *key_name;
94 	unsigned char *aes_key;
95 	unsigned char *hmac_key;
96 } *ticket_keys;
97 
98 #ifdef HAVE_SSL
99 /**
100  * callback TLS session ticket encrypt and decrypt
101  * For use with SSL_CTX_set_tlsext_ticket_key_cb or
102  * SSL_CTX_set_tlsext_ticket_key_evp_cb
103  * @param s: the SSL_CTX to use (from connect_sslctx_create())
104  * @param key_name: secret name, 16 bytes
105  * @param iv: up to EVP_MAX_IV_LENGTH.
106  * @param evp_ctx: the evp cipher context, function sets this.
107  * @param hmac_ctx: the hmac context, function sets this.
108  * 	with ..key_cb it is of type HMAC_CTX*
109  * 	with ..key_evp_cb it is of type EVP_MAC_CTX*
110  * @param enc: 1 is encrypt, 0 is decrypt
111  * @return 0 on no ticket, 1 for okay, and 2 for okay but renew the ticket
112  * 	(the ticket is decrypt only). and <0 for failures.
113  */
114 int tls_session_ticket_key_cb(SSL *s, unsigned char* key_name,
115 	unsigned char* iv, EVP_CIPHER_CTX *evp_ctx,
116 #ifdef HAVE_SSL_CTX_SET_TLSEXT_TICKET_KEY_EVP_CB
117 	EVP_MAC_CTX *hmac_ctx,
118 #else
119 	HMAC_CTX* hmac_ctx,
120 #endif
121 	int enc);
122 #endif /* HAVE_SSL */
123 
124 /* returns true is string addr is an ip6 specced address */
125 int
126 str_is_ip6(const char* str)
127 {
128 	if(strchr(str, ':'))
129 		return 1;
130 	else    return 0;
131 }
132 
133 int
134 fd_set_nonblock(int s)
135 {
136 #ifdef HAVE_FCNTL
137 	int flag;
138 	if((flag = fcntl(s, F_GETFL)) == -1) {
139 		log_err("can't fcntl F_GETFL: %s", strerror(errno));
140 		flag = 0;
141 	}
142 	flag |= O_NONBLOCK;
143 	if(fcntl(s, F_SETFL, flag) == -1) {
144 		log_err("can't fcntl F_SETFL: %s", strerror(errno));
145 		return 0;
146 	}
147 #elif defined(HAVE_IOCTLSOCKET)
148 	unsigned long on = 1;
149 	if(ioctlsocket(s, FIONBIO, &on) != 0) {
150 		log_err("can't ioctlsocket FIONBIO on: %s",
151 			wsa_strerror(WSAGetLastError()));
152 	}
153 #endif
154 	return 1;
155 }
156 
157 int
158 fd_set_block(int s)
159 {
160 #ifdef HAVE_FCNTL
161 	int flag;
162 	if((flag = fcntl(s, F_GETFL)) == -1) {
163 		log_err("cannot fcntl F_GETFL: %s", strerror(errno));
164 		flag = 0;
165 	}
166 	flag &= ~O_NONBLOCK;
167 	if(fcntl(s, F_SETFL, flag) == -1) {
168 		log_err("cannot fcntl F_SETFL: %s", strerror(errno));
169 		return 0;
170 	}
171 #elif defined(HAVE_IOCTLSOCKET)
172 	unsigned long off = 0;
173 	if(ioctlsocket(s, FIONBIO, &off) != 0) {
174 		if(WSAGetLastError() != WSAEINVAL || verbosity >= 4)
175 			log_err("can't ioctlsocket FIONBIO off: %s",
176 				wsa_strerror(WSAGetLastError()));
177 	}
178 #endif
179 	return 1;
180 }
181 
182 int
183 is_pow2(size_t num)
184 {
185 	if(num == 0) return 1;
186 	return (num & (num-1)) == 0;
187 }
188 
189 void*
190 memdup(void* data, size_t len)
191 {
192 	void* d;
193 	if(!data) return NULL;
194 	if(len == 0) return NULL;
195 	d = malloc(len);
196 	if(!d) return NULL;
197 	memcpy(d, data, len);
198 	return d;
199 }
200 
201 void
202 log_addr(enum verbosity_value v, const char* str,
203 	struct sockaddr_storage* addr, socklen_t addrlen)
204 {
205 	uint16_t port;
206 	const char* family = "unknown";
207 	char dest[100];
208 	int af = (int)((struct sockaddr_in*)addr)->sin_family;
209 	void* sinaddr = &((struct sockaddr_in*)addr)->sin_addr;
210 	if(verbosity < v)
211 		return;
212 	switch(af) {
213 		case AF_INET: family="ip4"; break;
214 		case AF_INET6: family="ip6";
215 			sinaddr = &((struct sockaddr_in6*)addr)->sin6_addr;
216 			break;
217 		case AF_LOCAL:
218 			dest[0]=0;
219 			(void)inet_ntop(af, sinaddr, dest,
220 				(socklen_t)sizeof(dest));
221 			verbose(v, "%s local %s", str, dest);
222 			return; /* do not continue and try to get port */
223 		default: break;
224 	}
225 	if(inet_ntop(af, sinaddr, dest, (socklen_t)sizeof(dest)) == 0) {
226 		(void)strlcpy(dest, "(inet_ntop error)", sizeof(dest));
227 	}
228 	dest[sizeof(dest)-1] = 0;
229 	port = ntohs(((struct sockaddr_in*)addr)->sin_port);
230 	if(verbosity >= 4)
231 		verbose(v, "%s %s %s port %d (len %d)", str, family, dest,
232 			(int)port, (int)addrlen);
233 	else	verbose(v, "%s %s port %d", str, dest, (int)port);
234 }
235 
236 int
237 extstrtoaddr(const char* str, struct sockaddr_storage* addr,
238 	socklen_t* addrlen, int port)
239 {
240 	char* s;
241 	if((s=strchr(str, '@'))) {
242 		char buf[MAX_ADDR_STRLEN];
243 		if(s-str >= MAX_ADDR_STRLEN) {
244 			return 0;
245 		}
246 		(void)strlcpy(buf, str, sizeof(buf));
247 		buf[s-str] = 0;
248 		port = atoi(s+1);
249 		if(port == 0 && strcmp(s+1,"0")!=0) {
250 			return 0;
251 		}
252 		return ipstrtoaddr(buf, port, addr, addrlen);
253 	}
254 	return ipstrtoaddr(str, port, addr, addrlen);
255 }
256 
257 int
258 ipstrtoaddr(const char* ip, int port, struct sockaddr_storage* addr,
259 	socklen_t* addrlen)
260 {
261 	uint16_t p;
262 	if(!ip) return 0;
263 	p = (uint16_t) port;
264 	if(str_is_ip6(ip)) {
265 		char buf[MAX_ADDR_STRLEN];
266 		char* s;
267 		struct sockaddr_in6* sa = (struct sockaddr_in6*)addr;
268 		*addrlen = (socklen_t)sizeof(struct sockaddr_in6);
269 		memset(sa, 0, *addrlen);
270 		sa->sin6_family = AF_INET6;
271 		sa->sin6_port = (in_port_t)htons(p);
272 		if((s=strchr(ip, '%'))) { /* ip6%interface, rfc 4007 */
273 			if(s-ip >= MAX_ADDR_STRLEN)
274 				return 0;
275 			(void)strlcpy(buf, ip, sizeof(buf));
276 			buf[s-ip]=0;
277 #ifdef HAVE_IF_NAMETOINDEX
278 			if (!(sa->sin6_scope_id = if_nametoindex(s+1)))
279 #endif /* HAVE_IF_NAMETOINDEX */
280 				sa->sin6_scope_id = (uint32_t)atoi(s+1);
281 			ip = buf;
282 		}
283 		if(inet_pton((int)sa->sin6_family, ip, &sa->sin6_addr) <= 0) {
284 			return 0;
285 		}
286 	} else { /* ip4 */
287 		struct sockaddr_in* sa = (struct sockaddr_in*)addr;
288 		*addrlen = (socklen_t)sizeof(struct sockaddr_in);
289 		memset(sa, 0, *addrlen);
290 		sa->sin_family = AF_INET;
291 		sa->sin_port = (in_port_t)htons(p);
292 		if(inet_pton((int)sa->sin_family, ip, &sa->sin_addr) <= 0) {
293 			return 0;
294 		}
295 	}
296 	return 1;
297 }
298 
299 int netblockstrtoaddr(const char* str, int port, struct sockaddr_storage* addr,
300         socklen_t* addrlen, int* net)
301 {
302 	char buf[64];
303 	char* s;
304 	*net = (str_is_ip6(str)?128:32);
305 	if((s=strchr(str, '/'))) {
306 		if(atoi(s+1) > *net) {
307 			log_err("netblock too large: %s", str);
308 			return 0;
309 		}
310 		*net = atoi(s+1);
311 		if(*net == 0 && strcmp(s+1, "0") != 0) {
312 			log_err("cannot parse netblock: '%s'", str);
313 			return 0;
314 		}
315 		strlcpy(buf, str, sizeof(buf));
316 		s = strchr(buf, '/');
317 		if(s) *s = 0;
318 		s = buf;
319 	}
320 	if(!ipstrtoaddr(s?s:str, port, addr, addrlen)) {
321 		log_err("cannot parse ip address: '%s'", str);
322 		return 0;
323 	}
324 	if(s) {
325 		addr_mask(addr, *addrlen, *net);
326 	}
327 	return 1;
328 }
329 
330 /* RPZ format address dname to network byte order address */
331 static int ipdnametoaddr(uint8_t* dname, size_t dnamelen,
332 	struct sockaddr_storage* addr, socklen_t* addrlen, int* af)
333 {
334 	uint8_t* ia;
335 	int dnamelabs = dname_count_labels(dname);
336 	uint8_t lablen;
337 	char* e = NULL;
338 	int z = 0;
339 	size_t len = 0;
340 	int i;
341 	*af = AF_INET;
342 
343 	/* need 1 byte for label length */
344 	if(dnamelen < 1)
345 		return 0;
346 
347 	if(dnamelabs > 6 ||
348 		dname_has_label(dname, dnamelen, (uint8_t*)"\002zz")) {
349 		*af = AF_INET6;
350 	}
351 	len = *dname;
352 	lablen = *dname++;
353 	i = (*af == AF_INET) ? 3 : 15;
354 	if(*af == AF_INET6) {
355 		struct sockaddr_in6* sa = (struct sockaddr_in6*)addr;
356 		*addrlen = (socklen_t)sizeof(struct sockaddr_in6);
357 		memset(sa, 0, *addrlen);
358 		sa->sin6_family = AF_INET6;
359 		ia = (uint8_t*)&sa->sin6_addr;
360 	} else { /* ip4 */
361 		struct sockaddr_in* sa = (struct sockaddr_in*)addr;
362 		*addrlen = (socklen_t)sizeof(struct sockaddr_in);
363 		memset(sa, 0, *addrlen);
364 		sa->sin_family = AF_INET;
365 		ia = (uint8_t*)&sa->sin_addr;
366 	}
367 	while(lablen && i >= 0 && len <= dnamelen) {
368 		char buff[LDNS_MAX_LABELLEN+1];
369 		uint16_t chunk; /* big enough to not overflow on IPv6 hextet */
370 		if((*af == AF_INET && (lablen > 3 || dnamelabs > 6)) ||
371 			(*af == AF_INET6 && (lablen > 4 || dnamelabs > 10))) {
372 			return 0;
373 		}
374 		if(memcmp(dname, "zz", 2) == 0 && *af == AF_INET6) {
375 			/* Add one or more 0 labels. Address is initialised at
376 			 * 0, so just skip the zero part. */
377 			int zl = 11 - dnamelabs;
378 			if(z || zl < 0)
379 				return 0;
380 			z = 1;
381 			i -= (zl*2);
382 		} else {
383 			memcpy(buff, dname, lablen);
384 			buff[lablen] = '\0';
385 			chunk = strtol(buff, &e, (*af == AF_INET) ? 10 : 16);
386 			if(!e || *e != '\0' || (*af == AF_INET && chunk > 255))
387 				return 0;
388 			if(*af == AF_INET) {
389 				log_assert(i < 4 && i >= 0);
390 				ia[i] = (uint8_t)chunk;
391 				i--;
392 			} else {
393 				log_assert(i < 16 && i >= 1);
394 				/* ia in network byte order */
395 				ia[i-1] = (uint8_t)(chunk >> 8);
396 				ia[i] = (uint8_t)(chunk & 0x00FF);
397 				i -= 2;
398 			}
399 		}
400 		dname += lablen;
401 		lablen = *dname++;
402 		len += lablen;
403 	}
404 	if(i != -1)
405 		/* input too short */
406 		return 0;
407 	return 1;
408 }
409 
410 int netblockdnametoaddr(uint8_t* dname, size_t dnamelen,
411 	struct sockaddr_storage* addr, socklen_t* addrlen, int* net, int* af)
412 {
413 	char buff[3 /* 3 digit netblock */ + 1];
414 	size_t nlablen;
415 	if(dnamelen < 1 || *dname > 3)
416 		/* netblock invalid */
417 		return 0;
418 	nlablen = *dname;
419 
420 	if(dnamelen < 1 + nlablen)
421 		return 0;
422 
423 	memcpy(buff, dname+1, nlablen);
424 	buff[nlablen] = '\0';
425 	*net = atoi(buff);
426 	if(*net == 0 && strcmp(buff, "0") != 0)
427 		return 0;
428 	dname += nlablen;
429 	dname++;
430 	if(!ipdnametoaddr(dname, dnamelen-1-nlablen, addr, addrlen, af))
431 		return 0;
432 	if((*af == AF_INET6 && *net > 128) || (*af == AF_INET && *net > 32))
433 		return 0;
434 	return 1;
435 }
436 
437 int authextstrtoaddr(char* str, struct sockaddr_storage* addr,
438 	socklen_t* addrlen, char** auth_name)
439 {
440 	char* s;
441 	int port = UNBOUND_DNS_PORT;
442 	if((s=strchr(str, '@'))) {
443 		char buf[MAX_ADDR_STRLEN];
444 		size_t len = (size_t)(s-str);
445 		char* hash = strchr(s+1, '#');
446 		if(hash) {
447 			*auth_name = hash+1;
448 		} else {
449 			*auth_name = NULL;
450 		}
451 		if(len >= MAX_ADDR_STRLEN) {
452 			return 0;
453 		}
454 		(void)strlcpy(buf, str, sizeof(buf));
455 		buf[len] = 0;
456 		port = atoi(s+1);
457 		if(port == 0) {
458 			if(!hash && strcmp(s+1,"0")!=0)
459 				return 0;
460 			if(hash && strncmp(s+1,"0#",2)!=0)
461 				return 0;
462 		}
463 		return ipstrtoaddr(buf, port, addr, addrlen);
464 	}
465 	if((s=strchr(str, '#'))) {
466 		char buf[MAX_ADDR_STRLEN];
467 		size_t len = (size_t)(s-str);
468 		if(len >= MAX_ADDR_STRLEN) {
469 			return 0;
470 		}
471 		(void)strlcpy(buf, str, sizeof(buf));
472 		buf[len] = 0;
473 		port = UNBOUND_DNS_OVER_TLS_PORT;
474 		*auth_name = s+1;
475 		return ipstrtoaddr(buf, port, addr, addrlen);
476 	}
477 	*auth_name = NULL;
478 	return ipstrtoaddr(str, port, addr, addrlen);
479 }
480 
481 uint8_t* authextstrtodname(char* str, int* port, char** auth_name)
482 {
483 	char* s;
484 	uint8_t* dname;
485 	size_t dname_len;
486 	*port = UNBOUND_DNS_PORT;
487 	*auth_name = NULL;
488 	if((s=strchr(str, '@'))) {
489 		char* hash = strchr(s+1, '#');
490 		if(hash) {
491 			*auth_name = hash+1;
492 		} else {
493 			*auth_name = NULL;
494 		}
495 		*port = atoi(s+1);
496 		if(*port == 0) {
497 			if(!hash && strcmp(s+1,"0")!=0)
498 				return 0;
499 			if(hash && strncmp(s+1,"0#",2)!=0)
500 				return 0;
501 		}
502 		*s = 0;
503 		dname = sldns_str2wire_dname(str, &dname_len);
504 		*s = '@';
505 	} else if((s=strchr(str, '#'))) {
506 		*port = UNBOUND_DNS_OVER_TLS_PORT;
507 		*auth_name = s+1;
508 		*s = 0;
509 		dname = sldns_str2wire_dname(str, &dname_len);
510 		*s = '#';
511 	} else {
512 		dname = sldns_str2wire_dname(str, &dname_len);
513 	}
514 	return dname;
515 }
516 
517 /** store port number into sockaddr structure */
518 void
519 sockaddr_store_port(struct sockaddr_storage* addr, socklen_t addrlen, int port)
520 {
521 	if(addr_is_ip6(addr, addrlen)) {
522 		struct sockaddr_in6* sa = (struct sockaddr_in6*)addr;
523 		sa->sin6_port = (in_port_t)htons((uint16_t)port);
524 	} else {
525 		struct sockaddr_in* sa = (struct sockaddr_in*)addr;
526 		sa->sin_port = (in_port_t)htons((uint16_t)port);
527 	}
528 }
529 
530 void
531 log_nametypeclass(enum verbosity_value v, const char* str, uint8_t* name,
532 	uint16_t type, uint16_t dclass)
533 {
534 	char buf[LDNS_MAX_DOMAINLEN+1];
535 	char t[12], c[12];
536 	const char *ts, *cs;
537 	if(verbosity < v)
538 		return;
539 	dname_str(name, buf);
540 	if(type == LDNS_RR_TYPE_TSIG) ts = "TSIG";
541 	else if(type == LDNS_RR_TYPE_IXFR) ts = "IXFR";
542 	else if(type == LDNS_RR_TYPE_AXFR) ts = "AXFR";
543 	else if(type == LDNS_RR_TYPE_MAILB) ts = "MAILB";
544 	else if(type == LDNS_RR_TYPE_MAILA) ts = "MAILA";
545 	else if(type == LDNS_RR_TYPE_ANY) ts = "ANY";
546 	else if(sldns_rr_descript(type) && sldns_rr_descript(type)->_name)
547 		ts = sldns_rr_descript(type)->_name;
548 	else {
549 		snprintf(t, sizeof(t), "TYPE%d", (int)type);
550 		ts = t;
551 	}
552 	if(sldns_lookup_by_id(sldns_rr_classes, (int)dclass) &&
553 		sldns_lookup_by_id(sldns_rr_classes, (int)dclass)->name)
554 		cs = sldns_lookup_by_id(sldns_rr_classes, (int)dclass)->name;
555 	else {
556 		snprintf(c, sizeof(c), "CLASS%d", (int)dclass);
557 		cs = c;
558 	}
559 	log_info("%s %s %s %s", str, buf, ts, cs);
560 }
561 
562 void
563 log_query_in(const char* str, uint8_t* name, uint16_t type, uint16_t dclass)
564 {
565 	char buf[LDNS_MAX_DOMAINLEN+1];
566 	char t[12], c[12];
567 	const char *ts, *cs;
568 	dname_str(name, buf);
569 	if(type == LDNS_RR_TYPE_TSIG) ts = "TSIG";
570 	else if(type == LDNS_RR_TYPE_IXFR) ts = "IXFR";
571 	else if(type == LDNS_RR_TYPE_AXFR) ts = "AXFR";
572 	else if(type == LDNS_RR_TYPE_MAILB) ts = "MAILB";
573 	else if(type == LDNS_RR_TYPE_MAILA) ts = "MAILA";
574 	else if(type == LDNS_RR_TYPE_ANY) ts = "ANY";
575 	else if(sldns_rr_descript(type) && sldns_rr_descript(type)->_name)
576 		ts = sldns_rr_descript(type)->_name;
577 	else {
578 		snprintf(t, sizeof(t), "TYPE%d", (int)type);
579 		ts = t;
580 	}
581 	if(sldns_lookup_by_id(sldns_rr_classes, (int)dclass) &&
582 		sldns_lookup_by_id(sldns_rr_classes, (int)dclass)->name)
583 		cs = sldns_lookup_by_id(sldns_rr_classes, (int)dclass)->name;
584 	else {
585 		snprintf(c, sizeof(c), "CLASS%d", (int)dclass);
586 		cs = c;
587 	}
588 	if(LOG_TAG_QUERYREPLY)
589 		log_query("%s %s %s %s", str, buf, ts, cs);
590 	else	log_info("%s %s %s %s", str, buf, ts, cs);
591 }
592 
593 void log_name_addr(enum verbosity_value v, const char* str, uint8_t* zone,
594 	struct sockaddr_storage* addr, socklen_t addrlen)
595 {
596 	uint16_t port;
597 	const char* family = "unknown_family ";
598 	char namebuf[LDNS_MAX_DOMAINLEN+1];
599 	char dest[100];
600 	int af = (int)((struct sockaddr_in*)addr)->sin_family;
601 	void* sinaddr = &((struct sockaddr_in*)addr)->sin_addr;
602 	if(verbosity < v)
603 		return;
604 	switch(af) {
605 		case AF_INET: family=""; break;
606 		case AF_INET6: family="";
607 			sinaddr = &((struct sockaddr_in6*)addr)->sin6_addr;
608 			break;
609 		case AF_LOCAL: family="local "; break;
610 		default: break;
611 	}
612 	if(inet_ntop(af, sinaddr, dest, (socklen_t)sizeof(dest)) == 0) {
613 		(void)strlcpy(dest, "(inet_ntop error)", sizeof(dest));
614 	}
615 	dest[sizeof(dest)-1] = 0;
616 	port = ntohs(((struct sockaddr_in*)addr)->sin_port);
617 	dname_str(zone, namebuf);
618 	if(af != AF_INET && af != AF_INET6)
619 		verbose(v, "%s <%s> %s%s#%d (addrlen %d)",
620 			str, namebuf, family, dest, (int)port, (int)addrlen);
621 	else	verbose(v, "%s <%s> %s%s#%d",
622 			str, namebuf, family, dest, (int)port);
623 }
624 
625 void log_err_addr(const char* str, const char* err,
626 	struct sockaddr_storage* addr, socklen_t addrlen)
627 {
628 	uint16_t port;
629 	char dest[100];
630 	int af = (int)((struct sockaddr_in*)addr)->sin_family;
631 	void* sinaddr = &((struct sockaddr_in*)addr)->sin_addr;
632 	if(af == AF_INET6)
633 		sinaddr = &((struct sockaddr_in6*)addr)->sin6_addr;
634 	if(inet_ntop(af, sinaddr, dest, (socklen_t)sizeof(dest)) == 0) {
635 		(void)strlcpy(dest, "(inet_ntop error)", sizeof(dest));
636 	}
637 	dest[sizeof(dest)-1] = 0;
638 	port = ntohs(((struct sockaddr_in*)addr)->sin_port);
639 	if(verbosity >= 4)
640 		log_err("%s: %s for %s port %d (len %d)", str, err, dest,
641 			(int)port, (int)addrlen);
642 	else	log_err("%s: %s for %s port %d", str, err, dest, (int)port);
643 }
644 
645 int
646 sockaddr_cmp(struct sockaddr_storage* addr1, socklen_t len1,
647 	struct sockaddr_storage* addr2, socklen_t len2)
648 {
649 	struct sockaddr_in* p1_in = (struct sockaddr_in*)addr1;
650 	struct sockaddr_in* p2_in = (struct sockaddr_in*)addr2;
651 	struct sockaddr_in6* p1_in6 = (struct sockaddr_in6*)addr1;
652 	struct sockaddr_in6* p2_in6 = (struct sockaddr_in6*)addr2;
653 	if(len1 < len2)
654 		return -1;
655 	if(len1 > len2)
656 		return 1;
657 	log_assert(len1 == len2);
658 	if( p1_in->sin_family < p2_in->sin_family)
659 		return -1;
660 	if( p1_in->sin_family > p2_in->sin_family)
661 		return 1;
662 	log_assert( p1_in->sin_family == p2_in->sin_family );
663 	/* compare ip4 */
664 	if( p1_in->sin_family == AF_INET ) {
665 		/* just order it, ntohs not required */
666 		if(p1_in->sin_port < p2_in->sin_port)
667 			return -1;
668 		if(p1_in->sin_port > p2_in->sin_port)
669 			return 1;
670 		log_assert(p1_in->sin_port == p2_in->sin_port);
671 		return memcmp(&p1_in->sin_addr, &p2_in->sin_addr, INET_SIZE);
672 	} else if (p1_in6->sin6_family == AF_INET6) {
673 		/* just order it, ntohs not required */
674 		if(p1_in6->sin6_port < p2_in6->sin6_port)
675 			return -1;
676 		if(p1_in6->sin6_port > p2_in6->sin6_port)
677 			return 1;
678 		log_assert(p1_in6->sin6_port == p2_in6->sin6_port);
679 		return memcmp(&p1_in6->sin6_addr, &p2_in6->sin6_addr,
680 			INET6_SIZE);
681 	} else {
682 		/* eek unknown type, perform this comparison for sanity. */
683 		return memcmp(addr1, addr2, len1);
684 	}
685 }
686 
687 int
688 sockaddr_cmp_addr(struct sockaddr_storage* addr1, socklen_t len1,
689 	struct sockaddr_storage* addr2, socklen_t len2)
690 {
691 	struct sockaddr_in* p1_in = (struct sockaddr_in*)addr1;
692 	struct sockaddr_in* p2_in = (struct sockaddr_in*)addr2;
693 	struct sockaddr_in6* p1_in6 = (struct sockaddr_in6*)addr1;
694 	struct sockaddr_in6* p2_in6 = (struct sockaddr_in6*)addr2;
695 	if(len1 < len2)
696 		return -1;
697 	if(len1 > len2)
698 		return 1;
699 	log_assert(len1 == len2);
700 	if( p1_in->sin_family < p2_in->sin_family)
701 		return -1;
702 	if( p1_in->sin_family > p2_in->sin_family)
703 		return 1;
704 	log_assert( p1_in->sin_family == p2_in->sin_family );
705 	/* compare ip4 */
706 	if( p1_in->sin_family == AF_INET ) {
707 		return memcmp(&p1_in->sin_addr, &p2_in->sin_addr, INET_SIZE);
708 	} else if (p1_in6->sin6_family == AF_INET6) {
709 		return memcmp(&p1_in6->sin6_addr, &p2_in6->sin6_addr,
710 			INET6_SIZE);
711 	} else {
712 		/* eek unknown type, perform this comparison for sanity. */
713 		return memcmp(addr1, addr2, len1);
714 	}
715 }
716 
717 int
718 addr_is_ip6(struct sockaddr_storage* addr, socklen_t len)
719 {
720 	if(len == (socklen_t)sizeof(struct sockaddr_in6) &&
721 		((struct sockaddr_in6*)addr)->sin6_family == AF_INET6)
722 		return 1;
723 	else    return 0;
724 }
725 
726 void
727 addr_mask(struct sockaddr_storage* addr, socklen_t len, int net)
728 {
729 	uint8_t mask[8] = {0x0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe};
730 	int i, max;
731 	uint8_t* s;
732 	if(addr_is_ip6(addr, len)) {
733 		s = (uint8_t*)&((struct sockaddr_in6*)addr)->sin6_addr;
734 		max = 128;
735 	} else {
736 		s = (uint8_t*)&((struct sockaddr_in*)addr)->sin_addr;
737 		max = 32;
738 	}
739 	if(net >= max)
740 		return;
741 	for(i=net/8+1; i<max/8; i++) {
742 		s[i] = 0;
743 	}
744 	s[net/8] &= mask[net&0x7];
745 }
746 
747 int
748 addr_in_common(struct sockaddr_storage* addr1, int net1,
749 	struct sockaddr_storage* addr2, int net2, socklen_t addrlen)
750 {
751 	int min = (net1<net2)?net1:net2;
752 	int i, to;
753 	int match = 0;
754 	uint8_t* s1, *s2;
755 	if(addr_is_ip6(addr1, addrlen)) {
756 		s1 = (uint8_t*)&((struct sockaddr_in6*)addr1)->sin6_addr;
757 		s2 = (uint8_t*)&((struct sockaddr_in6*)addr2)->sin6_addr;
758 		to = 16;
759 	} else {
760 		s1 = (uint8_t*)&((struct sockaddr_in*)addr1)->sin_addr;
761 		s2 = (uint8_t*)&((struct sockaddr_in*)addr2)->sin_addr;
762 		to = 4;
763 	}
764 	/* match = bits_in_common(s1, s2, to); */
765 	for(i=0; i<to; i++) {
766 		if(s1[i] == s2[i]) {
767 			match += 8;
768 		} else {
769 			uint8_t z = s1[i]^s2[i];
770 			log_assert(z);
771 			while(!(z&0x80)) {
772 				match++;
773 				z<<=1;
774 			}
775 			break;
776 		}
777 	}
778 	if(match > min) match = min;
779 	return match;
780 }
781 
782 void
783 addr_to_str(struct sockaddr_storage* addr, socklen_t addrlen,
784 	char* buf, size_t len)
785 {
786 	int af = (int)((struct sockaddr_in*)addr)->sin_family;
787 	void* sinaddr = &((struct sockaddr_in*)addr)->sin_addr;
788 	if(addr_is_ip6(addr, addrlen))
789 		sinaddr = &((struct sockaddr_in6*)addr)->sin6_addr;
790 	if(inet_ntop(af, sinaddr, buf, (socklen_t)len) == 0) {
791 		snprintf(buf, len, "(inet_ntop_error)");
792 	}
793 }
794 
795 int
796 addr_is_ip4mapped(struct sockaddr_storage* addr, socklen_t addrlen)
797 {
798 	/* prefix for ipv4 into ipv6 mapping is ::ffff:x.x.x.x */
799 	const uint8_t map_prefix[16] =
800 		{0,0,0,0,  0,0,0,0, 0,0,0xff,0xff, 0,0,0,0};
801 	uint8_t* s;
802 	if(!addr_is_ip6(addr, addrlen))
803 		return 0;
804 	/* s is 16 octet ipv6 address string */
805 	s = (uint8_t*)&((struct sockaddr_in6*)addr)->sin6_addr;
806 	return (memcmp(s, map_prefix, 12) == 0);
807 }
808 
809 int addr_is_broadcast(struct sockaddr_storage* addr, socklen_t addrlen)
810 {
811 	int af = (int)((struct sockaddr_in*)addr)->sin_family;
812 	void* sinaddr = &((struct sockaddr_in*)addr)->sin_addr;
813 	return af == AF_INET && addrlen>=(socklen_t)sizeof(struct sockaddr_in)
814 		&& memcmp(sinaddr, "\377\377\377\377", 4) == 0;
815 }
816 
817 int addr_is_any(struct sockaddr_storage* addr, socklen_t addrlen)
818 {
819 	int af = (int)((struct sockaddr_in*)addr)->sin_family;
820 	void* sinaddr = &((struct sockaddr_in*)addr)->sin_addr;
821 	void* sin6addr = &((struct sockaddr_in6*)addr)->sin6_addr;
822 	if(af == AF_INET && addrlen>=(socklen_t)sizeof(struct sockaddr_in)
823 		&& memcmp(sinaddr, "\000\000\000\000", 4) == 0)
824 		return 1;
825 	else if(af==AF_INET6 && addrlen>=(socklen_t)sizeof(struct sockaddr_in6)
826 		&& memcmp(sin6addr, "\000\000\000\000\000\000\000\000"
827 		"\000\000\000\000\000\000\000\000", 16) == 0)
828 		return 1;
829 	return 0;
830 }
831 
832 void sock_list_insert(struct sock_list** list, struct sockaddr_storage* addr,
833 	socklen_t len, struct regional* region)
834 {
835 	struct sock_list* add = (struct sock_list*)regional_alloc(region,
836 		sizeof(*add) - sizeof(add->addr) + (size_t)len);
837 	if(!add) {
838 		log_err("out of memory in socketlist insert");
839 		return;
840 	}
841 	log_assert(list);
842 	add->next = *list;
843 	add->len = len;
844 	*list = add;
845 	if(len) memmove(&add->addr, addr, len);
846 }
847 
848 void sock_list_prepend(struct sock_list** list, struct sock_list* add)
849 {
850 	struct sock_list* last = add;
851 	if(!last)
852 		return;
853 	while(last->next)
854 		last = last->next;
855 	last->next = *list;
856 	*list = add;
857 }
858 
859 int sock_list_find(struct sock_list* list, struct sockaddr_storage* addr,
860         socklen_t len)
861 {
862 	while(list) {
863 		if(len == list->len) {
864 			if(len == 0 || sockaddr_cmp_addr(addr, len,
865 				&list->addr, list->len) == 0)
866 				return 1;
867 		}
868 		list = list->next;
869 	}
870 	return 0;
871 }
872 
873 void sock_list_merge(struct sock_list** list, struct regional* region,
874 	struct sock_list* add)
875 {
876 	struct sock_list* p;
877 	for(p=add; p; p=p->next) {
878 		if(!sock_list_find(*list, &p->addr, p->len))
879 			sock_list_insert(list, &p->addr, p->len, region);
880 	}
881 }
882 
883 void
884 log_crypto_err(const char* str)
885 {
886 #ifdef HAVE_SSL
887 	log_crypto_err_code(str, ERR_get_error());
888 #else
889 	(void)str;
890 #endif /* HAVE_SSL */
891 }
892 
893 void log_crypto_err_code(const char* str, unsigned long err)
894 {
895 #ifdef HAVE_SSL
896 	/* error:[error code]:[library name]:[function name]:[reason string] */
897 	char buf[128];
898 	unsigned long e;
899 	ERR_error_string_n(err, buf, sizeof(buf));
900 	log_err("%s crypto %s", str, buf);
901 	while( (e=ERR_get_error()) ) {
902 		ERR_error_string_n(e, buf, sizeof(buf));
903 		log_err("and additionally crypto %s", buf);
904 	}
905 #else
906 	(void)str;
907 	(void)err;
908 #endif /* HAVE_SSL */
909 }
910 
911 #ifdef HAVE_SSL
912 /** log certificate details */
913 void
914 log_cert(unsigned level, const char* str, void* cert)
915 {
916 	BIO* bio;
917 	char nul = 0;
918 	char* pp = NULL;
919 	long len;
920 	if(verbosity < level) return;
921 	bio = BIO_new(BIO_s_mem());
922 	if(!bio) return;
923 	X509_print_ex(bio, (X509*)cert, 0, (unsigned long)-1
924 		^(X509_FLAG_NO_SUBJECT
925                         |X509_FLAG_NO_ISSUER|X509_FLAG_NO_VALIDITY
926 			|X509_FLAG_NO_EXTENSIONS|X509_FLAG_NO_AUX
927 			|X509_FLAG_NO_ATTRIBUTES));
928 	BIO_write(bio, &nul, (int)sizeof(nul));
929 	len = BIO_get_mem_data(bio, &pp);
930 	if(len != 0 && pp) {
931 		/* reduce size of cert printout */
932 		char* s;
933 		while((s=strstr(pp, "  "))!=NULL)
934 			memmove(s, s+1, strlen(s+1)+1);
935 		while((s=strstr(pp, "\t\t"))!=NULL)
936 			memmove(s, s+1, strlen(s+1)+1);
937 		verbose(level, "%s: \n%s", str, pp);
938 	}
939 	BIO_free(bio);
940 }
941 #endif /* HAVE_SSL */
942 
943 #if defined(HAVE_SSL) && defined(HAVE_NGHTTP2) && defined(HAVE_SSL_CTX_SET_ALPN_SELECT_CB)
944 static int alpn_select_cb(SSL* ATTR_UNUSED(ssl), const unsigned char** out,
945 	unsigned char* outlen, const unsigned char* in, unsigned int inlen,
946 	void* ATTR_UNUSED(arg))
947 {
948 	int rv = nghttp2_select_next_protocol((unsigned char **)out, outlen, in,
949 		inlen);
950 	if(rv == -1) {
951 		return SSL_TLSEXT_ERR_NOACK;
952 	}
953 	/* either http/1.1 or h2 selected */
954 	return SSL_TLSEXT_ERR_OK;
955 }
956 #endif
957 
958 int
959 listen_sslctx_setup(void* ctxt)
960 {
961 #ifdef HAVE_SSL
962 	SSL_CTX* ctx = (SSL_CTX*)ctxt;
963 	/* no SSLv2, SSLv3 because has defects */
964 #if SSL_OP_NO_SSLv2 != 0
965 	if((SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2) & SSL_OP_NO_SSLv2)
966 		!= SSL_OP_NO_SSLv2){
967 		log_crypto_err("could not set SSL_OP_NO_SSLv2");
968 		return 0;
969 	}
970 #endif
971 	if((SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv3) & SSL_OP_NO_SSLv3)
972 		!= SSL_OP_NO_SSLv3){
973 		log_crypto_err("could not set SSL_OP_NO_SSLv3");
974 		return 0;
975 	}
976 #if defined(SSL_OP_NO_TLSv1) && defined(SSL_OP_NO_TLSv1_1)
977 	/* if we have tls 1.1 disable 1.0 */
978 	if((SSL_CTX_set_options(ctx, SSL_OP_NO_TLSv1) & SSL_OP_NO_TLSv1)
979 		!= SSL_OP_NO_TLSv1){
980 		log_crypto_err("could not set SSL_OP_NO_TLSv1");
981 		return 0;
982 	}
983 #endif
984 #if defined(SSL_OP_NO_TLSv1_1) && defined(SSL_OP_NO_TLSv1_2)
985 	/* if we have tls 1.2 disable 1.1 */
986 	if((SSL_CTX_set_options(ctx, SSL_OP_NO_TLSv1_1) & SSL_OP_NO_TLSv1_1)
987 		!= SSL_OP_NO_TLSv1_1){
988 		log_crypto_err("could not set SSL_OP_NO_TLSv1_1");
989 		return 0;
990 	}
991 #endif
992 #if defined(SSL_OP_NO_RENEGOTIATION)
993 	/* disable client renegotiation */
994 	if((SSL_CTX_set_options(ctx, SSL_OP_NO_RENEGOTIATION) &
995 		SSL_OP_NO_RENEGOTIATION) != SSL_OP_NO_RENEGOTIATION) {
996 		log_crypto_err("could not set SSL_OP_NO_RENEGOTIATION");
997 		return 0;
998 	}
999 #endif
1000 #if defined(SHA256_DIGEST_LENGTH) && defined(USE_ECDSA)
1001 	/* if we detect system-wide crypto policies, use those */
1002 	if (access( "/etc/crypto-policies/config", F_OK ) != 0 ) {
1003 	/* if we have sha256, set the cipher list to have no known vulns */
1004 		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"))
1005 			log_crypto_err("could not set cipher list with SSL_CTX_set_cipher_list");
1006 	}
1007 #endif
1008 
1009 	if((SSL_CTX_set_options(ctx, SSL_OP_CIPHER_SERVER_PREFERENCE) &
1010 		SSL_OP_CIPHER_SERVER_PREFERENCE) !=
1011 		SSL_OP_CIPHER_SERVER_PREFERENCE) {
1012 		log_crypto_err("could not set SSL_OP_CIPHER_SERVER_PREFERENCE");
1013 		return 0;
1014 	}
1015 
1016 #ifdef HAVE_SSL_CTX_SET_SECURITY_LEVEL
1017 	SSL_CTX_set_security_level(ctx, 0);
1018 #endif
1019 #if defined(HAVE_SSL_CTX_SET_ALPN_SELECT_CB) && defined(HAVE_NGHTTP2)
1020 	SSL_CTX_set_alpn_select_cb(ctx, alpn_select_cb, NULL);
1021 #endif
1022 #else
1023 	(void)ctxt;
1024 #endif /* HAVE_SSL */
1025 	return 1;
1026 }
1027 
1028 void
1029 listen_sslctx_setup_2(void* ctxt)
1030 {
1031 #ifdef HAVE_SSL
1032 	SSL_CTX* ctx = (SSL_CTX*)ctxt;
1033 	(void)ctx;
1034 #if HAVE_DECL_SSL_CTX_SET_ECDH_AUTO
1035 	if(!SSL_CTX_set_ecdh_auto(ctx,1)) {
1036 		log_crypto_err("Error in SSL_CTX_ecdh_auto, not enabling ECDHE");
1037 	}
1038 #elif defined(USE_ECDSA)
1039 	if(1) {
1040 		EC_KEY *ecdh = EC_KEY_new_by_curve_name (NID_X9_62_prime256v1);
1041 		if (!ecdh) {
1042 			log_crypto_err("could not find p256, not enabling ECDHE");
1043 		} else {
1044 			if (1 != SSL_CTX_set_tmp_ecdh (ctx, ecdh)) {
1045 				log_crypto_err("Error in SSL_CTX_set_tmp_ecdh, not enabling ECDHE");
1046 			}
1047 			EC_KEY_free (ecdh);
1048 		}
1049 	}
1050 #endif
1051 #else
1052 	(void)ctxt;
1053 #endif /* HAVE_SSL */
1054 }
1055 
1056 void* listen_sslctx_create(char* key, char* pem, char* verifypem)
1057 {
1058 #ifdef HAVE_SSL
1059 	SSL_CTX* ctx = SSL_CTX_new(SSLv23_server_method());
1060 	if(!ctx) {
1061 		log_crypto_err("could not SSL_CTX_new");
1062 		return NULL;
1063 	}
1064 	if(!key || key[0] == 0) {
1065 		log_err("error: no tls-service-key file specified");
1066 		SSL_CTX_free(ctx);
1067 		return NULL;
1068 	}
1069 	if(!pem || pem[0] == 0) {
1070 		log_err("error: no tls-service-pem file specified");
1071 		SSL_CTX_free(ctx);
1072 		return NULL;
1073 	}
1074 	if(!listen_sslctx_setup(ctx)) {
1075 		SSL_CTX_free(ctx);
1076 		return NULL;
1077 	}
1078 	if(!SSL_CTX_use_certificate_chain_file(ctx, pem)) {
1079 		log_err("error for cert file: %s", pem);
1080 		log_crypto_err("error in SSL_CTX use_certificate_chain_file");
1081 		SSL_CTX_free(ctx);
1082 		return NULL;
1083 	}
1084 	if(!SSL_CTX_use_PrivateKey_file(ctx, key, SSL_FILETYPE_PEM)) {
1085 		log_err("error for private key file: %s", key);
1086 		log_crypto_err("Error in SSL_CTX use_PrivateKey_file");
1087 		SSL_CTX_free(ctx);
1088 		return NULL;
1089 	}
1090 	if(!SSL_CTX_check_private_key(ctx)) {
1091 		log_err("error for key file: %s", key);
1092 		log_crypto_err("Error in SSL_CTX check_private_key");
1093 		SSL_CTX_free(ctx);
1094 		return NULL;
1095 	}
1096 	listen_sslctx_setup_2(ctx);
1097 	if(verifypem && verifypem[0]) {
1098 		if(!SSL_CTX_load_verify_locations(ctx, verifypem, NULL)) {
1099 			log_crypto_err("Error in SSL_CTX verify locations");
1100 			SSL_CTX_free(ctx);
1101 			return NULL;
1102 		}
1103 		SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(
1104 			verifypem));
1105 		SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL);
1106 	}
1107 	return ctx;
1108 #else
1109 	(void)key; (void)pem; (void)verifypem;
1110 	return NULL;
1111 #endif
1112 }
1113 
1114 #ifdef USE_WINSOCK
1115 /* For windows, the CA trust store is not read by openssl.
1116    Add code to open the trust store using wincrypt API and add
1117    the root certs into openssl trust store */
1118 static int
1119 add_WIN_cacerts_to_openssl_store(SSL_CTX* tls_ctx)
1120 {
1121 	HCERTSTORE      hSystemStore;
1122 	PCCERT_CONTEXT  pTargetCert = NULL;
1123 	X509_STORE*	store;
1124 
1125 	verbose(VERB_ALGO, "Adding Windows certificates from system root store to CA store");
1126 
1127 	/* load just once per context lifetime for this version
1128 	   TODO: dynamically update CA trust changes as they are available */
1129 	if (!tls_ctx)
1130 		return 0;
1131 
1132 	/* Call wincrypt's CertOpenStore to open the CA root store. */
1133 
1134 	if ((hSystemStore = CertOpenStore(
1135 		CERT_STORE_PROV_SYSTEM,
1136 		0,
1137 		0,
1138 		/* NOTE: mingw does not have this const: replace with 1 << 16 from code
1139 		   CERT_SYSTEM_STORE_CURRENT_USER, */
1140 		1 << 16,
1141 		L"root")) == 0)
1142 	{
1143 		return 0;
1144 	}
1145 
1146 	store = SSL_CTX_get_cert_store(tls_ctx);
1147 	if (!store)
1148 		return 0;
1149 
1150 	/* failure if the CA store is empty or the call fails */
1151 	if ((pTargetCert = CertEnumCertificatesInStore(
1152 		hSystemStore, pTargetCert)) == 0) {
1153 		verbose(VERB_ALGO, "CA certificate store for Windows is empty.");
1154 		return 0;
1155 	}
1156 	/* iterate over the windows cert store and add to openssl store */
1157 	do
1158 	{
1159 		X509 *cert1 = d2i_X509(NULL,
1160 			(const unsigned char **)&pTargetCert->pbCertEncoded,
1161 			pTargetCert->cbCertEncoded);
1162 		if (!cert1) {
1163 			unsigned long error = ERR_get_error();
1164 			/* return error if a cert fails */
1165 			verbose(VERB_ALGO, "%s %d:%s",
1166 				"Unable to parse certificate in memory",
1167 				(int)error, ERR_error_string(error, NULL));
1168 			return 0;
1169 		}
1170 		else {
1171 			/* return error if a cert add to store fails */
1172 			if (X509_STORE_add_cert(store, cert1) == 0) {
1173 				unsigned long error = ERR_peek_last_error();
1174 
1175 				/* Ignore error X509_R_CERT_ALREADY_IN_HASH_TABLE which means the
1176 				* certificate is already in the store.  */
1177 				if(ERR_GET_LIB(error) != ERR_LIB_X509 ||
1178 					ERR_GET_REASON(error) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1179 					error = ERR_get_error();
1180 					verbose(VERB_ALGO, "%s %d:%s\n",
1181 					    "Error adding certificate", (int)error,
1182 					     ERR_error_string(error, NULL));
1183 					X509_free(cert1);
1184 					return 0;
1185 				}
1186 			}
1187 			X509_free(cert1);
1188 		}
1189 	} while ((pTargetCert = CertEnumCertificatesInStore(
1190 		hSystemStore, pTargetCert)) != 0);
1191 
1192 	/* Clean up memory and quit. */
1193 	if (pTargetCert)
1194 		CertFreeCertificateContext(pTargetCert);
1195 	if (hSystemStore)
1196 	{
1197 		if (!CertCloseStore(
1198 			hSystemStore, 0))
1199 			return 0;
1200 	}
1201 	verbose(VERB_ALGO, "Completed adding Windows certificates to CA store successfully");
1202 	return 1;
1203 }
1204 #endif /* USE_WINSOCK */
1205 
1206 void* connect_sslctx_create(char* key, char* pem, char* verifypem, int wincert)
1207 {
1208 #ifdef HAVE_SSL
1209 	SSL_CTX* ctx = SSL_CTX_new(SSLv23_client_method());
1210 	if(!ctx) {
1211 		log_crypto_err("could not allocate SSL_CTX pointer");
1212 		return NULL;
1213 	}
1214 #if SSL_OP_NO_SSLv2 != 0
1215 	if((SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2) & SSL_OP_NO_SSLv2)
1216 		!= SSL_OP_NO_SSLv2) {
1217 		log_crypto_err("could not set SSL_OP_NO_SSLv2");
1218 		SSL_CTX_free(ctx);
1219 		return NULL;
1220 	}
1221 #endif
1222 	if((SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv3) & SSL_OP_NO_SSLv3)
1223 		!= SSL_OP_NO_SSLv3) {
1224 		log_crypto_err("could not set SSL_OP_NO_SSLv3");
1225 		SSL_CTX_free(ctx);
1226 		return NULL;
1227 	}
1228 #if defined(SSL_OP_NO_RENEGOTIATION)
1229 	/* disable client renegotiation */
1230 	if((SSL_CTX_set_options(ctx, SSL_OP_NO_RENEGOTIATION) &
1231 		SSL_OP_NO_RENEGOTIATION) != SSL_OP_NO_RENEGOTIATION) {
1232 		log_crypto_err("could not set SSL_OP_NO_RENEGOTIATION");
1233 		SSL_CTX_free(ctx);
1234 		return 0;
1235 	}
1236 #endif
1237 	if(key && key[0]) {
1238 		if(!SSL_CTX_use_certificate_chain_file(ctx, pem)) {
1239 			log_err("error in client certificate %s", pem);
1240 			log_crypto_err("error in certificate file");
1241 			SSL_CTX_free(ctx);
1242 			return NULL;
1243 		}
1244 		if(!SSL_CTX_use_PrivateKey_file(ctx, key, SSL_FILETYPE_PEM)) {
1245 			log_err("error in client private key %s", key);
1246 			log_crypto_err("error in key file");
1247 			SSL_CTX_free(ctx);
1248 			return NULL;
1249 		}
1250 		if(!SSL_CTX_check_private_key(ctx)) {
1251 			log_err("error in client key %s", key);
1252 			log_crypto_err("error in SSL_CTX_check_private_key");
1253 			SSL_CTX_free(ctx);
1254 			return NULL;
1255 		}
1256 	}
1257 	if((verifypem && verifypem[0]) || wincert) {
1258 		if(verifypem && verifypem[0]) {
1259 			if(!SSL_CTX_load_verify_locations(ctx, verifypem, NULL)) {
1260 				log_crypto_err("error in SSL_CTX verify");
1261 				SSL_CTX_free(ctx);
1262 				return NULL;
1263 			}
1264 		}
1265 #ifdef USE_WINSOCK
1266 		if(wincert) {
1267 			if(!add_WIN_cacerts_to_openssl_store(ctx)) {
1268 				log_crypto_err("error in add_WIN_cacerts_to_openssl_store");
1269 				SSL_CTX_free(ctx);
1270 				return NULL;
1271 			}
1272 		}
1273 #else
1274 		if(wincert) {
1275 			if(!SSL_CTX_set_default_verify_paths(ctx)) {
1276 				log_crypto_err("error in default_verify_paths");
1277 				SSL_CTX_free(ctx);
1278 				return NULL;
1279 			}
1280 		}
1281 #endif
1282 		SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
1283 	}
1284 	return ctx;
1285 #else
1286 	(void)key; (void)pem; (void)verifypem; (void)wincert;
1287 	return NULL;
1288 #endif
1289 }
1290 
1291 void* incoming_ssl_fd(void* sslctx, int fd)
1292 {
1293 #ifdef HAVE_SSL
1294 	SSL* ssl = SSL_new((SSL_CTX*)sslctx);
1295 	if(!ssl) {
1296 		log_crypto_err("could not SSL_new");
1297 		return NULL;
1298 	}
1299 	SSL_set_accept_state(ssl);
1300 	(void)SSL_set_mode(ssl, (long)SSL_MODE_AUTO_RETRY);
1301 	if(!SSL_set_fd(ssl, fd)) {
1302 		log_crypto_err("could not SSL_set_fd");
1303 		SSL_free(ssl);
1304 		return NULL;
1305 	}
1306 	return ssl;
1307 #else
1308 	(void)sslctx; (void)fd;
1309 	return NULL;
1310 #endif
1311 }
1312 
1313 void* outgoing_ssl_fd(void* sslctx, int fd)
1314 {
1315 #ifdef HAVE_SSL
1316 	SSL* ssl = SSL_new((SSL_CTX*)sslctx);
1317 	if(!ssl) {
1318 		log_crypto_err("could not SSL_new");
1319 		return NULL;
1320 	}
1321 	SSL_set_connect_state(ssl);
1322 	(void)SSL_set_mode(ssl, (long)SSL_MODE_AUTO_RETRY);
1323 	if(!SSL_set_fd(ssl, fd)) {
1324 		log_crypto_err("could not SSL_set_fd");
1325 		SSL_free(ssl);
1326 		return NULL;
1327 	}
1328 	return ssl;
1329 #else
1330 	(void)sslctx; (void)fd;
1331 	return NULL;
1332 #endif
1333 }
1334 
1335 int check_auth_name_for_ssl(char* auth_name)
1336 {
1337 	if(!auth_name) return 1;
1338 #if defined(HAVE_SSL) && !defined(HAVE_SSL_SET1_HOST) && !defined(HAVE_X509_VERIFY_PARAM_SET1_HOST)
1339 	log_err("the query has an auth_name %s, but libssl has no call to "
1340 		"perform TLS authentication.  Remove that name from config "
1341 		"or upgrade the ssl crypto library.", auth_name);
1342 	return 0;
1343 #else
1344 	return 1;
1345 #endif
1346 }
1347 
1348 /** set the authname on an SSL structure, SSL* ssl */
1349 int set_auth_name_on_ssl(void* ssl, char* auth_name, int use_sni)
1350 {
1351 	if(!auth_name) return 1;
1352 #ifdef HAVE_SSL
1353 	if(use_sni) {
1354 		(void)SSL_set_tlsext_host_name(ssl, auth_name);
1355 	}
1356 #else
1357 	(void)ssl;
1358 	(void)use_sni;
1359 #endif
1360 #ifdef HAVE_SSL_SET1_HOST
1361 	SSL_set_verify(ssl, SSL_VERIFY_PEER, NULL);
1362 	/* setting the hostname makes openssl verify the
1363 	 * host name in the x509 certificate in the
1364 	 * SSL connection*/
1365 	if(!SSL_set1_host(ssl, auth_name)) {
1366 		log_err("SSL_set1_host failed");
1367 		return 0;
1368 	}
1369 #elif defined(HAVE_X509_VERIFY_PARAM_SET1_HOST)
1370 	/* openssl 1.0.2 has this function that can be used for
1371 	 * set1_host like verification */
1372 	if(auth_name) {
1373 		X509_VERIFY_PARAM* param = SSL_get0_param(ssl);
1374 #  ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
1375 		X509_VERIFY_PARAM_set_hostflags(param, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
1376 #  endif
1377 		if(!X509_VERIFY_PARAM_set1_host(param, auth_name, strlen(auth_name))) {
1378 			log_err("X509_VERIFY_PARAM_set1_host failed");
1379 			return 0;
1380 		}
1381 		SSL_set_verify(ssl, SSL_VERIFY_PEER, NULL);
1382 	}
1383 #else
1384 	verbose(VERB_ALGO, "the query has an auth_name, but libssl has no call to perform TLS authentication");
1385 #endif /* HAVE_SSL_SET1_HOST */
1386 	return 1;
1387 }
1388 
1389 #if defined(HAVE_SSL) && defined(OPENSSL_THREADS) && !defined(THREADS_DISABLED) && defined(CRYPTO_LOCK) && OPENSSL_VERSION_NUMBER < 0x10100000L
1390 /** global lock list for openssl locks */
1391 static lock_basic_type *ub_openssl_locks = NULL;
1392 
1393 /** callback that gets thread id for openssl */
1394 #ifdef HAVE_CRYPTO_THREADID_SET_CALLBACK
1395 static void
1396 ub_crypto_id_cb(CRYPTO_THREADID *id)
1397 {
1398 	CRYPTO_THREADID_set_numeric(id, (unsigned long)log_thread_get());
1399 }
1400 #else
1401 static unsigned long
1402 ub_crypto_id_cb(void)
1403 {
1404 	return (unsigned long)log_thread_get();
1405 }
1406 #endif
1407 
1408 static void
1409 ub_crypto_lock_cb(int mode, int type, const char *ATTR_UNUSED(file),
1410 	int ATTR_UNUSED(line))
1411 {
1412 	if((mode&CRYPTO_LOCK)) {
1413 		lock_basic_lock(&ub_openssl_locks[type]);
1414 	} else {
1415 		lock_basic_unlock(&ub_openssl_locks[type]);
1416 	}
1417 }
1418 #endif /* OPENSSL_THREADS */
1419 
1420 int ub_openssl_lock_init(void)
1421 {
1422 #if defined(HAVE_SSL) && defined(OPENSSL_THREADS) && !defined(THREADS_DISABLED) && defined(CRYPTO_LOCK) && OPENSSL_VERSION_NUMBER < 0x10100000L
1423 	int i;
1424 	ub_openssl_locks = (lock_basic_type*)reallocarray(
1425 		NULL, (size_t)CRYPTO_num_locks(), sizeof(lock_basic_type));
1426 	if(!ub_openssl_locks)
1427 		return 0;
1428 	for(i=0; i<CRYPTO_num_locks(); i++) {
1429 		lock_basic_init(&ub_openssl_locks[i]);
1430 	}
1431 #  ifdef HAVE_CRYPTO_THREADID_SET_CALLBACK
1432 	CRYPTO_THREADID_set_callback(&ub_crypto_id_cb);
1433 #  else
1434 	CRYPTO_set_id_callback(&ub_crypto_id_cb);
1435 #  endif
1436 	CRYPTO_set_locking_callback(&ub_crypto_lock_cb);
1437 #endif /* OPENSSL_THREADS */
1438 	return 1;
1439 }
1440 
1441 void ub_openssl_lock_delete(void)
1442 {
1443 #if defined(HAVE_SSL) && defined(OPENSSL_THREADS) && !defined(THREADS_DISABLED) && defined(CRYPTO_LOCK) && OPENSSL_VERSION_NUMBER < 0x10100000L
1444 	int i;
1445 	if(!ub_openssl_locks)
1446 		return;
1447 #  ifdef HAVE_CRYPTO_THREADID_SET_CALLBACK
1448 	CRYPTO_THREADID_set_callback(NULL);
1449 #  else
1450 	CRYPTO_set_id_callback(NULL);
1451 #  endif
1452 	CRYPTO_set_locking_callback(NULL);
1453 	for(i=0; i<CRYPTO_num_locks(); i++) {
1454 		lock_basic_destroy(&ub_openssl_locks[i]);
1455 	}
1456 	free(ub_openssl_locks);
1457 #endif /* OPENSSL_THREADS */
1458 }
1459 
1460 int listen_sslctx_setup_ticket_keys(void* sslctx, struct config_strlist* tls_session_ticket_keys) {
1461 #ifdef HAVE_SSL
1462 	size_t s = 1;
1463 	struct config_strlist* p;
1464 	struct tls_session_ticket_key *keys;
1465 	for(p = tls_session_ticket_keys; p; p = p->next) {
1466 		s++;
1467 	}
1468 	keys = calloc(s, sizeof(struct tls_session_ticket_key));
1469 	if(!keys)
1470 		return 0;
1471 	memset(keys, 0, s*sizeof(*keys));
1472 	ticket_keys = keys;
1473 
1474 	for(p = tls_session_ticket_keys; p; p = p->next) {
1475 		size_t n;
1476 		unsigned char *data;
1477 		FILE *f;
1478 
1479 		data = (unsigned char *)malloc(80);
1480 		if(!data)
1481 			return 0;
1482 
1483 		f = fopen(p->str, "rb");
1484 		if(!f) {
1485 			log_err("could not read tls-session-ticket-key %s: %s", p->str, strerror(errno));
1486 			free(data);
1487 			return 0;
1488 		}
1489 		n = fread(data, 1, 80, f);
1490 		fclose(f);
1491 
1492 		if(n != 80) {
1493 			log_err("tls-session-ticket-key %s is %d bytes, must be 80 bytes", p->str, (int)n);
1494 			free(data);
1495 			return 0;
1496 		}
1497 		verbose(VERB_OPS, "read tls-session-ticket-key: %s", p->str);
1498 
1499 		keys->key_name = data;
1500 		keys->aes_key = data + 16;
1501 		keys->hmac_key = data + 48;
1502 		keys++;
1503 	}
1504 	/* terminate array with NULL key name entry */
1505 	keys->key_name = NULL;
1506 #  ifdef HAVE_SSL_CTX_SET_TLSEXT_TICKET_KEY_EVP_CB
1507 	if(SSL_CTX_set_tlsext_ticket_key_evp_cb(sslctx, tls_session_ticket_key_cb) == 0) {
1508 		log_err("no support for TLS session ticket");
1509 		return 0;
1510 	}
1511 #  else
1512 	if(SSL_CTX_set_tlsext_ticket_key_cb(sslctx, tls_session_ticket_key_cb) == 0) {
1513 		log_err("no support for TLS session ticket");
1514 		return 0;
1515 	}
1516 #  endif
1517 	return 1;
1518 #else
1519 	(void)sslctx;
1520 	(void)tls_session_ticket_keys;
1521 	return 0;
1522 #endif
1523 
1524 }
1525 
1526 #ifdef HAVE_SSL
1527 int tls_session_ticket_key_cb(SSL *ATTR_UNUSED(sslctx), unsigned char* key_name,
1528 	unsigned char* iv, EVP_CIPHER_CTX *evp_sctx,
1529 #ifdef HAVE_SSL_CTX_SET_TLSEXT_TICKET_KEY_EVP_CB
1530 	EVP_MAC_CTX *hmac_ctx,
1531 #else
1532 	HMAC_CTX* hmac_ctx,
1533 #endif
1534 	int enc)
1535 {
1536 #ifdef HAVE_SSL
1537 #  ifdef HAVE_SSL_CTX_SET_TLSEXT_TICKET_KEY_EVP_CB
1538 	OSSL_PARAM params[3];
1539 #  else
1540 	const EVP_MD *digest;
1541 #  endif
1542 	const EVP_CIPHER *cipher;
1543 	int evp_cipher_length;
1544 #  ifndef HAVE_SSL_CTX_SET_TLSEXT_TICKET_KEY_EVP_CB
1545 	digest = EVP_sha256();
1546 #  endif
1547 	cipher = EVP_aes_256_cbc();
1548 	evp_cipher_length = EVP_CIPHER_iv_length(cipher);
1549 	if( enc == 1 ) {
1550 		/* encrypt */
1551 		verbose(VERB_CLIENT, "start session encrypt");
1552 		memcpy(key_name, ticket_keys->key_name, 16);
1553 		if (RAND_bytes(iv, evp_cipher_length) != 1) {
1554 			verbose(VERB_CLIENT, "RAND_bytes failed");
1555 			return -1;
1556 		}
1557 		if (EVP_EncryptInit_ex(evp_sctx, cipher, NULL, ticket_keys->aes_key, iv) != 1) {
1558 			verbose(VERB_CLIENT, "EVP_EncryptInit_ex failed");
1559 			return -1;
1560 		}
1561 #ifdef HAVE_SSL_CTX_SET_TLSEXT_TICKET_KEY_EVP_CB
1562 		params[0] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY,
1563 			ticket_keys->hmac_key, 32);
1564 		params[1] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
1565 			"sha256", 0);
1566 		params[2] = OSSL_PARAM_construct_end();
1567 #ifdef HAVE_EVP_MAC_CTX_SET_PARAMS
1568 		EVP_MAC_CTX_set_params(hmac_ctx, params);
1569 #else
1570 		EVP_MAC_set_ctx_params(hmac_ctx, params);
1571 #endif
1572 #elif !defined(HMAC_INIT_EX_RETURNS_VOID)
1573 		if (HMAC_Init_ex(hmac_ctx, ticket_keys->hmac_key, 32, digest, NULL) != 1) {
1574 			verbose(VERB_CLIENT, "HMAC_Init_ex failed");
1575 			return -1;
1576 		}
1577 #else
1578 		HMAC_Init_ex(hmac_ctx, ticket_keys->hmac_key, 32, digest, NULL);
1579 #endif
1580 		return 1;
1581 	} else if (enc == 0) {
1582 		/* decrypt */
1583 		struct tls_session_ticket_key *key;
1584 		verbose(VERB_CLIENT, "start session decrypt");
1585 		for(key = ticket_keys; key->key_name != NULL; key++) {
1586 			if (!memcmp(key_name, key->key_name, 16)) {
1587 				verbose(VERB_CLIENT, "Found session_key");
1588 				break;
1589 			}
1590 		}
1591 		if(key->key_name == NULL) {
1592 			verbose(VERB_CLIENT, "Not found session_key");
1593 			return 0;
1594 		}
1595 
1596 #ifdef HAVE_SSL_CTX_SET_TLSEXT_TICKET_KEY_EVP_CB
1597 		params[0] = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_KEY,
1598 			key->hmac_key, 32);
1599 		params[1] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
1600 			"sha256", 0);
1601 		params[2] = OSSL_PARAM_construct_end();
1602 #ifdef HAVE_EVP_MAC_CTX_SET_PARAMS
1603 		EVP_MAC_CTX_set_params(hmac_ctx, params);
1604 #else
1605 		EVP_MAC_set_ctx_params(hmac_ctx, params);
1606 #endif
1607 #elif !defined(HMAC_INIT_EX_RETURNS_VOID)
1608 		if (HMAC_Init_ex(hmac_ctx, key->hmac_key, 32, digest, NULL) != 1) {
1609 			verbose(VERB_CLIENT, "HMAC_Init_ex failed");
1610 			return -1;
1611 		}
1612 #else
1613 		HMAC_Init_ex(hmac_ctx, key->hmac_key, 32, digest, NULL);
1614 #endif
1615 		if (EVP_DecryptInit_ex(evp_sctx, cipher, NULL, key->aes_key, iv) != 1) {
1616 			log_err("EVP_DecryptInit_ex failed");
1617 			return -1;
1618 		}
1619 
1620 		return (key == ticket_keys) ? 1 : 2;
1621 	}
1622 	return -1;
1623 #else
1624 	(void)key_name;
1625 	(void)iv;
1626 	(void)evp_sctx;
1627 	(void)hmac_ctx;
1628 	(void)enc;
1629 	return 0;
1630 #endif
1631 }
1632 #endif /* HAVE_SSL */
1633 
1634 void
1635 listen_sslctx_delete_ticket_keys(void)
1636 {
1637 	struct tls_session_ticket_key *key;
1638 	if(!ticket_keys) return;
1639 	for(key = ticket_keys; key->key_name != NULL; key++) {
1640 		/* wipe key data from memory*/
1641 #ifdef HAVE_EXPLICIT_BZERO
1642 		explicit_bzero(key->key_name, 80);
1643 #else
1644 		memset(key->key_name, 0xdd, 80);
1645 #endif
1646 		free(key->key_name);
1647 	}
1648 	free(ticket_keys);
1649 	ticket_keys = NULL;
1650 }
1651 
1652 #  ifndef USE_WINSOCK
1653 char*
1654 sock_strerror(int errn)
1655 {
1656 	return strerror(errn);
1657 }
1658 
1659 void
1660 sock_close(int socket)
1661 {
1662 	close(socket);
1663 }
1664 
1665 #  else
1666 char*
1667 sock_strerror(int ATTR_UNUSED(errn))
1668 {
1669 	return wsa_strerror(WSAGetLastError());
1670 }
1671 
1672 void
1673 sock_close(int socket)
1674 {
1675 	closesocket(socket);
1676 }
1677 #  endif /* USE_WINSOCK */
1678