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