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