xref: /freebsd/contrib/unbound/util/edns.c (revision 5685098846d7f11ad642d9804d94dc7429a7b212)
1 /*
2  * util/edns.c - handle base EDNS options.
3  *
4  * Copyright (c) 2018, 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 /**
37  * \file
38  *
39  * This file contains functions for base EDNS options.
40  */
41 
42 #include "config.h"
43 #include "util/edns.h"
44 #include "util/config_file.h"
45 #include "util/netevent.h"
46 #include "util/net_help.h"
47 #include "util/regional.h"
48 #include "util/rfc_1982.h"
49 #include "util/siphash.h"
50 #include "util/data/msgparse.h"
51 #include "util/data/msgreply.h"
52 #include "sldns/sbuffer.h"
53 
54 #if 0
55 /* XXX: remove me */
56 #include "edns.h"
57 #endif
58 
edns_strings_create(void)59 struct edns_strings* edns_strings_create(void)
60 {
61 	struct edns_strings* edns_strings = calloc(1,
62 		sizeof(struct edns_strings));
63 	if(!edns_strings)
64 		return NULL;
65 	if(!(edns_strings->region = regional_create())) {
66 		edns_strings_delete(edns_strings);
67 		return NULL;
68 	}
69 	return edns_strings;
70 }
71 
edns_strings_delete(struct edns_strings * edns_strings)72 void edns_strings_delete(struct edns_strings* edns_strings)
73 {
74 	if(!edns_strings)
75 		return;
76 	regional_destroy(edns_strings->region);
77 	free(edns_strings);
78 }
79 
80 static int
edns_strings_client_insert(struct edns_strings * edns_strings,struct sockaddr_storage * addr,socklen_t addrlen,int net,const char * string)81 edns_strings_client_insert(struct edns_strings* edns_strings,
82 	struct sockaddr_storage* addr, socklen_t addrlen, int net,
83 	const char* string)
84 {
85 	struct edns_string_addr* esa = regional_alloc_zero(edns_strings->region,
86 		sizeof(struct edns_string_addr));
87 	if(!esa)
88 		return 0;
89 	esa->string_len = strlen(string);
90 	esa->string = regional_alloc_init(edns_strings->region, string,
91 		esa->string_len);
92 	if(!esa->string)
93 		return 0;
94 	if(!addr_tree_insert(&edns_strings->client_strings, &esa->node, addr,
95 		addrlen, net)) {
96 		verbose(VERB_QUERY, "duplicate EDNS client string ignored.");
97 	}
98 	return 1;
99 }
100 
edns_strings_apply_cfg(struct edns_strings * edns_strings,struct config_file * config)101 int edns_strings_apply_cfg(struct edns_strings* edns_strings,
102 	struct config_file* config)
103 {
104 	struct config_str2list* c;
105 	regional_free_all(edns_strings->region);
106 	addr_tree_init(&edns_strings->client_strings);
107 
108 	for(c=config->edns_client_strings; c; c=c->next) {
109 		struct sockaddr_storage addr;
110 		socklen_t addrlen;
111 		int net;
112 		log_assert(c->str && c->str2);
113 
114 		if(!netblockstrtoaddr(c->str, UNBOUND_DNS_PORT, &addr, &addrlen,
115 			&net)) {
116 			log_err("cannot parse EDNS client string IP netblock: "
117 				"%s", c->str);
118 			return 0;
119 		}
120 		if(!edns_strings_client_insert(edns_strings, &addr, addrlen,
121 			net, c->str2)) {
122 			log_err("out of memory while adding EDNS strings");
123 			return 0;
124 		}
125 	}
126 	edns_strings->client_string_opcode = config->edns_client_string_opcode;
127 
128 	addr_tree_init_parents(&edns_strings->client_strings);
129 	return 1;
130 }
131 
132 struct edns_string_addr*
edns_string_addr_lookup(rbtree_type * tree,struct sockaddr_storage * addr,socklen_t addrlen)133 edns_string_addr_lookup(rbtree_type* tree, struct sockaddr_storage* addr,
134 	socklen_t addrlen)
135 {
136 	return (struct edns_string_addr*)addr_tree_lookup(tree, addr, addrlen);
137 }
138 
139 uint8_t*
edns_cookie_server_hash(const uint8_t * in,const uint8_t * secret,int v4,uint8_t * hash)140 edns_cookie_server_hash(const uint8_t* in, const uint8_t* secret, int v4,
141 	uint8_t* hash)
142 {
143 	v4?siphash(in, 20, secret, hash, 8):siphash(in, 32, secret, hash, 8);
144 	return hash;
145 }
146 
147 void
edns_cookie_server_write(uint8_t * buf,const uint8_t * secret,int v4,uint32_t timestamp)148 edns_cookie_server_write(uint8_t* buf, const uint8_t* secret, int v4,
149 	uint32_t timestamp)
150 {
151 	uint8_t hash[8];
152 	buf[ 8] = 1;   /* Version */
153 	buf[ 9] = 0;   /* Reserved */
154 	buf[10] = 0;   /* Reserved */
155 	buf[11] = 0;   /* Reserved */
156 	sldns_write_uint32(buf + 12, timestamp);
157 	(void)edns_cookie_server_hash(buf, secret, v4, hash);
158 	memcpy(buf + 16, hash, 8);
159 }
160 
161 enum edns_cookie_val_status
edns_cookie_server_validate(const uint8_t * cookie,size_t cookie_len,const uint8_t * secret,size_t secret_len,int v4,const uint8_t * hash_input,uint32_t now)162 edns_cookie_server_validate(const uint8_t* cookie, size_t cookie_len,
163 	const uint8_t* secret, size_t secret_len, int v4,
164 	const uint8_t* hash_input, uint32_t now)
165 {
166 	uint8_t hash[8];
167 	uint32_t timestamp;
168 	uint32_t subt_1982 = 0; /* Initialize for the compiler; unused value */
169 	int comp_1982;
170 	if(cookie_len != 24)
171 		/* RFC9018 cookies are 24 bytes long */
172 		return COOKIE_STATUS_CLIENT_ONLY;
173 	if(secret_len != 16 ||  /* RFC9018 cookies have 16 byte secrets */
174 		cookie[8] != 1) /* RFC9018 cookies are cookie version 1 */
175 		return COOKIE_STATUS_INVALID;
176 	timestamp = sldns_read_uint32(cookie + 12);
177 	if((comp_1982 = compare_1982(now, timestamp)) > 0
178 		&& (subt_1982 = subtract_1982(timestamp, now)) > 3600)
179 		/* Cookie is older than 1 hour (see RFC9018 Section 4.3.) */
180 		return COOKIE_STATUS_EXPIRED;
181 	if(comp_1982 <= 0 && subtract_1982(now, timestamp) > 300)
182 		/* Cookie time is more than 5 minutes in the future.
183 		 * (see RFC9018 Section 4.3.) */
184 		return COOKIE_STATUS_FUTURE;
185 	if(memcmp(edns_cookie_server_hash(hash_input, secret, v4, hash),
186 		cookie + 16, 8) != 0)
187 		/* Hashes do not match */
188 		return COOKIE_STATUS_INVALID;
189 	if(comp_1982 > 0 && subt_1982 > 1800)
190 		/* Valid cookie but older than 30 minutes, so create a new one
191 		 * anyway */
192 		return COOKIE_STATUS_VALID_RENEW;
193 	return COOKIE_STATUS_VALID;
194 }
195 
196 struct cookie_secrets*
cookie_secrets_create(void)197 cookie_secrets_create(void)
198 {
199 	struct cookie_secrets* cookie_secrets = calloc(1,
200 		sizeof(*cookie_secrets));
201 	if(!cookie_secrets)
202 		return NULL;
203 	lock_basic_init(&cookie_secrets->lock);
204 	lock_protect(&cookie_secrets->lock, &cookie_secrets->cookie_count,
205 		sizeof(cookie_secrets->cookie_count));
206 	lock_protect(&cookie_secrets->lock, cookie_secrets->cookie_secrets,
207 		sizeof(cookie_secret_type)*UNBOUND_COOKIE_HISTORY_SIZE);
208 	return cookie_secrets;
209 }
210 
211 void
cookie_secrets_delete(struct cookie_secrets * cookie_secrets)212 cookie_secrets_delete(struct cookie_secrets* cookie_secrets)
213 {
214 	if(!cookie_secrets)
215 		return;
216 	lock_basic_destroy(&cookie_secrets->lock);
217 	explicit_bzero(cookie_secrets->cookie_secrets,
218 		sizeof(cookie_secret_type)*UNBOUND_COOKIE_HISTORY_SIZE);
219 	free(cookie_secrets);
220 }
221 
222 /** Read the cookie secret file */
223 static int
cookie_secret_file_read(struct cookie_secrets * cookie_secrets,char * cookie_secret_file)224 cookie_secret_file_read(struct cookie_secrets* cookie_secrets,
225 	char* cookie_secret_file)
226 {
227 	char secret[UNBOUND_COOKIE_SECRET_SIZE * 2 + 2/*'\n' and '\0'*/];
228 	FILE* f;
229 	int corrupt = 0;
230 	size_t count;
231 
232 	log_assert(cookie_secret_file != NULL);
233 	cookie_secrets->cookie_count = 0;
234 	f = fopen(cookie_secret_file, "r");
235 	/* a non-existing cookie file is not an error */
236 	if( f == NULL ) {
237 		if(errno != EPERM) {
238 			log_err("Could not read cookie-secret-file '%s': %s",
239 				cookie_secret_file, strerror(errno));
240 			return 0;
241 		}
242 		return 1;
243 	}
244 	/* cookie secret file exists and is readable */
245 	for( count = 0; count < UNBOUND_COOKIE_HISTORY_SIZE; count++ ) {
246 		size_t secret_len = 0;
247 		ssize_t decoded_len = 0;
248 		if( fgets(secret, sizeof(secret), f) == NULL ) { break; }
249 		secret_len = strlen(secret);
250 		if( secret_len == 0 ) { break; }
251 		log_assert( secret_len <= sizeof(secret) );
252 		secret_len = secret[secret_len - 1] == '\n' ? secret_len - 1 : secret_len;
253 		if( secret_len != UNBOUND_COOKIE_SECRET_SIZE * 2 ) { corrupt++; break; }
254 		/* needed for `hex_pton`; stripping potential `\n` */
255 		secret[secret_len] = '\0';
256 		decoded_len = hex_pton(secret, cookie_secrets->cookie_secrets[count].cookie_secret,
257 		                       UNBOUND_COOKIE_SECRET_SIZE);
258 		if( decoded_len != UNBOUND_COOKIE_SECRET_SIZE ) { corrupt++; break; }
259 		cookie_secrets->cookie_count++;
260 	}
261 	fclose(f);
262 	return corrupt == 0;
263 }
264 
265 int
cookie_secrets_apply_cfg(struct cookie_secrets * cookie_secrets,char * cookie_secret_file)266 cookie_secrets_apply_cfg(struct cookie_secrets* cookie_secrets,
267 	char* cookie_secret_file)
268 {
269 	if(!cookie_secrets) {
270 		if(!cookie_secret_file || !cookie_secret_file[0])
271 			return 1; /* There is nothing to read anyway */
272 		log_err("Could not read cookie secrets, no structure alloced");
273 		return 0;
274 	}
275 	if(!cookie_secret_file_read(cookie_secrets, cookie_secret_file))
276 		return 0;
277 	return 1;
278 }
279 
280 enum edns_cookie_val_status
cookie_secrets_server_validate(const uint8_t * cookie,size_t cookie_len,struct cookie_secrets * cookie_secrets,int v4,const uint8_t * hash_input,uint32_t now)281 cookie_secrets_server_validate(const uint8_t* cookie, size_t cookie_len,
282 	struct cookie_secrets* cookie_secrets, int v4,
283 	const uint8_t* hash_input, uint32_t now)
284 {
285 	size_t i;
286 	enum edns_cookie_val_status cookie_val_status,
287 		last = COOKIE_STATUS_INVALID;
288 	if(!cookie_secrets)
289 		return COOKIE_STATUS_INVALID; /* There are no cookie secrets.*/
290 	lock_basic_lock(&cookie_secrets->lock);
291 	if(cookie_secrets->cookie_count == 0) {
292 		lock_basic_unlock(&cookie_secrets->lock);
293 		return COOKIE_STATUS_INVALID; /* There are no cookie secrets.*/
294 	}
295 	for(i=0; i<cookie_secrets->cookie_count; i++) {
296 		cookie_val_status = edns_cookie_server_validate(cookie,
297 			cookie_len,
298 			cookie_secrets->cookie_secrets[i].cookie_secret,
299 			UNBOUND_COOKIE_SECRET_SIZE, v4, hash_input, now);
300 		if(cookie_val_status == COOKIE_STATUS_VALID ||
301 			cookie_val_status == COOKIE_STATUS_VALID_RENEW) {
302 			lock_basic_unlock(&cookie_secrets->lock);
303 			/* For staging cookies, write a fresh cookie. */
304 			if(i != 0)
305 				return COOKIE_STATUS_VALID_RENEW;
306 			return cookie_val_status;
307 		}
308 		if(last == COOKIE_STATUS_INVALID)
309 			last = cookie_val_status; /* Store more interesting
310 				failure to return. */
311 	}
312 	lock_basic_unlock(&cookie_secrets->lock);
313 	return last;
314 }
315 
add_cookie_secret(struct cookie_secrets * cookie_secrets,uint8_t * secret,size_t secret_len)316 void add_cookie_secret(struct cookie_secrets* cookie_secrets,
317 	uint8_t* secret, size_t secret_len)
318 {
319 	log_assert(secret_len == UNBOUND_COOKIE_SECRET_SIZE);
320 	(void)secret_len;
321 	if(!cookie_secrets)
322 		return;
323 
324 	/* New cookie secret becomes the staging secret (position 1)
325 	 * unless there is no active cookie yet, then it becomes the active
326 	 * secret.  If the UNBOUND_COOKIE_HISTORY_SIZE > 2 then all staging cookies
327 	 * are moved one position down.
328 	 */
329 	if(cookie_secrets->cookie_count == 0) {
330 		memcpy( cookie_secrets->cookie_secrets->cookie_secret
331 		       , secret, UNBOUND_COOKIE_SECRET_SIZE);
332 		cookie_secrets->cookie_count = 1;
333 		explicit_bzero(secret, UNBOUND_COOKIE_SECRET_SIZE);
334 		return;
335 	}
336 #if UNBOUND_COOKIE_HISTORY_SIZE > 2
337 	memmove( &cookie_secrets->cookie_secrets[2], &cookie_secrets->cookie_secrets[1]
338 	       , sizeof(struct cookie_secret) * (UNBOUND_COOKIE_HISTORY_SIZE - 2));
339 #endif
340 	memcpy( cookie_secrets->cookie_secrets[1].cookie_secret
341 	      , secret, UNBOUND_COOKIE_SECRET_SIZE);
342 	cookie_secrets->cookie_count = cookie_secrets->cookie_count     < UNBOUND_COOKIE_HISTORY_SIZE
343 	                  ? cookie_secrets->cookie_count + 1 : UNBOUND_COOKIE_HISTORY_SIZE;
344 	explicit_bzero(secret, UNBOUND_COOKIE_SECRET_SIZE);
345 }
346 
activate_cookie_secret(struct cookie_secrets * cookie_secrets)347 void activate_cookie_secret(struct cookie_secrets* cookie_secrets)
348 {
349 	uint8_t active_secret[UNBOUND_COOKIE_SECRET_SIZE];
350 	if(!cookie_secrets)
351 		return;
352 	/* The staging secret becomes the active secret.
353 	 * The active secret becomes a staging secret.
354 	 * If the UNBOUND_COOKIE_HISTORY_SIZE > 2 then all staging secrets are moved
355 	 * one position up and the previously active secret becomes the last
356 	 * staging secret.
357 	 */
358 	if(cookie_secrets->cookie_count < 2)
359 		return;
360 	memcpy( active_secret, cookie_secrets->cookie_secrets[0].cookie_secret
361 	      , UNBOUND_COOKIE_SECRET_SIZE);
362 	memmove( &cookie_secrets->cookie_secrets[0], &cookie_secrets->cookie_secrets[1]
363 	       , sizeof(struct cookie_secret) * (UNBOUND_COOKIE_HISTORY_SIZE - 1));
364 	memcpy( cookie_secrets->cookie_secrets[cookie_secrets->cookie_count - 1].cookie_secret
365 	      , active_secret, UNBOUND_COOKIE_SECRET_SIZE);
366 	explicit_bzero(active_secret, UNBOUND_COOKIE_SECRET_SIZE);
367 }
368 
drop_cookie_secret(struct cookie_secrets * cookie_secrets)369 void drop_cookie_secret(struct cookie_secrets* cookie_secrets)
370 {
371 	if(!cookie_secrets)
372 		return;
373 	/* Drops a staging cookie secret. If there are more than one, it will
374 	 * drop the last staging secret. */
375 	if(cookie_secrets->cookie_count < 2)
376 		return;
377 	explicit_bzero( cookie_secrets->cookie_secrets[cookie_secrets->cookie_count - 1].cookie_secret
378 	              , UNBOUND_COOKIE_SECRET_SIZE);
379 	cookie_secrets->cookie_count -= 1;
380 }
381