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