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