xref: /freebsd/contrib/unbound/util/edns.c (revision be771a7b7f4580a30d99e41a5bb1b93a385a119d)
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 
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 
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
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 
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*
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 size_t
140 edns_strings_get_mem(struct edns_strings* edns_strings)
141 {
142 	if(!edns_strings) return 0;
143 	return regional_get_mem(edns_strings->region) + sizeof(*edns_strings);
144 }
145 
146 void
147 edns_strings_swap_tree(struct edns_strings* edns_strings,
148 	struct edns_strings* data)
149 {
150 	rbtree_type tree = edns_strings->client_strings;
151 	uint16_t opcode = edns_strings->client_string_opcode;
152 	struct regional* region = edns_strings->region;
153 
154 	edns_strings->client_strings = data->client_strings;
155 	edns_strings->client_string_opcode = data->client_string_opcode;
156 	edns_strings->region = data->region;
157 	data->client_strings = tree;
158 	data->client_string_opcode = opcode;
159 	data->region = region;
160 }
161 
162 uint8_t*
163 edns_cookie_server_hash(const uint8_t* in, const uint8_t* secret, int v4,
164 	uint8_t* hash)
165 {
166 	v4?siphash(in, 20, secret, hash, 8):siphash(in, 32, secret, hash, 8);
167 	return hash;
168 }
169 
170 void
171 edns_cookie_server_write(uint8_t* buf, const uint8_t* secret, int v4,
172 	uint32_t timestamp)
173 {
174 	uint8_t hash[8];
175 	buf[ 8] = 1;   /* Version */
176 	buf[ 9] = 0;   /* Reserved */
177 	buf[10] = 0;   /* Reserved */
178 	buf[11] = 0;   /* Reserved */
179 	sldns_write_uint32(buf + 12, timestamp);
180 	(void)edns_cookie_server_hash(buf, secret, v4, hash);
181 	memcpy(buf + 16, hash, 8);
182 }
183 
184 enum edns_cookie_val_status
185 edns_cookie_server_validate(const uint8_t* cookie, size_t cookie_len,
186 	const uint8_t* secret, size_t secret_len, int v4,
187 	const uint8_t* hash_input, uint32_t now)
188 {
189 	uint8_t hash[8];
190 	uint32_t timestamp;
191 	uint32_t subt_1982 = 0; /* Initialize for the compiler; unused value */
192 	int comp_1982;
193 	if(cookie_len != 24)
194 		/* RFC9018 cookies are 24 bytes long */
195 		return COOKIE_STATUS_CLIENT_ONLY;
196 	if(secret_len != 16 ||  /* RFC9018 cookies have 16 byte secrets */
197 		cookie[8] != 1) /* RFC9018 cookies are cookie version 1 */
198 		return COOKIE_STATUS_INVALID;
199 	timestamp = sldns_read_uint32(cookie + 12);
200 	if((comp_1982 = compare_1982(now, timestamp)) > 0
201 		&& (subt_1982 = subtract_1982(timestamp, now)) > 3600)
202 		/* Cookie is older than 1 hour (see RFC9018 Section 4.3.) */
203 		return COOKIE_STATUS_EXPIRED;
204 	if(comp_1982 <= 0 && subtract_1982(now, timestamp) > 300)
205 		/* Cookie time is more than 5 minutes in the future.
206 		 * (see RFC9018 Section 4.3.) */
207 		return COOKIE_STATUS_FUTURE;
208 	if(memcmp(edns_cookie_server_hash(hash_input, secret, v4, hash),
209 		cookie + 16, 8) != 0)
210 		/* Hashes do not match */
211 		return COOKIE_STATUS_INVALID;
212 	if(comp_1982 > 0 && subt_1982 > 1800)
213 		/* Valid cookie but older than 30 minutes, so create a new one
214 		 * anyway */
215 		return COOKIE_STATUS_VALID_RENEW;
216 	return COOKIE_STATUS_VALID;
217 }
218 
219 struct cookie_secrets*
220 cookie_secrets_create(void)
221 {
222 	struct cookie_secrets* cookie_secrets = calloc(1,
223 		sizeof(*cookie_secrets));
224 	if(!cookie_secrets)
225 		return NULL;
226 	lock_basic_init(&cookie_secrets->lock);
227 	lock_protect(&cookie_secrets->lock, &cookie_secrets->cookie_count,
228 		sizeof(cookie_secrets->cookie_count));
229 	lock_protect(&cookie_secrets->lock, cookie_secrets->cookie_secrets,
230 		sizeof(cookie_secret_type)*UNBOUND_COOKIE_HISTORY_SIZE);
231 	return cookie_secrets;
232 }
233 
234 void
235 cookie_secrets_delete(struct cookie_secrets* cookie_secrets)
236 {
237 	if(!cookie_secrets)
238 		return;
239 	lock_basic_destroy(&cookie_secrets->lock);
240 	explicit_bzero(cookie_secrets->cookie_secrets,
241 		sizeof(cookie_secret_type)*UNBOUND_COOKIE_HISTORY_SIZE);
242 	free(cookie_secrets);
243 }
244 
245 /** Read the cookie secret file */
246 static int
247 cookie_secret_file_read(struct cookie_secrets* cookie_secrets,
248 	char* cookie_secret_file)
249 {
250 	char secret[UNBOUND_COOKIE_SECRET_SIZE * 2 + 2/*'\n' and '\0'*/];
251 	FILE* f;
252 	int corrupt = 0;
253 	size_t count;
254 
255 	log_assert(cookie_secret_file != NULL);
256 	cookie_secrets->cookie_count = 0;
257 	f = fopen(cookie_secret_file, "r");
258 	/* a non-existing cookie file is not an error */
259 	if( f == NULL ) {
260 		if(errno != EPERM) {
261 			log_err("Could not read cookie-secret-file '%s': %s",
262 				cookie_secret_file, strerror(errno));
263 			return 0;
264 		}
265 		return 1;
266 	}
267 	/* cookie secret file exists and is readable */
268 	for( count = 0; count < UNBOUND_COOKIE_HISTORY_SIZE; count++ ) {
269 		size_t secret_len = 0;
270 		ssize_t decoded_len = 0;
271 		if( fgets(secret, sizeof(secret), f) == NULL ) { break; }
272 		secret_len = strlen(secret);
273 		if( secret_len == 0 ) { break; }
274 		log_assert( secret_len <= sizeof(secret) );
275 		secret_len = secret[secret_len - 1] == '\n' ? secret_len - 1 : secret_len;
276 		if( secret_len != UNBOUND_COOKIE_SECRET_SIZE * 2 ) { corrupt++; break; }
277 		/* needed for `hex_pton`; stripping potential `\n` */
278 		secret[secret_len] = '\0';
279 		decoded_len = hex_pton(secret, cookie_secrets->cookie_secrets[count].cookie_secret,
280 		                       UNBOUND_COOKIE_SECRET_SIZE);
281 		if( decoded_len != UNBOUND_COOKIE_SECRET_SIZE ) { corrupt++; break; }
282 		cookie_secrets->cookie_count++;
283 	}
284 	fclose(f);
285 	return corrupt == 0;
286 }
287 
288 int
289 cookie_secrets_apply_cfg(struct cookie_secrets* cookie_secrets,
290 	char* cookie_secret_file)
291 {
292 	if(!cookie_secrets) {
293 		if(!cookie_secret_file || !cookie_secret_file[0])
294 			return 1; /* There is nothing to read anyway */
295 		log_err("Could not read cookie secrets, no structure alloced");
296 		return 0;
297 	}
298 	if(!cookie_secret_file_read(cookie_secrets, cookie_secret_file))
299 		return 0;
300 	return 1;
301 }
302 
303 enum edns_cookie_val_status
304 cookie_secrets_server_validate(const uint8_t* cookie, size_t cookie_len,
305 	struct cookie_secrets* cookie_secrets, int v4,
306 	const uint8_t* hash_input, uint32_t now)
307 {
308 	size_t i;
309 	enum edns_cookie_val_status cookie_val_status,
310 		last = COOKIE_STATUS_INVALID;
311 	if(!cookie_secrets)
312 		return COOKIE_STATUS_INVALID; /* There are no cookie secrets.*/
313 	lock_basic_lock(&cookie_secrets->lock);
314 	if(cookie_secrets->cookie_count == 0) {
315 		lock_basic_unlock(&cookie_secrets->lock);
316 		return COOKIE_STATUS_INVALID; /* There are no cookie secrets.*/
317 	}
318 	for(i=0; i<cookie_secrets->cookie_count; i++) {
319 		cookie_val_status = edns_cookie_server_validate(cookie,
320 			cookie_len,
321 			cookie_secrets->cookie_secrets[i].cookie_secret,
322 			UNBOUND_COOKIE_SECRET_SIZE, v4, hash_input, now);
323 		if(cookie_val_status == COOKIE_STATUS_VALID ||
324 			cookie_val_status == COOKIE_STATUS_VALID_RENEW) {
325 			lock_basic_unlock(&cookie_secrets->lock);
326 			/* For staging cookies, write a fresh cookie. */
327 			if(i != 0)
328 				return COOKIE_STATUS_VALID_RENEW;
329 			return cookie_val_status;
330 		}
331 		if(last == COOKIE_STATUS_INVALID)
332 			last = cookie_val_status; /* Store more interesting
333 				failure to return. */
334 	}
335 	lock_basic_unlock(&cookie_secrets->lock);
336 	return last;
337 }
338 
339 void add_cookie_secret(struct cookie_secrets* cookie_secrets,
340 	uint8_t* secret, size_t secret_len)
341 {
342 	log_assert(secret_len == UNBOUND_COOKIE_SECRET_SIZE);
343 	(void)secret_len;
344 	if(!cookie_secrets)
345 		return;
346 
347 	/* New cookie secret becomes the staging secret (position 1)
348 	 * unless there is no active cookie yet, then it becomes the active
349 	 * secret.  If the UNBOUND_COOKIE_HISTORY_SIZE > 2 then all staging cookies
350 	 * are moved one position down.
351 	 */
352 	if(cookie_secrets->cookie_count == 0) {
353 		memcpy( cookie_secrets->cookie_secrets->cookie_secret
354 		       , secret, UNBOUND_COOKIE_SECRET_SIZE);
355 		cookie_secrets->cookie_count = 1;
356 		explicit_bzero(secret, UNBOUND_COOKIE_SECRET_SIZE);
357 		return;
358 	}
359 #if UNBOUND_COOKIE_HISTORY_SIZE > 2
360 	memmove( &cookie_secrets->cookie_secrets[2], &cookie_secrets->cookie_secrets[1]
361 	       , sizeof(struct cookie_secret) * (UNBOUND_COOKIE_HISTORY_SIZE - 2));
362 #endif
363 	memcpy( cookie_secrets->cookie_secrets[1].cookie_secret
364 	      , secret, UNBOUND_COOKIE_SECRET_SIZE);
365 	cookie_secrets->cookie_count = cookie_secrets->cookie_count     < UNBOUND_COOKIE_HISTORY_SIZE
366 	                  ? cookie_secrets->cookie_count + 1 : UNBOUND_COOKIE_HISTORY_SIZE;
367 	explicit_bzero(secret, UNBOUND_COOKIE_SECRET_SIZE);
368 }
369 
370 void activate_cookie_secret(struct cookie_secrets* cookie_secrets)
371 {
372 	uint8_t active_secret[UNBOUND_COOKIE_SECRET_SIZE];
373 	if(!cookie_secrets)
374 		return;
375 	/* The staging secret becomes the active secret.
376 	 * The active secret becomes a staging secret.
377 	 * If the UNBOUND_COOKIE_HISTORY_SIZE > 2 then all staging secrets are moved
378 	 * one position up and the previously active secret becomes the last
379 	 * staging secret.
380 	 */
381 	if(cookie_secrets->cookie_count < 2)
382 		return;
383 	memcpy( active_secret, cookie_secrets->cookie_secrets[0].cookie_secret
384 	      , UNBOUND_COOKIE_SECRET_SIZE);
385 	memmove( &cookie_secrets->cookie_secrets[0], &cookie_secrets->cookie_secrets[1]
386 	       , sizeof(struct cookie_secret) * (UNBOUND_COOKIE_HISTORY_SIZE - 1));
387 	memcpy( cookie_secrets->cookie_secrets[cookie_secrets->cookie_count - 1].cookie_secret
388 	      , active_secret, UNBOUND_COOKIE_SECRET_SIZE);
389 	explicit_bzero(active_secret, UNBOUND_COOKIE_SECRET_SIZE);
390 }
391 
392 void drop_cookie_secret(struct cookie_secrets* cookie_secrets)
393 {
394 	if(!cookie_secrets)
395 		return;
396 	/* Drops a staging cookie secret. If there are more than one, it will
397 	 * drop the last staging secret. */
398 	if(cookie_secrets->cookie_count < 2)
399 		return;
400 	explicit_bzero( cookie_secrets->cookie_secrets[cookie_secrets->cookie_count - 1].cookie_secret
401 	              , UNBOUND_COOKIE_SECRET_SIZE);
402 	cookie_secrets->cookie_count -= 1;
403 }
404