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