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