xref: /freebsd/contrib/unbound/util/net_help.c (revision 1f1e2261e341e6ca6862f82261066ef1705f0a7a)
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 			/* return error if a cert fails */
1166 			verbose(VERB_ALGO, "%s %d:%s",
1167 				"Unable to parse certificate in memory",
1168 				(int)ERR_get_error(), ERR_error_string(ERR_get_error(), NULL));
1169 			return 0;
1170 		}
1171 		else {
1172 			/* return error if a cert add to store fails */
1173 			if (X509_STORE_add_cert(store, cert1) == 0) {
1174 				unsigned long error = ERR_peek_last_error();
1175 
1176 				/* Ignore error X509_R_CERT_ALREADY_IN_HASH_TABLE which means the
1177 				* certificate is already in the store.  */
1178 				if(ERR_GET_LIB(error) != ERR_LIB_X509 ||
1179 				   ERR_GET_REASON(error) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
1180 					verbose(VERB_ALGO, "%s %d:%s\n",
1181 					    "Error adding certificate", (int)ERR_get_error(),
1182 					     ERR_error_string(ERR_get_error(), NULL));
1183 					X509_free(cert1);
1184 					return 0;
1185 				}
1186 			}
1187 			X509_free(cert1);
1188 		}
1189 	} while ((pTargetCert = CertEnumCertificatesInStore(
1190 		hSystemStore, pTargetCert)) != 0);
1191 
1192 	/* Clean up memory and quit. */
1193 	if (pTargetCert)
1194 		CertFreeCertificateContext(pTargetCert);
1195 	if (hSystemStore)
1196 	{
1197 		if (!CertCloseStore(
1198 			hSystemStore, 0))
1199 			return 0;
1200 	}
1201 	verbose(VERB_ALGO, "Completed adding Windows certificates to CA store successfully");
1202 	return 1;
1203 }
1204 #endif /* USE_WINSOCK */
1205 
1206 void* connect_sslctx_create(char* key, char* pem, char* verifypem, int wincert)
1207 {
1208 #ifdef HAVE_SSL
1209 	SSL_CTX* ctx = SSL_CTX_new(SSLv23_client_method());
1210 	if(!ctx) {
1211 		log_crypto_err("could not allocate SSL_CTX pointer");
1212 		return NULL;
1213 	}
1214 #if SSL_OP_NO_SSLv2 != 0
1215 	if((SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2) & SSL_OP_NO_SSLv2)
1216 		!= SSL_OP_NO_SSLv2) {
1217 		log_crypto_err("could not set SSL_OP_NO_SSLv2");
1218 		SSL_CTX_free(ctx);
1219 		return NULL;
1220 	}
1221 #endif
1222 	if((SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv3) & SSL_OP_NO_SSLv3)
1223 		!= SSL_OP_NO_SSLv3) {
1224 		log_crypto_err("could not set SSL_OP_NO_SSLv3");
1225 		SSL_CTX_free(ctx);
1226 		return NULL;
1227 	}
1228 #if defined(SSL_OP_NO_RENEGOTIATION)
1229 	/* disable client renegotiation */
1230 	if((SSL_CTX_set_options(ctx, SSL_OP_NO_RENEGOTIATION) &
1231 		SSL_OP_NO_RENEGOTIATION) != SSL_OP_NO_RENEGOTIATION) {
1232 		log_crypto_err("could not set SSL_OP_NO_RENEGOTIATION");
1233 		SSL_CTX_free(ctx);
1234 		return 0;
1235 	}
1236 #endif
1237 	if(key && key[0]) {
1238 		if(!SSL_CTX_use_certificate_chain_file(ctx, pem)) {
1239 			log_err("error in client certificate %s", pem);
1240 			log_crypto_err("error in certificate file");
1241 			SSL_CTX_free(ctx);
1242 			return NULL;
1243 		}
1244 		if(!SSL_CTX_use_PrivateKey_file(ctx, key, SSL_FILETYPE_PEM)) {
1245 			log_err("error in client private key %s", key);
1246 			log_crypto_err("error in key file");
1247 			SSL_CTX_free(ctx);
1248 			return NULL;
1249 		}
1250 		if(!SSL_CTX_check_private_key(ctx)) {
1251 			log_err("error in client key %s", key);
1252 			log_crypto_err("error in SSL_CTX_check_private_key");
1253 			SSL_CTX_free(ctx);
1254 			return NULL;
1255 		}
1256 	}
1257 	if((verifypem && verifypem[0]) || wincert) {
1258 		if(verifypem && verifypem[0]) {
1259 			if(!SSL_CTX_load_verify_locations(ctx, verifypem, NULL)) {
1260 				log_crypto_err("error in SSL_CTX verify");
1261 				SSL_CTX_free(ctx);
1262 				return NULL;
1263 			}
1264 		}
1265 #ifdef USE_WINSOCK
1266 		if(wincert) {
1267 			if(!add_WIN_cacerts_to_openssl_store(ctx)) {
1268 				log_crypto_err("error in add_WIN_cacerts_to_openssl_store");
1269 				SSL_CTX_free(ctx);
1270 				return NULL;
1271 			}
1272 		}
1273 #else
1274 		if(wincert) {
1275 			if(!SSL_CTX_set_default_verify_paths(ctx)) {
1276 				log_crypto_err("error in default_verify_paths");
1277 				SSL_CTX_free(ctx);
1278 				return NULL;
1279 			}
1280 		}
1281 #endif
1282 		SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
1283 	}
1284 	return ctx;
1285 #else
1286 	(void)key; (void)pem; (void)verifypem; (void)wincert;
1287 	return NULL;
1288 #endif
1289 }
1290 
1291 void* incoming_ssl_fd(void* sslctx, int fd)
1292 {
1293 #ifdef HAVE_SSL
1294 	SSL* ssl = SSL_new((SSL_CTX*)sslctx);
1295 	if(!ssl) {
1296 		log_crypto_err("could not SSL_new");
1297 		return NULL;
1298 	}
1299 	SSL_set_accept_state(ssl);
1300 	(void)SSL_set_mode(ssl, (long)SSL_MODE_AUTO_RETRY);
1301 	if(!SSL_set_fd(ssl, fd)) {
1302 		log_crypto_err("could not SSL_set_fd");
1303 		SSL_free(ssl);
1304 		return NULL;
1305 	}
1306 	return ssl;
1307 #else
1308 	(void)sslctx; (void)fd;
1309 	return NULL;
1310 #endif
1311 }
1312 
1313 void* outgoing_ssl_fd(void* sslctx, int fd)
1314 {
1315 #ifdef HAVE_SSL
1316 	SSL* ssl = SSL_new((SSL_CTX*)sslctx);
1317 	if(!ssl) {
1318 		log_crypto_err("could not SSL_new");
1319 		return NULL;
1320 	}
1321 	SSL_set_connect_state(ssl);
1322 	(void)SSL_set_mode(ssl, (long)SSL_MODE_AUTO_RETRY);
1323 	if(!SSL_set_fd(ssl, fd)) {
1324 		log_crypto_err("could not SSL_set_fd");
1325 		SSL_free(ssl);
1326 		return NULL;
1327 	}
1328 	return ssl;
1329 #else
1330 	(void)sslctx; (void)fd;
1331 	return NULL;
1332 #endif
1333 }
1334 
1335 int check_auth_name_for_ssl(char* auth_name)
1336 {
1337 	if(!auth_name) return 1;
1338 #if defined(HAVE_SSL) && !defined(HAVE_SSL_SET1_HOST) && !defined(HAVE_X509_VERIFY_PARAM_SET1_HOST)
1339 	log_err("the query has an auth_name %s, but libssl has no call to "
1340 		"perform TLS authentication.  Remove that name from config "
1341 		"or upgrade the ssl crypto library.", auth_name);
1342 	return 0;
1343 #else
1344 	return 1;
1345 #endif
1346 }
1347 
1348 /** set the authname on an SSL structure, SSL* ssl */
1349 int set_auth_name_on_ssl(void* ssl, char* auth_name, int use_sni)
1350 {
1351 	if(!auth_name) return 1;
1352 #ifdef HAVE_SSL
1353 	if(use_sni) {
1354 		(void)SSL_set_tlsext_host_name(ssl, auth_name);
1355 	}
1356 #else
1357 	(void)ssl;
1358 	(void)use_sni;
1359 #endif
1360 #ifdef HAVE_SSL_SET1_HOST
1361 	SSL_set_verify(ssl, SSL_VERIFY_PEER, NULL);
1362 	/* setting the hostname makes openssl verify the
1363 	 * host name in the x509 certificate in the
1364 	 * SSL connection*/
1365 	if(!SSL_set1_host(ssl, auth_name)) {
1366 		log_err("SSL_set1_host failed");
1367 		return 0;
1368 	}
1369 #elif defined(HAVE_X509_VERIFY_PARAM_SET1_HOST)
1370 	/* openssl 1.0.2 has this function that can be used for
1371 	 * set1_host like verification */
1372 	if(auth_name) {
1373 		X509_VERIFY_PARAM* param = SSL_get0_param(ssl);
1374 #  ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
1375 		X509_VERIFY_PARAM_set_hostflags(param, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
1376 #  endif
1377 		if(!X509_VERIFY_PARAM_set1_host(param, auth_name, strlen(auth_name))) {
1378 			log_err("X509_VERIFY_PARAM_set1_host failed");
1379 			return 0;
1380 		}
1381 		SSL_set_verify(ssl, SSL_VERIFY_PEER, NULL);
1382 	}
1383 #else
1384 	verbose(VERB_ALGO, "the query has an auth_name, but libssl has no call to perform TLS authentication");
1385 #endif /* HAVE_SSL_SET1_HOST */
1386 	return 1;
1387 }
1388 
1389 #if defined(HAVE_SSL) && defined(OPENSSL_THREADS) && !defined(THREADS_DISABLED) && defined(CRYPTO_LOCK) && OPENSSL_VERSION_NUMBER < 0x10100000L
1390 /** global lock list for openssl locks */
1391 static lock_basic_type *ub_openssl_locks = NULL;
1392 
1393 /** callback that gets thread id for openssl */
1394 #ifdef HAVE_CRYPTO_THREADID_SET_CALLBACK
1395 static void
1396 ub_crypto_id_cb(CRYPTO_THREADID *id)
1397 {
1398 	CRYPTO_THREADID_set_numeric(id, (unsigned long)log_thread_get());
1399 }
1400 #else
1401 static unsigned long
1402 ub_crypto_id_cb(void)
1403 {
1404 	return (unsigned long)log_thread_get();
1405 }
1406 #endif
1407 
1408 static void
1409 ub_crypto_lock_cb(int mode, int type, const char *ATTR_UNUSED(file),
1410 	int ATTR_UNUSED(line))
1411 {
1412 	if((mode&CRYPTO_LOCK)) {
1413 		lock_basic_lock(&ub_openssl_locks[type]);
1414 	} else {
1415 		lock_basic_unlock(&ub_openssl_locks[type]);
1416 	}
1417 }
1418 #endif /* OPENSSL_THREADS */
1419 
1420 int ub_openssl_lock_init(void)
1421 {
1422 #if defined(HAVE_SSL) && defined(OPENSSL_THREADS) && !defined(THREADS_DISABLED) && defined(CRYPTO_LOCK) && OPENSSL_VERSION_NUMBER < 0x10100000L
1423 	int i;
1424 	ub_openssl_locks = (lock_basic_type*)reallocarray(
1425 		NULL, (size_t)CRYPTO_num_locks(), sizeof(lock_basic_type));
1426 	if(!ub_openssl_locks)
1427 		return 0;
1428 	for(i=0; i<CRYPTO_num_locks(); i++) {
1429 		lock_basic_init(&ub_openssl_locks[i]);
1430 	}
1431 #  ifdef HAVE_CRYPTO_THREADID_SET_CALLBACK
1432 	CRYPTO_THREADID_set_callback(&ub_crypto_id_cb);
1433 #  else
1434 	CRYPTO_set_id_callback(&ub_crypto_id_cb);
1435 #  endif
1436 	CRYPTO_set_locking_callback(&ub_crypto_lock_cb);
1437 #endif /* OPENSSL_THREADS */
1438 	return 1;
1439 }
1440 
1441 void ub_openssl_lock_delete(void)
1442 {
1443 #if defined(HAVE_SSL) && defined(OPENSSL_THREADS) && !defined(THREADS_DISABLED) && defined(CRYPTO_LOCK) && OPENSSL_VERSION_NUMBER < 0x10100000L
1444 	int i;
1445 	if(!ub_openssl_locks)
1446 		return;
1447 #  ifdef HAVE_CRYPTO_THREADID_SET_CALLBACK
1448 	CRYPTO_THREADID_set_callback(NULL);
1449 #  else
1450 	CRYPTO_set_id_callback(NULL);
1451 #  endif
1452 	CRYPTO_set_locking_callback(NULL);
1453 	for(i=0; i<CRYPTO_num_locks(); i++) {
1454 		lock_basic_destroy(&ub_openssl_locks[i]);
1455 	}
1456 	free(ub_openssl_locks);
1457 #endif /* OPENSSL_THREADS */
1458 }
1459 
1460 int listen_sslctx_setup_ticket_keys(void* sslctx, struct config_strlist* tls_session_ticket_keys) {
1461 #ifdef HAVE_SSL
1462 	size_t s = 1;
1463 	struct config_strlist* p;
1464 	struct tls_session_ticket_key *keys;
1465 	for(p = tls_session_ticket_keys; p; p = p->next) {
1466 		s++;
1467 	}
1468 	keys = calloc(s, sizeof(struct tls_session_ticket_key));
1469 	if(!keys)
1470 		return 0;
1471 	memset(keys, 0, s*sizeof(*keys));
1472 	ticket_keys = keys;
1473 
1474 	for(p = tls_session_ticket_keys; p; p = p->next) {
1475 		size_t n;
1476 		unsigned char *data;
1477 		FILE *f;
1478 
1479 		data = (unsigned char *)malloc(80);
1480 		if(!data)
1481 			return 0;
1482 
1483 		f = fopen(p->str, "rb");
1484 		if(!f) {
1485 			log_err("could not read tls-session-ticket-key %s: %s", p->str, strerror(errno));
1486 			free(data);
1487 			return 0;
1488 		}
1489 		n = fread(data, 1, 80, f);
1490 		fclose(f);
1491 
1492 		if(n != 80) {
1493 			log_err("tls-session-ticket-key %s is %d bytes, must be 80 bytes", p->str, (int)n);
1494 			free(data);
1495 			return 0;
1496 		}
1497 		verbose(VERB_OPS, "read tls-session-ticket-key: %s", p->str);
1498 
1499 		keys->key_name = data;
1500 		keys->aes_key = data + 16;
1501 		keys->hmac_key = data + 48;
1502 		keys++;
1503 	}
1504 	/* terminate array with NULL key name entry */
1505 	keys->key_name = NULL;
1506 #  ifdef HAVE_SSL_CTX_SET_TLSEXT_TICKET_KEY_EVP_CB
1507 	if(SSL_CTX_set_tlsext_ticket_key_evp_cb(sslctx, tls_session_ticket_key_cb) == 0) {
1508 		log_err("no support for TLS session ticket");
1509 		return 0;
1510 	}
1511 #  else
1512 	if(SSL_CTX_set_tlsext_ticket_key_cb(sslctx, tls_session_ticket_key_cb) == 0) {
1513 		log_err("no support for TLS session ticket");
1514 		return 0;
1515 	}
1516 #  endif
1517 	return 1;
1518 #else
1519 	(void)sslctx;
1520 	(void)tls_session_ticket_keys;
1521 	return 0;
1522 #endif
1523 
1524 }
1525 
1526 #ifdef HAVE_SSL
1527 int tls_session_ticket_key_cb(SSL *ATTR_UNUSED(sslctx), unsigned char* key_name,
1528 	unsigned char* iv, EVP_CIPHER_CTX *evp_sctx,
1529 #ifdef HAVE_SSL_CTX_SET_TLSEXT_TICKET_KEY_EVP_CB
1530 	EVP_MAC_CTX *hmac_ctx,
1531 #else
1532 	HMAC_CTX* hmac_ctx,
1533 #endif
1534 	int enc)
1535 {
1536 #ifdef HAVE_SSL
1537 #  ifdef HAVE_SSL_CTX_SET_TLSEXT_TICKET_KEY_EVP_CB
1538 	OSSL_PARAM params[3];
1539 #  else
1540 	const EVP_MD *digest;
1541 #  endif
1542 	const EVP_CIPHER *cipher;
1543 	int evp_cipher_length;
1544 #  ifndef HAVE_SSL_CTX_SET_TLSEXT_TICKET_KEY_EVP_CB
1545 	digest = EVP_sha256();
1546 #  endif
1547 	cipher = EVP_aes_256_cbc();
1548 	evp_cipher_length = EVP_CIPHER_iv_length(cipher);
1549 	if( enc == 1 ) {
1550 		/* encrypt */
1551 		verbose(VERB_CLIENT, "start session encrypt");
1552 		memcpy(key_name, ticket_keys->key_name, 16);
1553 		if (RAND_bytes(iv, evp_cipher_length) != 1) {
1554 			verbose(VERB_CLIENT, "RAND_bytes failed");
1555 			return -1;
1556 		}
1557 		if (EVP_EncryptInit_ex(evp_sctx, cipher, NULL, ticket_keys->aes_key, iv) != 1) {
1558 			verbose(VERB_CLIENT, "EVP_EncryptInit_ex failed");
1559 			return -1;
1560 		}
1561 #ifdef HAVE_SSL_CTX_SET_TLSEXT_TICKET_KEY_EVP_CB
1562 		params[0] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY,
1563 			ticket_keys->hmac_key, 32);
1564 		params[1] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
1565 			"sha256", 0);
1566 		params[2] = OSSL_PARAM_construct_end();
1567 #ifdef HAVE_EVP_MAC_CTX_SET_PARAMS
1568 		EVP_MAC_CTX_set_params(hmac_ctx, params);
1569 #else
1570 		EVP_MAC_set_ctx_params(hmac_ctx, params);
1571 #endif
1572 #elif !defined(HMAC_INIT_EX_RETURNS_VOID)
1573 		if (HMAC_Init_ex(hmac_ctx, ticket_keys->hmac_key, 32, digest, NULL) != 1) {
1574 			verbose(VERB_CLIENT, "HMAC_Init_ex failed");
1575 			return -1;
1576 		}
1577 #else
1578 		HMAC_Init_ex(hmac_ctx, ticket_keys->hmac_key, 32, digest, NULL);
1579 #endif
1580 		return 1;
1581 	} else if (enc == 0) {
1582 		/* decrypt */
1583 		struct tls_session_ticket_key *key;
1584 		verbose(VERB_CLIENT, "start session decrypt");
1585 		for(key = ticket_keys; key->key_name != NULL; key++) {
1586 			if (!memcmp(key_name, key->key_name, 16)) {
1587 				verbose(VERB_CLIENT, "Found session_key");
1588 				break;
1589 			}
1590 		}
1591 		if(key->key_name == NULL) {
1592 			verbose(VERB_CLIENT, "Not found session_key");
1593 			return 0;
1594 		}
1595 
1596 #ifdef HAVE_SSL_CTX_SET_TLSEXT_TICKET_KEY_EVP_CB
1597 		params[0] = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_KEY,
1598 			key->hmac_key, 32);
1599 		params[1] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
1600 			"sha256", 0);
1601 		params[2] = OSSL_PARAM_construct_end();
1602 #ifdef HAVE_EVP_MAC_CTX_SET_PARAMS
1603 		EVP_MAC_CTX_set_params(hmac_ctx, params);
1604 #else
1605 		EVP_MAC_set_ctx_params(hmac_ctx, params);
1606 #endif
1607 #elif !defined(HMAC_INIT_EX_RETURNS_VOID)
1608 		if (HMAC_Init_ex(hmac_ctx, key->hmac_key, 32, digest, NULL) != 1) {
1609 			verbose(VERB_CLIENT, "HMAC_Init_ex failed");
1610 			return -1;
1611 		}
1612 #else
1613 		HMAC_Init_ex(hmac_ctx, key->hmac_key, 32, digest, NULL);
1614 #endif
1615 		if (EVP_DecryptInit_ex(evp_sctx, cipher, NULL, key->aes_key, iv) != 1) {
1616 			log_err("EVP_DecryptInit_ex failed");
1617 			return -1;
1618 		}
1619 
1620 		return (key == ticket_keys) ? 1 : 2;
1621 	}
1622 	return -1;
1623 #else
1624 	(void)key_name;
1625 	(void)iv;
1626 	(void)evp_sctx;
1627 	(void)hmac_ctx;
1628 	(void)enc;
1629 	return 0;
1630 #endif
1631 }
1632 #endif /* HAVE_SSL */
1633 
1634 void
1635 listen_sslctx_delete_ticket_keys(void)
1636 {
1637 	struct tls_session_ticket_key *key;
1638 	if(!ticket_keys) return;
1639 	for(key = ticket_keys; key->key_name != NULL; key++) {
1640 		/* wipe key data from memory*/
1641 #ifdef HAVE_EXPLICIT_BZERO
1642 		explicit_bzero(key->key_name, 80);
1643 #else
1644 		memset(key->key_name, 0xdd, 80);
1645 #endif
1646 		free(key->key_name);
1647 	}
1648 	free(ticket_keys);
1649 	ticket_keys = NULL;
1650 }
1651 
1652 #  ifndef USE_WINSOCK
1653 char*
1654 sock_strerror(int errn)
1655 {
1656 	return strerror(errn);
1657 }
1658 
1659 void
1660 sock_close(int socket)
1661 {
1662 	close(socket);
1663 }
1664 
1665 #  else
1666 char*
1667 sock_strerror(int ATTR_UNUSED(errn))
1668 {
1669 	return wsa_strerror(WSAGetLastError());
1670 }
1671 
1672 void
1673 sock_close(int socket)
1674 {
1675 	closesocket(socket);
1676 }
1677 #  endif /* USE_WINSOCK */
1678