xref: /freebsd/contrib/unbound/util/data/msgparse.c (revision 5685098846d7f11ad642d9804d94dc7429a7b212)
1 /*
2  * util/data/msgparse.c - parse wireformat DNS messages.
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  * Routines for message parsing a packet buffer to a descriptive structure.
38  */
39 #include "config.h"
40 #include "util/config_file.h"
41 #include "util/data/msgparse.h"
42 #include "util/data/msgreply.h"
43 #include "util/data/dname.h"
44 #include "util/data/packed_rrset.h"
45 #include "util/netevent.h"
46 #include "util/storage/lookup3.h"
47 #include "util/regional.h"
48 #include "util/rfc_1982.h"
49 #include "util/edns.h"
50 #include "util/net_help.h"
51 #include "sldns/rrdef.h"
52 #include "sldns/sbuffer.h"
53 #include "sldns/parseutil.h"
54 #include "sldns/wire2str.h"
55 
56 /** smart comparison of (compressed, valid) dnames from packet */
57 static int
smart_compare(sldns_buffer * pkt,uint8_t * dnow,uint8_t * dprfirst,uint8_t * dprlast)58 smart_compare(sldns_buffer* pkt, uint8_t* dnow,
59 	uint8_t* dprfirst, uint8_t* dprlast)
60 {
61 	if(LABEL_IS_PTR(*dnow)) {
62 		/* ptr points to a previous dname */
63 		uint8_t* p;
64 		if((size_t)PTR_OFFSET(dnow[0], dnow[1])
65 			>= sldns_buffer_limit(pkt))
66 			return -1;
67 		p = sldns_buffer_at(pkt, PTR_OFFSET(dnow[0], dnow[1]));
68 		if( p == dprfirst || p == dprlast )
69 			return 0;
70 		/* prev dname is also a ptr, both ptrs are the same. */
71 		if(LABEL_IS_PTR(*dprlast) &&
72 			dprlast[0] == dnow[0] && dprlast[1] == dnow[1])
73 			return 0;
74 	}
75 	return dname_pkt_compare(pkt, dnow, dprlast);
76 }
77 
78 /**
79  * Allocate new rrset in region, fill with data.
80  */
81 static struct rrset_parse*
new_rrset(struct msg_parse * msg,uint8_t * dname,size_t dnamelen,uint16_t type,uint16_t dclass,hashvalue_type hash,uint32_t rrset_flags,sldns_pkt_section section,struct regional * region)82 new_rrset(struct msg_parse* msg, uint8_t* dname, size_t dnamelen,
83 	uint16_t type, uint16_t dclass, hashvalue_type hash,
84 	uint32_t rrset_flags, sldns_pkt_section section,
85 	struct regional* region)
86 {
87 	struct rrset_parse* p = regional_alloc(region, sizeof(*p));
88 	if(!p) return NULL;
89 	p->rrset_bucket_next = msg->hashtable[hash & (PARSE_TABLE_SIZE-1)];
90 	msg->hashtable[hash & (PARSE_TABLE_SIZE-1)] = p;
91 	p->rrset_all_next = 0;
92 	if(msg->rrset_last)
93 		msg->rrset_last->rrset_all_next = p;
94 	else 	msg->rrset_first = p;
95 	msg->rrset_last = p;
96 	p->hash = hash;
97 	p->section = section;
98 	p->dname = dname;
99 	p->dname_len = dnamelen;
100 	p->type = type;
101 	p->rrset_class = dclass;
102 	p->flags = rrset_flags;
103 	p->rr_count = 0;
104 	p->size = 0;
105 	p->rr_first = 0;
106 	p->rr_last = 0;
107 	p->rrsig_count = 0;
108 	p->rrsig_first = 0;
109 	p->rrsig_last = 0;
110 	return p;
111 }
112 
113 /** See if next rrset is nsec at zone apex */
114 static int
nsec_at_apex(sldns_buffer * pkt)115 nsec_at_apex(sldns_buffer* pkt)
116 {
117 	/* we are at ttl position in packet. */
118 	size_t pos = sldns_buffer_position(pkt);
119 	uint16_t rdatalen;
120 	if(sldns_buffer_remaining(pkt) < 7) /* ttl+len+root */
121 		return 0; /* eek! */
122 	sldns_buffer_skip(pkt, 4); /* ttl */;
123 	rdatalen = sldns_buffer_read_u16(pkt);
124 	if(sldns_buffer_remaining(pkt) < rdatalen) {
125 		sldns_buffer_set_position(pkt, pos);
126 		return 0; /* parse error happens later */
127 	}
128 	/* must validate the nsec next domain name format */
129 	if(pkt_dname_len(pkt) == 0) {
130 		sldns_buffer_set_position(pkt, pos);
131 		return 0; /* parse error */
132 	}
133 
134 	/* see if SOA bit is set. */
135 	if(sldns_buffer_position(pkt) < pos+4+rdatalen) {
136 		/* nsec type bitmap contains items */
137 		uint8_t win, blen, bits;
138 		/* need: windownum, bitmap len, firstbyte */
139 		if(sldns_buffer_position(pkt)+3 > pos+4+rdatalen) {
140 			sldns_buffer_set_position(pkt, pos);
141 			return 0; /* malformed nsec */
142 		}
143 		win = sldns_buffer_read_u8(pkt);
144 		blen = sldns_buffer_read_u8(pkt);
145 		bits = sldns_buffer_read_u8(pkt);
146 		/* 0window always first window. bitlen >=1 or parse
147 		   error really. bit 0x2 is SOA. */
148 		if(win == 0 && blen >= 1 && (bits & 0x02)) {
149 			sldns_buffer_set_position(pkt, pos);
150 			return 1;
151 		}
152 	}
153 
154 	sldns_buffer_set_position(pkt, pos);
155 	return 0;
156 }
157 
158 /** Calculate rrset flags */
159 static uint32_t
pkt_rrset_flags(sldns_buffer * pkt,uint16_t type,sldns_pkt_section sec)160 pkt_rrset_flags(sldns_buffer* pkt, uint16_t type, sldns_pkt_section sec)
161 {
162 	uint32_t f = 0;
163 	if(type == LDNS_RR_TYPE_NSEC && nsec_at_apex(pkt)) {
164 		f |= PACKED_RRSET_NSEC_AT_APEX;
165 	} else if(type == LDNS_RR_TYPE_SOA && sec == LDNS_SECTION_AUTHORITY) {
166 		f |= PACKED_RRSET_SOA_NEG;
167 	}
168 	return f;
169 }
170 
171 hashvalue_type
pkt_hash_rrset(sldns_buffer * pkt,uint8_t * dname,uint16_t type,uint16_t dclass,uint32_t rrset_flags)172 pkt_hash_rrset(sldns_buffer* pkt, uint8_t* dname, uint16_t type,
173 	uint16_t dclass, uint32_t rrset_flags)
174 {
175 	/* note this MUST be identical to rrset_key_hash in packed_rrset.c */
176 	/* this routine handles compressed names */
177 	hashvalue_type h = 0xab;
178 	h = dname_pkt_hash(pkt, dname, h);
179 	h = hashlittle(&type, sizeof(type), h);		/* host order */
180 	h = hashlittle(&dclass, sizeof(dclass), h);	/* netw order */
181 	h = hashlittle(&rrset_flags, sizeof(uint32_t), h);
182 	return h;
183 }
184 
185 /** create partial dname hash for rrset hash */
186 static hashvalue_type
pkt_hash_rrset_first(sldns_buffer * pkt,uint8_t * dname)187 pkt_hash_rrset_first(sldns_buffer* pkt, uint8_t* dname)
188 {
189 	/* works together with pkt_hash_rrset_rest */
190 	/* note this MUST be identical to rrset_key_hash in packed_rrset.c */
191 	/* this routine handles compressed names */
192 	hashvalue_type h = 0xab;
193 	h = dname_pkt_hash(pkt, dname, h);
194 	return h;
195 }
196 
197 /** create a rrset hash from a partial dname hash */
198 static hashvalue_type
pkt_hash_rrset_rest(hashvalue_type dname_h,uint16_t type,uint16_t dclass,uint32_t rrset_flags)199 pkt_hash_rrset_rest(hashvalue_type dname_h, uint16_t type, uint16_t dclass,
200 	uint32_t rrset_flags)
201 {
202 	/* works together with pkt_hash_rrset_first */
203 	/* note this MUST be identical to rrset_key_hash in packed_rrset.c */
204 	hashvalue_type h;
205 	h = hashlittle(&type, sizeof(type), dname_h);	/* host order */
206 	h = hashlittle(&dclass, sizeof(dclass), h);	/* netw order */
207 	h = hashlittle(&rrset_flags, sizeof(uint32_t), h);
208 	return h;
209 }
210 
211 /** compare rrset_parse with data */
212 static int
rrset_parse_equals(struct rrset_parse * p,sldns_buffer * pkt,hashvalue_type h,uint32_t rrset_flags,uint8_t * dname,size_t dnamelen,uint16_t type,uint16_t dclass)213 rrset_parse_equals(struct rrset_parse* p, sldns_buffer* pkt, hashvalue_type h,
214 	uint32_t rrset_flags, uint8_t* dname, size_t dnamelen,
215 	uint16_t type, uint16_t dclass)
216 {
217 	if(p->hash == h && p->dname_len == dnamelen && p->type == type &&
218 		p->rrset_class == dclass && p->flags == rrset_flags &&
219 		dname_pkt_compare(pkt, dname, p->dname) == 0)
220 		return 1;
221 	return 0;
222 }
223 
224 
225 struct rrset_parse*
msgparse_hashtable_lookup(struct msg_parse * msg,sldns_buffer * pkt,hashvalue_type h,uint32_t rrset_flags,uint8_t * dname,size_t dnamelen,uint16_t type,uint16_t dclass)226 msgparse_hashtable_lookup(struct msg_parse* msg, sldns_buffer* pkt,
227 	hashvalue_type h, uint32_t rrset_flags, uint8_t* dname,
228 	size_t dnamelen, uint16_t type, uint16_t dclass)
229 {
230 	struct rrset_parse* p = msg->hashtable[h & (PARSE_TABLE_SIZE-1)];
231 	while(p) {
232 		if(rrset_parse_equals(p, pkt, h, rrset_flags, dname, dnamelen,
233 			type, dclass))
234 			return p;
235 		p = p->rrset_bucket_next;
236 	}
237 	return NULL;
238 }
239 
240 /** return type networkformat that rrsig in packet covers */
241 static int
pkt_rrsig_covered(sldns_buffer * pkt,uint8_t * here,uint16_t * type)242 pkt_rrsig_covered(sldns_buffer* pkt, uint8_t* here, uint16_t* type)
243 {
244 	size_t pos = sldns_buffer_position(pkt);
245 	sldns_buffer_set_position(pkt, (size_t)(here-sldns_buffer_begin(pkt)));
246 	/* ttl + len + size of small rrsig(rootlabel, no signature) */
247 	if(sldns_buffer_remaining(pkt) < 4+2+19)
248 		return 0;
249 	sldns_buffer_skip(pkt, 4); /* ttl */
250 	if(sldns_buffer_read_u16(pkt) < 19) /* too short */ {
251 		sldns_buffer_set_position(pkt, pos);
252 		return 0;
253 	}
254 	*type = sldns_buffer_read_u16(pkt);
255 	sldns_buffer_set_position(pkt, pos);
256 	return 1;
257 }
258 
259 /** true if covered type equals prevtype */
260 static int
pkt_rrsig_covered_equals(sldns_buffer * pkt,uint8_t * here,uint16_t type)261 pkt_rrsig_covered_equals(sldns_buffer* pkt, uint8_t* here, uint16_t type)
262 {
263 	uint16_t t;
264 	if(pkt_rrsig_covered(pkt, here, &t) && t == type)
265 		return 1;
266 	return 0;
267 }
268 
269 void
msgparse_bucket_remove(struct msg_parse * msg,struct rrset_parse * rrset)270 msgparse_bucket_remove(struct msg_parse* msg, struct rrset_parse* rrset)
271 {
272 	struct rrset_parse** p;
273 	p = &msg->hashtable[ rrset->hash & (PARSE_TABLE_SIZE-1) ];
274 	while(*p) {
275 		if(*p == rrset) {
276 			*p = rrset->rrset_bucket_next;
277 			return;
278 		}
279 		p = &( (*p)->rrset_bucket_next );
280 	}
281 }
282 
283 /** change section of rrset from previous to current section */
284 static void
change_section(struct msg_parse * msg,struct rrset_parse * rrset,sldns_pkt_section section)285 change_section(struct msg_parse* msg, struct rrset_parse* rrset,
286 	sldns_pkt_section section)
287 {
288 	struct rrset_parse *p, *prev;
289 	/* remove from list */
290 	if(section == rrset->section)
291 		return;
292 	p = msg->rrset_first;
293 	prev = 0;
294 	while(p) {
295 		if(p == rrset) {
296 			if(prev) prev->rrset_all_next = p->rrset_all_next;
297 			else	msg->rrset_first = p->rrset_all_next;
298 			if(msg->rrset_last == rrset)
299 				msg->rrset_last = prev;
300 			break;
301 		}
302 		prev = p;
303 		p = p->rrset_all_next;
304 	}
305 	/* remove from count */
306 	switch(rrset->section) {
307 		case LDNS_SECTION_ANSWER: msg->an_rrsets--; break;
308 		case LDNS_SECTION_AUTHORITY: msg->ns_rrsets--; break;
309 		case LDNS_SECTION_ADDITIONAL: msg->ar_rrsets--; break;
310 		default: log_assert(0);
311 	}
312 	/* insert at end of list */
313 	rrset->rrset_all_next = 0;
314 	if(msg->rrset_last)
315 		msg->rrset_last->rrset_all_next = rrset;
316 	else	msg->rrset_first = rrset;
317 	msg->rrset_last = rrset;
318 	/* up count of new section */
319 	switch(section) {
320 		case LDNS_SECTION_AUTHORITY: msg->ns_rrsets++; break;
321 		case LDNS_SECTION_ADDITIONAL: msg->ar_rrsets++; break;
322 		default: log_assert(0);
323 	}
324 	rrset->section = section;
325 }
326 
327 /** see if rrset of type RRSIG contains sig over given type */
328 static int
rrset_has_sigover(sldns_buffer * pkt,struct rrset_parse * rrset,uint16_t type,int * hasother)329 rrset_has_sigover(sldns_buffer* pkt, struct rrset_parse* rrset, uint16_t type,
330 	int* hasother)
331 {
332 	int res = 0;
333 	struct rr_parse* rr = rrset->rr_first;
334 	log_assert( rrset->type == LDNS_RR_TYPE_RRSIG );
335 	while(rr) {
336 		if(pkt_rrsig_covered_equals(pkt, rr->ttl_data, type))
337 			res = 1;
338 		else	*hasother = 1;
339 		rr = rr->next;
340 	}
341 	return res;
342 }
343 
344 /** move rrsigs from sigset to dataset */
345 static int
moveover_rrsigs(sldns_buffer * pkt,struct regional * region,struct rrset_parse * sigset,struct rrset_parse * dataset,int duplicate)346 moveover_rrsigs(sldns_buffer* pkt, struct regional* region,
347 	struct rrset_parse* sigset, struct rrset_parse* dataset, int duplicate)
348 {
349 	struct rr_parse* sig = sigset->rr_first;
350 	struct rr_parse* prev = NULL;
351 	struct rr_parse* insert;
352 	struct rr_parse* nextsig;
353 	while(sig) {
354 		nextsig = sig->next;
355 		if(pkt_rrsig_covered_equals(pkt, sig->ttl_data,
356 			dataset->type)) {
357 			if(duplicate) {
358 				/* new */
359 				insert = (struct rr_parse*)regional_alloc(
360 					region, sizeof(struct rr_parse));
361 				if(!insert) return 0;
362 				insert->outside_packet = 0;
363 				insert->ttl_data = sig->ttl_data;
364 				insert->size = sig->size;
365 				/* prev not used */
366 			} else {
367 				/* remove from sigset */
368 				if(prev) prev->next = sig->next;
369 				else	sigset->rr_first = sig->next;
370 				if(sigset->rr_last == sig)
371 					sigset->rr_last = prev;
372 				sigset->rr_count--;
373 				sigset->size -= sig->size;
374 				insert = sig;
375 				/* prev not changed */
376 			}
377 			/* add to dataset */
378 			dataset->rrsig_count++;
379 			insert->next = 0;
380 			if(dataset->rrsig_last)
381 				dataset->rrsig_last->next = insert;
382 			else	dataset->rrsig_first = insert;
383 			dataset->rrsig_last = insert;
384 			dataset->size += insert->size;
385 		} else  {
386 			prev = sig;
387 		}
388 		sig = nextsig;
389 	}
390 	return 1;
391 }
392 
393 /** change an rrsig rrset for use as data rrset */
394 static struct rrset_parse*
change_rrsig_rrset(struct rrset_parse * sigset,struct msg_parse * msg,sldns_buffer * pkt,uint16_t datatype,uint32_t rrset_flags,int hasother,sldns_pkt_section section,struct regional * region)395 change_rrsig_rrset(struct rrset_parse* sigset, struct msg_parse* msg,
396 	sldns_buffer* pkt, uint16_t datatype, uint32_t rrset_flags,
397 	int hasother, sldns_pkt_section section, struct regional* region)
398 {
399 	struct rrset_parse* dataset = sigset;
400 	hashvalue_type hash = pkt_hash_rrset(pkt, sigset->dname, datatype,
401 		sigset->rrset_class, rrset_flags);
402 	log_assert( sigset->type == LDNS_RR_TYPE_RRSIG );
403 	log_assert( datatype != LDNS_RR_TYPE_RRSIG );
404 	if(hasother) {
405 		/* need to make new rrset to hold data type */
406 		dataset = new_rrset(msg, sigset->dname, sigset->dname_len,
407 			datatype, sigset->rrset_class, hash, rrset_flags,
408 			section, region);
409 		if(!dataset)
410 			return NULL;
411 		switch(section) {
412 			case LDNS_SECTION_ANSWER: msg->an_rrsets++; break;
413 			case LDNS_SECTION_AUTHORITY: msg->ns_rrsets++; break;
414 			case LDNS_SECTION_ADDITIONAL: msg->ar_rrsets++; break;
415 			default: log_assert(0);
416 		}
417 		if(!moveover_rrsigs(pkt, region, sigset, dataset,
418 			msg->qtype == LDNS_RR_TYPE_RRSIG ||
419 			(msg->qtype == LDNS_RR_TYPE_ANY &&
420 			section != LDNS_SECTION_ANSWER) ))
421 			return NULL;
422 		return dataset;
423 	}
424 	/* changeover the type of the rrset to data set */
425 	msgparse_bucket_remove(msg, dataset);
426 	/* insert into new hash bucket */
427 	dataset->rrset_bucket_next = msg->hashtable[hash&(PARSE_TABLE_SIZE-1)];
428 	msg->hashtable[hash&(PARSE_TABLE_SIZE-1)] = dataset;
429 	dataset->hash = hash;
430 	/* use section of data item for result */
431 	change_section(msg, dataset, section);
432 	dataset->type = datatype;
433 	dataset->flags = rrset_flags;
434 	dataset->rrsig_count += dataset->rr_count;
435 	dataset->rr_count = 0;
436 	/* move sigs to end of siglist */
437 	if(dataset->rrsig_last)
438 		dataset->rrsig_last->next = dataset->rr_first;
439 	else	dataset->rrsig_first = dataset->rr_first;
440 	dataset->rrsig_last = dataset->rr_last;
441 	dataset->rr_first = 0;
442 	dataset->rr_last = 0;
443 	return dataset;
444 }
445 
446 /** Find rrset. If equal to previous it is fast. hash if not so.
447  * @param msg: the message with hash table.
448  * @param pkt: the packet in wireformat (needed for compression ptrs).
449  * @param dname: pointer to start of dname (compressed) in packet.
450  * @param dnamelen: uncompressed wirefmt length of dname.
451  * @param type: type of current rr.
452  * @param dclass: class of current rr.
453  * @param hash: hash value is returned if the rrset could not be found.
454  * @param rrset_flags: is returned if the rrset could not be found.
455  * @param prev_dname_first: dname of last seen RR. First seen dname.
456  * @param prev_dname_last: dname of last seen RR. Last seen dname.
457  * @param prev_dnamelen: dname len of last seen RR.
458  * @param prev_type: type of last seen RR.
459  * @param prev_dclass: class of last seen RR.
460  * @param rrset_prev: last seen RRset.
461  * @param section: the current section in the packet.
462  * @param region: used to allocate temporary parsing data.
463  * @return 0 on out of memory.
464  */
465 static int
find_rrset(struct msg_parse * msg,sldns_buffer * pkt,uint8_t * dname,size_t dnamelen,uint16_t type,uint16_t dclass,hashvalue_type * hash,uint32_t * rrset_flags,uint8_t ** prev_dname_first,uint8_t ** prev_dname_last,size_t * prev_dnamelen,uint16_t * prev_type,uint16_t * prev_dclass,struct rrset_parse ** rrset_prev,sldns_pkt_section section,struct regional * region)466 find_rrset(struct msg_parse* msg, sldns_buffer* pkt, uint8_t* dname,
467 	size_t dnamelen, uint16_t type, uint16_t dclass, hashvalue_type* hash,
468 	uint32_t* rrset_flags,
469 	uint8_t** prev_dname_first, uint8_t** prev_dname_last,
470 	size_t* prev_dnamelen, uint16_t* prev_type,
471 	uint16_t* prev_dclass, struct rrset_parse** rrset_prev,
472 	sldns_pkt_section section, struct regional* region)
473 {
474 	hashvalue_type dname_h = pkt_hash_rrset_first(pkt, dname);
475 	uint16_t covtype;
476 	if(*rrset_prev) {
477 		/* check if equal to previous item */
478 		if(type == *prev_type && dclass == *prev_dclass &&
479 			dnamelen == *prev_dnamelen &&
480 			smart_compare(pkt, dname, *prev_dname_first,
481 				*prev_dname_last) == 0 &&
482 			type != LDNS_RR_TYPE_RRSIG) {
483 			/* same as previous */
484 			*prev_dname_last = dname;
485 			return 1;
486 		}
487 		/* check if rrsig over previous item */
488 		if(type == LDNS_RR_TYPE_RRSIG && dclass == *prev_dclass &&
489 			pkt_rrsig_covered_equals(pkt, sldns_buffer_current(pkt),
490 				*prev_type) &&
491 			smart_compare(pkt, dname, *prev_dname_first,
492 				*prev_dname_last) == 0) {
493 			/* covers previous */
494 			*prev_dname_last = dname;
495 			return 1;
496 		}
497 	}
498 	/* find by hashing and lookup in hashtable */
499 	*rrset_flags = pkt_rrset_flags(pkt, type, section);
500 
501 	/* if rrsig - try to lookup matching data set first */
502 	if(type == LDNS_RR_TYPE_RRSIG && pkt_rrsig_covered(pkt,
503 		sldns_buffer_current(pkt), &covtype)) {
504 		*hash = pkt_hash_rrset_rest(dname_h, covtype, dclass,
505 			*rrset_flags);
506 		*rrset_prev = msgparse_hashtable_lookup(msg, pkt, *hash,
507 			*rrset_flags, dname, dnamelen, covtype, dclass);
508 		if(!*rrset_prev && covtype == LDNS_RR_TYPE_NSEC) {
509 			/* if NSEC try with NSEC apex bit twiddled */
510 			*rrset_flags ^= PACKED_RRSET_NSEC_AT_APEX;
511 			*hash = pkt_hash_rrset_rest(dname_h, covtype, dclass,
512 				*rrset_flags);
513 			*rrset_prev = msgparse_hashtable_lookup(msg, pkt,
514 				*hash, *rrset_flags, dname, dnamelen, covtype,
515 				dclass);
516 			if(!*rrset_prev) /* untwiddle if not found */
517 				*rrset_flags ^= PACKED_RRSET_NSEC_AT_APEX;
518 		}
519 		if(!*rrset_prev && covtype == LDNS_RR_TYPE_SOA) {
520 			/* if SOA try with SOA neg flag twiddled */
521 			*rrset_flags ^= PACKED_RRSET_SOA_NEG;
522 			*hash = pkt_hash_rrset_rest(dname_h, covtype, dclass,
523 				*rrset_flags);
524 			*rrset_prev = msgparse_hashtable_lookup(msg, pkt,
525 				*hash, *rrset_flags, dname, dnamelen, covtype,
526 				dclass);
527 			if(!*rrset_prev) /* untwiddle if not found */
528 				*rrset_flags ^= PACKED_RRSET_SOA_NEG;
529 		}
530 		if(*rrset_prev) {
531 			*prev_dname_first = (*rrset_prev)->dname;
532 			*prev_dname_last = dname;
533 			*prev_dnamelen = dnamelen;
534 			*prev_type = covtype;
535 			*prev_dclass = dclass;
536 			return 1;
537 		}
538 	}
539 	if(type != LDNS_RR_TYPE_RRSIG) {
540 		int hasother = 0;
541 		/* find matching rrsig */
542 		*hash = pkt_hash_rrset_rest(dname_h, LDNS_RR_TYPE_RRSIG,
543 			dclass, 0);
544 		*rrset_prev = msgparse_hashtable_lookup(msg, pkt, *hash,
545 			0, dname, dnamelen, LDNS_RR_TYPE_RRSIG,
546 			dclass);
547 		if(*rrset_prev && rrset_has_sigover(pkt, *rrset_prev, type,
548 			&hasother)) {
549 			/* yes! */
550 			*prev_dname_first = (*rrset_prev)->dname;
551 			*prev_dname_last = dname;
552 			*prev_dnamelen = dnamelen;
553 			*prev_type = type;
554 			*prev_dclass = dclass;
555 			*rrset_prev = change_rrsig_rrset(*rrset_prev, msg,
556 				pkt, type, *rrset_flags, hasother, section,
557 				region);
558 			if(!*rrset_prev) return 0;
559 			return 1;
560 		}
561 	}
562 
563 	*hash = pkt_hash_rrset_rest(dname_h, type, dclass, *rrset_flags);
564 	*rrset_prev = msgparse_hashtable_lookup(msg, pkt, *hash, *rrset_flags,
565 		dname, dnamelen, type, dclass);
566 	if(*rrset_prev)
567 		*prev_dname_first = (*rrset_prev)->dname;
568 	else 	*prev_dname_first = dname;
569 	*prev_dname_last = dname;
570 	*prev_dnamelen = dnamelen;
571 	*prev_type = type;
572 	*prev_dclass = dclass;
573 	return 1;
574 }
575 
576 /**
577  * Parse query section.
578  * @param pkt: packet, position at call must be at start of query section.
579  *	at end position is after query section.
580  * @param msg: store results here.
581  * @return: 0 if OK, or rcode on error.
582  */
583 static int
parse_query_section(sldns_buffer * pkt,struct msg_parse * msg)584 parse_query_section(sldns_buffer* pkt, struct msg_parse* msg)
585 {
586 	if(msg->qdcount == 0)
587 		return 0;
588 	if(msg->qdcount > 1)
589 		return LDNS_RCODE_FORMERR;
590 	log_assert(msg->qdcount == 1);
591 	if(sldns_buffer_remaining(pkt) <= 0)
592 		return LDNS_RCODE_FORMERR;
593 	msg->qname = sldns_buffer_current(pkt);
594 	if((msg->qname_len = pkt_dname_len(pkt)) == 0)
595 		return LDNS_RCODE_FORMERR;
596 	if(sldns_buffer_remaining(pkt) < sizeof(uint16_t)*2)
597 		return LDNS_RCODE_FORMERR;
598 	msg->qtype = sldns_buffer_read_u16(pkt);
599 	msg->qclass = sldns_buffer_read_u16(pkt);
600 	return 0;
601 }
602 
603 size_t
get_rdf_size(sldns_rdf_type rdf)604 get_rdf_size(sldns_rdf_type rdf)
605 {
606 	switch(rdf) {
607 		case LDNS_RDF_TYPE_CLASS:
608 		case LDNS_RDF_TYPE_ALG:
609 		case LDNS_RDF_TYPE_INT8:
610 			return 1;
611 			break;
612 		case LDNS_RDF_TYPE_INT16:
613 		case LDNS_RDF_TYPE_TYPE:
614 		case LDNS_RDF_TYPE_CERT_ALG:
615 			return 2;
616 			break;
617 		case LDNS_RDF_TYPE_INT32:
618 		case LDNS_RDF_TYPE_TIME:
619 		case LDNS_RDF_TYPE_A:
620 		case LDNS_RDF_TYPE_PERIOD:
621 			return 4;
622 			break;
623 		case LDNS_RDF_TYPE_TSIGTIME:
624 			return 6;
625 			break;
626 		case LDNS_RDF_TYPE_AAAA:
627 			return 16;
628 			break;
629 		default:
630 			log_assert(0); /* add type above */
631 			/* only types that appear before a domain  *
632 			 * name are needed. rest is simply copied. */
633 	}
634 	return 0;
635 }
636 
637 /** calculate the size of one rr */
638 static int
calc_size(sldns_buffer * pkt,uint16_t type,struct rr_parse * rr)639 calc_size(sldns_buffer* pkt, uint16_t type, struct rr_parse* rr)
640 {
641 	const sldns_rr_descriptor* desc;
642 	uint16_t pkt_len; /* length of rr inside the packet */
643 	rr->size = sizeof(uint16_t); /* the rdatalen */
644 	sldns_buffer_skip(pkt, 4); /* skip ttl */
645 	pkt_len = sldns_buffer_read_u16(pkt);
646 	if(sldns_buffer_remaining(pkt) < pkt_len)
647 		return 0;
648 	desc = sldns_rr_descript(type);
649 	if(pkt_len > 0 && desc && desc->_dname_count > 0) {
650 		int count = (int)desc->_dname_count;
651 		int rdf = 0;
652 		size_t len;
653 		size_t oldpos;
654 		/* skip first part. */
655 		while(pkt_len > 0 && count) {
656 			switch(desc->_wireformat[rdf]) {
657 			case LDNS_RDF_TYPE_DNAME:
658 				/* decompress every domain name */
659 				oldpos = sldns_buffer_position(pkt);
660 				if((len = pkt_dname_len(pkt)) == 0)
661 					return 0; /* malformed dname */
662 				if(sldns_buffer_position(pkt)-oldpos > pkt_len)
663 					return 0; /* dname exceeds rdata */
664 				pkt_len -= sldns_buffer_position(pkt)-oldpos;
665 				rr->size += len;
666 				count--;
667 				len = 0;
668 				break;
669 			case LDNS_RDF_TYPE_STR:
670 				if(pkt_len < 1) {
671 					/* NOTREACHED, due to 'while(>0)' */
672 					return 0; /* len byte exceeds rdata */
673 				}
674 				len = sldns_buffer_current(pkt)[0] + 1;
675 				break;
676 			default:
677 				len = get_rdf_size(desc->_wireformat[rdf]);
678 			}
679 			if(len) {
680 				if(pkt_len < len)
681 					return 0; /* exceeds rdata */
682 				pkt_len -= len;
683 				sldns_buffer_skip(pkt, (ssize_t)len);
684 				rr->size += len;
685 			}
686 			rdf++;
687 		}
688 	}
689 	/* remaining rdata */
690 	rr->size += pkt_len;
691 	sldns_buffer_skip(pkt, (ssize_t)pkt_len);
692 	return 1;
693 }
694 
695 /** skip rr ttl and rdata */
696 static int
skip_ttl_rdata(sldns_buffer * pkt)697 skip_ttl_rdata(sldns_buffer* pkt)
698 {
699 	uint16_t rdatalen;
700 	if(sldns_buffer_remaining(pkt) < 6) /* ttl + rdatalen */
701 		return 0;
702 	sldns_buffer_skip(pkt, 4); /* ttl */
703 	rdatalen = sldns_buffer_read_u16(pkt);
704 	if(sldns_buffer_remaining(pkt) < rdatalen)
705 		return 0;
706 	sldns_buffer_skip(pkt, (ssize_t)rdatalen);
707 	return 1;
708 }
709 
710 /** see if RRSIG is a duplicate of another */
711 static int
sig_is_double(sldns_buffer * pkt,struct rrset_parse * rrset,uint8_t * ttldata)712 sig_is_double(sldns_buffer* pkt, struct rrset_parse* rrset, uint8_t* ttldata)
713 {
714 	uint16_t rlen, siglen;
715 	size_t pos = sldns_buffer_position(pkt);
716 	struct rr_parse* sig;
717 	if(sldns_buffer_remaining(pkt) < 6)
718 		return 0;
719 	sldns_buffer_skip(pkt, 4); /* ttl */
720 	rlen = sldns_buffer_read_u16(pkt);
721 	if(sldns_buffer_remaining(pkt) < rlen) {
722 		sldns_buffer_set_position(pkt, pos);
723 		return 0;
724 	}
725 	sldns_buffer_set_position(pkt, pos);
726 
727 	sig = rrset->rrsig_first;
728 	while(sig) {
729 		/* check if rdatalen is same */
730 		memmove(&siglen, sig->ttl_data+4, sizeof(siglen));
731 		siglen = ntohs(siglen);
732 		/* checks if data in packet is exactly the same, this means
733 		 * also dname in rdata is the same, but rrsig is not allowed
734 		 * to have compressed dnames anyway. If it is compressed anyway
735 		 * it will lead to duplicate rrs for qtype=RRSIG. (or ANY).
736 		 *
737 		 * Cannot use sig->size because size of the other one is not
738 		 * calculated yet.
739 		 */
740 		if(siglen == rlen) {
741 			if(siglen>0 && memcmp(sig->ttl_data+6, ttldata+6,
742 				siglen) == 0) {
743 				/* same! */
744 				return 1;
745 			}
746 		}
747 		sig = sig->next;
748 	}
749 	return 0;
750 }
751 
752 /** Add rr (from packet here) to rrset, skips rr */
753 static int
add_rr_to_rrset(struct rrset_parse * rrset,sldns_buffer * pkt,struct msg_parse * msg,struct regional * region,sldns_pkt_section section,uint16_t type)754 add_rr_to_rrset(struct rrset_parse* rrset, sldns_buffer* pkt,
755 	struct msg_parse* msg, struct regional* region,
756 	sldns_pkt_section section, uint16_t type)
757 {
758 	struct rr_parse* rr;
759 	/* check section of rrset. */
760 	if(rrset->section != section && type != LDNS_RR_TYPE_RRSIG &&
761 		rrset->type != LDNS_RR_TYPE_RRSIG) {
762 		/* silently drop it - we drop the last part, since
763 		 * trust in rr data depends on the section it is in.
764 		 * the less trustworthy part is discarded.
765 		 * also the last part is more likely to be incomplete.
766 		 * RFC 2181: must put RRset only once in response. */
767 		/*
768 		verbose(VERB_QUERY, "Packet contains rrset data in "
769 			"multiple sections, dropped last part.");
770 		log_buf(VERB_QUERY, "packet was", pkt);
771 		*/
772 		/* forwards */
773 		if(!skip_ttl_rdata(pkt))
774 			return LDNS_RCODE_FORMERR;
775 		return 0;
776 	}
777 
778 	if( (msg->qtype == LDNS_RR_TYPE_RRSIG ||
779 	     msg->qtype == LDNS_RR_TYPE_ANY)
780 	    && sig_is_double(pkt, rrset, sldns_buffer_current(pkt))) {
781 		if(!skip_ttl_rdata(pkt))
782 			return LDNS_RCODE_FORMERR;
783 		return 0;
784 	}
785 
786 	/* create rr */
787 	if(!(rr = (struct rr_parse*)regional_alloc(region, sizeof(*rr))))
788 		return LDNS_RCODE_SERVFAIL;
789 	rr->outside_packet = 0;
790 	rr->ttl_data = sldns_buffer_current(pkt);
791 	rr->next = 0;
792 	if(type == LDNS_RR_TYPE_RRSIG && rrset->type != LDNS_RR_TYPE_RRSIG) {
793 		if(rrset->rrsig_last)
794 			rrset->rrsig_last->next = rr;
795 		else	rrset->rrsig_first = rr;
796 		rrset->rrsig_last = rr;
797 		rrset->rrsig_count++;
798 	} else {
799 		if(rrset->rr_last)
800 			rrset->rr_last->next = rr;
801 		else	rrset->rr_first = rr;
802 		rrset->rr_last = rr;
803 		rrset->rr_count++;
804 	}
805 
806 	/* calc decompressed size */
807 	if(!calc_size(pkt, type, rr))
808 		return LDNS_RCODE_FORMERR;
809 	rrset->size += rr->size;
810 
811 	return 0;
812 }
813 
814 /**
815  * Parse packet RR section, for answer, authority and additional sections.
816  * @param pkt: packet, position at call must be at start of section.
817  *	at end position is after section.
818  * @param msg: store results here.
819  * @param region: how to alloc results.
820  * @param section: section enum.
821  * @param num_rrs: how many rrs are in the section.
822  * @param num_rrsets: returns number of rrsets in the section.
823  * @return: 0 if OK, or rcode on error.
824  */
825 static int
parse_section(sldns_buffer * pkt,struct msg_parse * msg,struct regional * region,sldns_pkt_section section,uint16_t num_rrs,size_t * num_rrsets)826 parse_section(sldns_buffer* pkt, struct msg_parse* msg,
827 	struct regional* region, sldns_pkt_section section,
828 	uint16_t num_rrs, size_t* num_rrsets)
829 {
830 	uint16_t i;
831 	uint8_t* dname, *prev_dname_f = NULL, *prev_dname_l = NULL;
832 	size_t dnamelen, prev_dnamelen = 0;
833 	uint16_t type, prev_type = 0;
834 	uint16_t dclass, prev_dclass = 0;
835 	uint32_t rrset_flags = 0;
836 	hashvalue_type hash = 0;
837 	struct rrset_parse* rrset = NULL;
838 	int r;
839 
840 	if(num_rrs == 0)
841 		return 0;
842 	if(sldns_buffer_remaining(pkt) <= 0)
843 		return LDNS_RCODE_FORMERR;
844 	for(i=0; i<num_rrs; i++) {
845 		/* parse this RR. */
846 		dname = sldns_buffer_current(pkt);
847 		if((dnamelen = pkt_dname_len(pkt)) == 0)
848 			return LDNS_RCODE_FORMERR;
849 		if(sldns_buffer_remaining(pkt) < 10) /* type, class, ttl, len */
850 			return LDNS_RCODE_FORMERR;
851 		type = sldns_buffer_read_u16(pkt);
852 		sldns_buffer_read(pkt, &dclass, sizeof(dclass));
853 
854 		if(0) { /* debug show what is being parsed. */
855 			if(type == LDNS_RR_TYPE_RRSIG) {
856 				uint16_t t;
857 				if(pkt_rrsig_covered(pkt,
858 					sldns_buffer_current(pkt), &t))
859 					fprintf(stderr, "parse of %s(%d) [%s(%d)]",
860 					sldns_rr_descript(type)?
861 					sldns_rr_descript(type)->_name: "??",
862 					(int)type,
863 					sldns_rr_descript(t)?
864 					sldns_rr_descript(t)->_name: "??",
865 					(int)t);
866 			} else
867 			  fprintf(stderr, "parse of %s(%d)",
868 				sldns_rr_descript(type)?
869 				sldns_rr_descript(type)->_name: "??",
870 				(int)type);
871 			fprintf(stderr, " %s(%d) ",
872 				sldns_lookup_by_id(sldns_rr_classes,
873 				(int)ntohs(dclass))?sldns_lookup_by_id(
874 				sldns_rr_classes, (int)ntohs(dclass))->name:
875 				"??", (int)ntohs(dclass));
876 			dname_print(stderr, pkt, dname);
877 			fprintf(stderr, "\n");
878 		}
879 
880 		/* see if it is part of an existing RR set */
881 		if(!find_rrset(msg, pkt, dname, dnamelen, type, dclass, &hash,
882 			&rrset_flags, &prev_dname_f, &prev_dname_l,
883 			&prev_dnamelen, &prev_type, &prev_dclass, &rrset,
884 			section, region))
885 			return LDNS_RCODE_SERVFAIL;
886 		if(!rrset) {
887 			/* it is a new RR set. hash&flags already calculated.*/
888 			(*num_rrsets)++;
889 			rrset = new_rrset(msg, dname, dnamelen, type, dclass,
890 				hash, rrset_flags, section, region);
891 			if(!rrset)
892 				return LDNS_RCODE_SERVFAIL;
893 		}
894 		else if(0)	{
895 			fprintf(stderr, "is part of existing: ");
896 			dname_print(stderr, pkt, rrset->dname);
897 			fprintf(stderr, " type %s(%d)\n",
898 				sldns_rr_descript(rrset->type)?
899 				sldns_rr_descript(rrset->type)->_name: "??",
900 				(int)rrset->type);
901 		}
902 		/* add to rrset. */
903 		if((r=add_rr_to_rrset(rrset, pkt, msg, region, section,
904 			type)) != 0)
905 			return r;
906 	}
907 	return 0;
908 }
909 
910 int
parse_packet(sldns_buffer * pkt,struct msg_parse * msg,struct regional * region)911 parse_packet(sldns_buffer* pkt, struct msg_parse* msg, struct regional* region)
912 {
913 	int ret;
914 	if(sldns_buffer_remaining(pkt) < LDNS_HEADER_SIZE)
915 		return LDNS_RCODE_FORMERR;
916 	/* read the header */
917 	sldns_buffer_read(pkt, &msg->id, sizeof(uint16_t));
918 	msg->flags = sldns_buffer_read_u16(pkt);
919 	msg->qdcount = sldns_buffer_read_u16(pkt);
920 	msg->ancount = sldns_buffer_read_u16(pkt);
921 	msg->nscount = sldns_buffer_read_u16(pkt);
922 	msg->arcount = sldns_buffer_read_u16(pkt);
923 	if(msg->qdcount > 1)
924 		return LDNS_RCODE_FORMERR;
925 	if((ret = parse_query_section(pkt, msg)) != 0)
926 		return ret;
927 	if((ret = parse_section(pkt, msg, region, LDNS_SECTION_ANSWER,
928 		msg->ancount, &msg->an_rrsets)) != 0)
929 		return ret;
930 	if((ret = parse_section(pkt, msg, region, LDNS_SECTION_AUTHORITY,
931 		msg->nscount, &msg->ns_rrsets)) != 0)
932 		return ret;
933 	if(sldns_buffer_remaining(pkt) == 0 && msg->arcount == 1) {
934 		/* BIND accepts leniently that an EDNS record is missing.
935 		 * so, we do too. */
936 	} else if((ret = parse_section(pkt, msg, region,
937 		LDNS_SECTION_ADDITIONAL, msg->arcount, &msg->ar_rrsets)) != 0)
938 		return ret;
939 	/* if(sldns_buffer_remaining(pkt) > 0) { */
940 		/* there is spurious data at end of packet. ignore */
941 	/* } */
942 	msg->rrset_count = msg->an_rrsets + msg->ns_rrsets + msg->ar_rrsets;
943 	return 0;
944 }
945 
946 /** parse EDNS options from EDNS wireformat rdata */
947 static int
parse_edns_options_from_query(uint8_t * rdata_ptr,size_t rdata_len,struct edns_data * edns,struct config_file * cfg,struct comm_point * c,struct comm_reply * repinfo,uint32_t now,struct regional * region,struct cookie_secrets * cookie_secrets)948 parse_edns_options_from_query(uint8_t* rdata_ptr, size_t rdata_len,
949 	struct edns_data* edns, struct config_file* cfg, struct comm_point* c,
950 	struct comm_reply* repinfo, uint32_t now, struct regional* region,
951 	struct cookie_secrets* cookie_secrets)
952 {
953 	/* To respond with a Keepalive option, the client connection must have
954 	 * received one message with a TCP Keepalive EDNS option, and that
955 	 * option must have 0 length data. Subsequent messages sent on that
956 	 * connection will have a TCP Keepalive option.
957 	 *
958 	 * In the if-statement below, the option is added unsolicited. This
959 	 * means that the client has sent an KEEPALIVE option earlier. We know
960 	 * here this is true, because c->tcp_keepalive is set.
961 	 */
962 	if (cfg && cfg->do_tcp_keepalive && c && c->type != comm_udp && c->tcp_keepalive) {
963 		if(!edns_opt_list_append_keepalive(&edns->opt_list_out,
964 					c->tcp_timeout_msec / 100, region)) {
965 			log_err("out of memory");
966 			return LDNS_RCODE_SERVFAIL;
967 		}
968 	}
969 
970 	/* while still more options, and have code+len to read */
971 	/* ignores partial content (i.e. rdata len 3) */
972 	while(rdata_len >= 4) {
973 		uint16_t opt_code = sldns_read_uint16(rdata_ptr);
974 		uint16_t opt_len = sldns_read_uint16(rdata_ptr+2);
975 		uint8_t server_cookie[40];
976 		enum edns_cookie_val_status cookie_val_status;
977 		int cookie_is_v4 = 1;
978 
979 		rdata_ptr += 4;
980 		rdata_len -= 4;
981 		if(opt_len > rdata_len)
982 			break; /* option code partial */
983 
984 		/* handle parse time edns options here */
985 		switch(opt_code) {
986 		case LDNS_EDNS_NSID:
987 			if (!cfg || !cfg->nsid)
988 				break;
989 			if(!edns_opt_list_append(&edns->opt_list_out,
990 						LDNS_EDNS_NSID, cfg->nsid_len,
991 						cfg->nsid, region)) {
992 				log_err("out of memory");
993 				return LDNS_RCODE_SERVFAIL;
994 			}
995 			break;
996 
997 		case LDNS_EDNS_KEEPALIVE:
998 			/* To respond with a Keepalive option, the client
999 			 * connection must have received one message with a TCP
1000 			 * Keepalive EDNS option, and that option must have 0
1001 			 * length data. Subsequent messages sent on that
1002 			 * connection will have a TCP Keepalive option.
1003 			 *
1004 			 * This should be the first time the client sends this
1005 			 * option, so c->tcp_keepalive is not set.
1006 			 * Besides adding the reply KEEPALIVE option,
1007 			 * c->tcp_keepalive will be set so that the
1008 			 * option will be added unsolicited in subsequent
1009 			 * responses (see the comment above the if-statement
1010 			 * at the start of this function).
1011 			 */
1012 			if (!cfg || !cfg->do_tcp_keepalive || !c ||
1013 					c->type == comm_udp || c->tcp_keepalive)
1014 				break;
1015 			if(opt_len) {
1016 				verbose(VERB_ALGO, "query with bad edns keepalive.");
1017 				return LDNS_RCODE_FORMERR;
1018 			}
1019 			if(!edns_opt_list_append_keepalive(&edns->opt_list_out,
1020 						c->tcp_timeout_msec / 100,
1021 						region)) {
1022 				log_err("out of memory");
1023 				return LDNS_RCODE_SERVFAIL;
1024 			}
1025 			c->tcp_keepalive = 1;
1026 			break;
1027 
1028 		case LDNS_EDNS_PADDING:
1029 			if(!cfg || !cfg->pad_responses ||
1030 					!c || c->type != comm_tcp ||!c->ssl)
1031 				break;
1032 			if(!edns_opt_list_append(&edns->opt_list_out,
1033 						LDNS_EDNS_PADDING,
1034 						0, NULL, region)) {
1035 				log_err("out of memory");
1036 				return LDNS_RCODE_SERVFAIL;
1037 			}
1038 			edns->padding_block_size = cfg->pad_responses_block_size;
1039 			break;
1040 
1041 		case LDNS_EDNS_COOKIE:
1042 			if(!cfg || !cfg->do_answer_cookie || !repinfo)
1043 				break;
1044 			if(opt_len != 8 && (opt_len < 16 || opt_len > 40)) {
1045 				verbose(VERB_ALGO, "worker request: "
1046 					"badly formatted cookie");
1047 				return LDNS_RCODE_FORMERR;
1048 			}
1049 			edns->cookie_present = 1;
1050 
1051 			/* Copy client cookie, version and timestamp for
1052 			 * validation and creation purposes.
1053 			 */
1054 			if(opt_len >= 16) {
1055 				memmove(server_cookie, rdata_ptr, 16);
1056 			} else {
1057 				memset(server_cookie, 0, 16);
1058 				memmove(server_cookie, rdata_ptr, opt_len);
1059 			}
1060 
1061 			/* Copy client ip for validation and creation
1062 			 * purposes. It will be overwritten if (re)creation
1063 			 * is needed.
1064 			 */
1065 			if(repinfo->remote_addr.ss_family == AF_INET) {
1066 				memcpy(server_cookie + 16,
1067 					&((struct sockaddr_in*)&repinfo->remote_addr)->sin_addr, 4);
1068 			} else {
1069 				cookie_is_v4 = 0;
1070 				memcpy(server_cookie + 16,
1071 					&((struct sockaddr_in6*)&repinfo->remote_addr)->sin6_addr, 16);
1072 			}
1073 
1074 			if(cfg->cookie_secret_file &&
1075 				cfg->cookie_secret_file[0]) {
1076 				/* Loop over the active and staging cookies. */
1077 				cookie_val_status =
1078 					cookie_secrets_server_validate(
1079 					rdata_ptr, opt_len, cookie_secrets,
1080 					cookie_is_v4, server_cookie, now);
1081 			} else {
1082 				/* Use the cookie option value to validate. */
1083 				cookie_val_status = edns_cookie_server_validate(
1084 					rdata_ptr, opt_len, cfg->cookie_secret,
1085 					cfg->cookie_secret_len, cookie_is_v4,
1086 					server_cookie, now);
1087 			}
1088 			if(cookie_val_status == COOKIE_STATUS_VALID_RENEW)
1089 				edns->cookie_valid = 1;
1090 			switch(cookie_val_status) {
1091 			case COOKIE_STATUS_VALID:
1092 				edns->cookie_valid = 1;
1093 				/* Reuse cookie */
1094 				if(!edns_opt_list_append(
1095 					&edns->opt_list_out, LDNS_EDNS_COOKIE,
1096 					opt_len, rdata_ptr, region)) {
1097 					log_err("out of memory");
1098 					return LDNS_RCODE_SERVFAIL;
1099 				}
1100 				/* Cookie to be reused added to outgoing
1101 				 * options. Done!
1102 				 */
1103 				break;
1104 			case COOKIE_STATUS_CLIENT_ONLY:
1105 				edns->cookie_client = 1;
1106 				ATTR_FALLTHROUGH
1107 				/* fallthrough */
1108 			case COOKIE_STATUS_VALID_RENEW:
1109 			case COOKIE_STATUS_FUTURE:
1110 			case COOKIE_STATUS_EXPIRED:
1111 			case COOKIE_STATUS_INVALID:
1112 			default:
1113 				if(cfg->cookie_secret_file &&
1114 					cfg->cookie_secret_file[0]) {
1115 					if(!cookie_secrets)
1116 						break;
1117 					lock_basic_lock(&cookie_secrets->lock);
1118 					if(cookie_secrets->cookie_count < 1) {
1119 						lock_basic_unlock(&cookie_secrets->lock);
1120 						break;
1121 					}
1122 					edns_cookie_server_write(server_cookie,
1123 						cookie_secrets->cookie_secrets[0].cookie_secret,
1124 						cookie_is_v4, now);
1125 					lock_basic_unlock(&cookie_secrets->lock);
1126 				} else {
1127 					edns_cookie_server_write(server_cookie,
1128 						cfg->cookie_secret, cookie_is_v4, now);
1129 				}
1130 				if(!edns_opt_list_append(&edns->opt_list_out,
1131 					LDNS_EDNS_COOKIE, 24, server_cookie,
1132 					region)) {
1133 					log_err("out of memory");
1134 					return LDNS_RCODE_SERVFAIL;
1135 				}
1136 				break;
1137 			}
1138 			break;
1139 		default:
1140 			break;
1141 		}
1142 		if(!edns_opt_list_append(&edns->opt_list_in,
1143 				opt_code, opt_len, rdata_ptr, region)) {
1144 			log_err("out of memory");
1145 			return LDNS_RCODE_SERVFAIL;
1146 		}
1147 		rdata_ptr += opt_len;
1148 		rdata_len -= opt_len;
1149 	}
1150 	return LDNS_RCODE_NOERROR;
1151 }
1152 
1153 int
parse_extract_edns_from_response_msg(struct msg_parse * msg,struct edns_data * edns,struct regional * region)1154 parse_extract_edns_from_response_msg(struct msg_parse* msg,
1155 	struct edns_data* edns, struct regional* region)
1156 {
1157 	struct rrset_parse* rrset = msg->rrset_first;
1158 	struct rrset_parse* prev = 0;
1159 	struct rrset_parse* found = 0;
1160 	struct rrset_parse* found_prev = 0;
1161 	size_t rdata_len;
1162 	uint8_t* rdata_ptr;
1163 	/* since the class encodes the UDP size, we cannot use hash table to
1164 	 * find the EDNS OPT record. Scan the packet. */
1165 	while(rrset) {
1166 		if(rrset->type == LDNS_RR_TYPE_OPT) {
1167 			/* only one OPT RR allowed. */
1168 			if(found) return LDNS_RCODE_FORMERR;
1169 			/* found it! */
1170 			found_prev = prev;
1171 			found = rrset;
1172 		}
1173 		prev = rrset;
1174 		rrset = rrset->rrset_all_next;
1175 	}
1176 	if(!found) {
1177 		memset(edns, 0, sizeof(*edns));
1178 		edns->udp_size = 512;
1179 		return 0;
1180 	}
1181 	/* check the found RRset */
1182 	/* most lenient check possible. ignore dname, use last opt */
1183 	if(found->section != LDNS_SECTION_ADDITIONAL)
1184 		return LDNS_RCODE_FORMERR;
1185 	if(found->rr_count == 0)
1186 		return LDNS_RCODE_FORMERR;
1187 	if(0) { /* strict checking of dname and RRcount */
1188 		if(found->dname_len != 1 || !found->dname
1189 			|| found->dname[0] != 0) return LDNS_RCODE_FORMERR;
1190 		if(found->rr_count != 1) return LDNS_RCODE_FORMERR;
1191 	}
1192 	log_assert(found->rr_first && found->rr_last);
1193 
1194 	/* remove from packet */
1195 	if(found_prev)	found_prev->rrset_all_next = found->rrset_all_next;
1196 	else	msg->rrset_first = found->rrset_all_next;
1197 	if(found == msg->rrset_last)
1198 		msg->rrset_last = found_prev;
1199 	msg->arcount --;
1200 	msg->ar_rrsets --;
1201 	msg->rrset_count --;
1202 
1203 	/* take the data ! */
1204 	edns->edns_present = 1;
1205 	edns->ext_rcode = found->rr_last->ttl_data[0];
1206 	edns->edns_version = found->rr_last->ttl_data[1];
1207 	edns->bits = sldns_read_uint16(&found->rr_last->ttl_data[2]);
1208 	edns->udp_size = ntohs(found->rrset_class);
1209 	edns->opt_list_in = NULL;
1210 	edns->opt_list_out = NULL;
1211 	edns->opt_list_inplace_cb_out = NULL;
1212 	edns->padding_block_size = 0;
1213 	edns->cookie_present = 0;
1214 	edns->cookie_valid = 0;
1215 
1216 	/* take the options */
1217 	rdata_len = found->rr_first->size-2;
1218 	rdata_ptr = found->rr_first->ttl_data+6;
1219 
1220 	/* while still more options, and have code+len to read */
1221 	/* ignores partial content (i.e. rdata len 3) */
1222 	while(rdata_len >= 4) {
1223 		uint16_t opt_code = sldns_read_uint16(rdata_ptr);
1224 		uint16_t opt_len = sldns_read_uint16(rdata_ptr+2);
1225 		rdata_ptr += 4;
1226 		rdata_len -= 4;
1227 		if(opt_len > rdata_len)
1228 			break; /* option code partial */
1229 
1230 		if(!edns_opt_list_append(&edns->opt_list_in,
1231 				opt_code, opt_len, rdata_ptr, region)) {
1232 			log_err("out of memory");
1233 			break;
1234 		}
1235 		rdata_ptr += opt_len;
1236 		rdata_len -= opt_len;
1237 	}
1238 	/* ignore rrsigs */
1239 	return LDNS_RCODE_NOERROR;
1240 }
1241 
1242 /** skip RR in packet */
1243 static int
skip_pkt_rr(sldns_buffer * pkt)1244 skip_pkt_rr(sldns_buffer* pkt)
1245 {
1246 	if(sldns_buffer_remaining(pkt) < 1) return 0;
1247 	if(!pkt_dname_len(pkt))
1248 		return 0;
1249 	if(sldns_buffer_remaining(pkt) < 4) return 0;
1250 	sldns_buffer_skip(pkt, 4); /* type and class */
1251 	if(!skip_ttl_rdata(pkt))
1252 		return 0;
1253 	return 1;
1254 }
1255 
1256 /** skip RRs from packet */
1257 int
skip_pkt_rrs(sldns_buffer * pkt,int num)1258 skip_pkt_rrs(sldns_buffer* pkt, int num)
1259 {
1260 	int i;
1261 	for(i=0; i<num; i++) {
1262 		if(!skip_pkt_rr(pkt))
1263 			return 0;
1264 	}
1265 	return 1;
1266 }
1267 
1268 int
parse_edns_from_query_pkt(sldns_buffer * pkt,struct edns_data * edns,struct config_file * cfg,struct comm_point * c,struct comm_reply * repinfo,time_t now,struct regional * region,struct cookie_secrets * cookie_secrets)1269 parse_edns_from_query_pkt(sldns_buffer* pkt, struct edns_data* edns,
1270 	struct config_file* cfg, struct comm_point* c,
1271 	struct comm_reply* repinfo, time_t now, struct regional* region,
1272 	struct cookie_secrets* cookie_secrets)
1273 {
1274 	size_t rdata_len;
1275 	uint8_t* rdata_ptr;
1276 	log_assert(LDNS_QDCOUNT(sldns_buffer_begin(pkt)) == 1);
1277 	memset(edns, 0, sizeof(*edns));
1278 	if(LDNS_ANCOUNT(sldns_buffer_begin(pkt)) != 0 ||
1279 		LDNS_NSCOUNT(sldns_buffer_begin(pkt)) != 0) {
1280 		if(!skip_pkt_rrs(pkt, ((int)LDNS_ANCOUNT(sldns_buffer_begin(pkt)))+
1281 			((int)LDNS_NSCOUNT(sldns_buffer_begin(pkt)))))
1282 			return LDNS_RCODE_FORMERR;
1283 	}
1284 	/* check edns section is present */
1285 	if(LDNS_ARCOUNT(sldns_buffer_begin(pkt)) > 1) {
1286 		return LDNS_RCODE_FORMERR;
1287 	}
1288 	if(LDNS_ARCOUNT(sldns_buffer_begin(pkt)) == 0) {
1289 		edns->udp_size = 512;
1290 		return 0;
1291 	}
1292 	/* domain name must be the root of length 1. */
1293 	if(pkt_dname_len(pkt) != 1)
1294 		return LDNS_RCODE_FORMERR;
1295 	if(sldns_buffer_remaining(pkt) < 10) /* type, class, ttl, rdatalen */
1296 		return LDNS_RCODE_FORMERR;
1297 	if(sldns_buffer_read_u16(pkt) != LDNS_RR_TYPE_OPT)
1298 		return LDNS_RCODE_FORMERR;
1299 	edns->edns_present = 1;
1300 	edns->udp_size = sldns_buffer_read_u16(pkt); /* class is udp size */
1301 	edns->ext_rcode = sldns_buffer_read_u8(pkt); /* ttl used for bits */
1302 	edns->edns_version = sldns_buffer_read_u8(pkt);
1303 	edns->bits = sldns_buffer_read_u16(pkt);
1304 	edns->opt_list_in = NULL;
1305 	edns->opt_list_out = NULL;
1306 	edns->opt_list_inplace_cb_out = NULL;
1307 	edns->padding_block_size = 0;
1308 	edns->cookie_present = 0;
1309 	edns->cookie_valid = 0;
1310 
1311 	/* take the options */
1312 	rdata_len = sldns_buffer_read_u16(pkt);
1313 	if(sldns_buffer_remaining(pkt) < rdata_len)
1314 		return LDNS_RCODE_FORMERR;
1315 	rdata_ptr = sldns_buffer_current(pkt);
1316 	/* ignore rrsigs */
1317 	return parse_edns_options_from_query(rdata_ptr, rdata_len, edns, cfg,
1318 		c, repinfo, now, region, cookie_secrets);
1319 }
1320 
1321 void
log_edns_opt_list(enum verbosity_value level,const char * info_str,struct edns_option * list)1322 log_edns_opt_list(enum verbosity_value level, const char* info_str,
1323 	struct edns_option* list)
1324 {
1325 	if(verbosity >= level && list) {
1326 		char str[128], *s;
1327 		size_t slen;
1328 		verbose(level, "%s", info_str);
1329 		while(list) {
1330 			s = str;
1331 			slen = sizeof(str);
1332 			(void)sldns_wire2str_edns_option_print(&s, &slen, list->opt_code,
1333 				list->opt_data, list->opt_len);
1334 			verbose(level, "  %s", str);
1335 			list = list->next;
1336 		}
1337 	}
1338 }
1339 
1340 /** remove RR from msgparse RRset, return true if rrset is entirely bad */
1341 int
msgparse_rrset_remove_rr(const char * str,sldns_buffer * pkt,struct rrset_parse * rrset,struct rr_parse * prev,struct rr_parse * rr,struct sockaddr_storage * addr,socklen_t addrlen)1342 msgparse_rrset_remove_rr(const char* str, sldns_buffer* pkt, struct rrset_parse* rrset,
1343 	struct rr_parse* prev, struct rr_parse* rr, struct sockaddr_storage* addr, socklen_t addrlen)
1344 {
1345 	if(verbosity >= VERB_QUERY && rrset->dname_len <= LDNS_MAX_DOMAINLEN && str) {
1346 		uint8_t buf[LDNS_MAX_DOMAINLEN+1];
1347 		dname_pkt_copy(pkt, buf, rrset->dname);
1348 		if(addr)
1349 			log_name_addr(VERB_QUERY, str, buf, addr, addrlen);
1350 		else	log_nametypeclass(VERB_QUERY, str, buf,
1351 				rrset->type, ntohs(rrset->rrset_class));
1352 	}
1353 	if(prev)
1354 		prev->next = rr->next;
1355 	else	rrset->rr_first = rr->next;
1356 	if(rrset->rr_last == rr)
1357 		rrset->rr_last = prev;
1358 	rrset->rr_count --;
1359 	rrset->size -= rr->size;
1360 	/* rr struct still exists, but is unlinked, so that in the for loop
1361 	 * the rr->next works fine to continue. */
1362 	return rrset->rr_count == 0;
1363 }
1364