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