1 /*
2  * iterator/iter_scrub.c - scrubbing, normalization, sanitization of DNS msgs.
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 /**
37  * \file
38  *
39  * This file has routine(s) for cleaning up incoming DNS messages from
40  * possible useless or malicious junk in it.
41  */
42 #include "config.h"
43 #include "iterator/iter_scrub.h"
44 #include "iterator/iterator.h"
45 #include "iterator/iter_priv.h"
46 #include "services/cache/rrset.h"
47 #include "util/log.h"
48 #include "util/net_help.h"
49 #include "util/regional.h"
50 #include "util/config_file.h"
51 #include "util/module.h"
52 #include "util/data/msgparse.h"
53 #include "util/data/dname.h"
54 #include "util/data/msgreply.h"
55 #include "util/alloc.h"
56 #include "sldns/sbuffer.h"
57 
58 /** RRset flag used during scrubbing. The RRset is OK. */
59 #define RRSET_SCRUB_OK	0x80
60 
61 /** remove rrset, update loop variables */
62 static void
63 remove_rrset(const char* str, sldns_buffer* pkt, struct msg_parse* msg,
64 	struct rrset_parse* prev, struct rrset_parse** rrset)
65 {
66 	if(verbosity >= VERB_QUERY && str
67 		&& (*rrset)->dname_len <= LDNS_MAX_DOMAINLEN) {
68 		uint8_t buf[LDNS_MAX_DOMAINLEN+1];
69 		dname_pkt_copy(pkt, buf, (*rrset)->dname);
70 		log_nametypeclass(VERB_QUERY, str, buf,
71 			(*rrset)->type, ntohs((*rrset)->rrset_class));
72 	}
73 	if(prev)
74 		prev->rrset_all_next = (*rrset)->rrset_all_next;
75 	else	msg->rrset_first = (*rrset)->rrset_all_next;
76 	if(msg->rrset_last == *rrset)
77 		msg->rrset_last = prev;
78 	msg->rrset_count --;
79 	switch((*rrset)->section) {
80 		case LDNS_SECTION_ANSWER: msg->an_rrsets--; break;
81 		case LDNS_SECTION_AUTHORITY: msg->ns_rrsets--; break;
82 		case LDNS_SECTION_ADDITIONAL: msg->ar_rrsets--; break;
83 		default: log_assert(0);
84 	}
85 	msgparse_bucket_remove(msg, *rrset);
86 	*rrset = (*rrset)->rrset_all_next;
87 }
88 
89 /** return true if rr type has additional names in it */
90 static int
91 has_additional(uint16_t t)
92 {
93 	switch(t) {
94 		case LDNS_RR_TYPE_MB:
95 		case LDNS_RR_TYPE_MD:
96 		case LDNS_RR_TYPE_MF:
97 		case LDNS_RR_TYPE_NS:
98 		case LDNS_RR_TYPE_MX:
99 		case LDNS_RR_TYPE_KX:
100 		case LDNS_RR_TYPE_SRV:
101 			return 1;
102 		case LDNS_RR_TYPE_NAPTR:
103 			/* TODO: NAPTR not supported, glue stripped off */
104 			return 0;
105 	}
106 	return 0;
107 }
108 
109 /** get additional name from rrset RR, return false if no name present */
110 static int
111 get_additional_name(struct rrset_parse* rrset, struct rr_parse* rr,
112 	uint8_t** nm, size_t* nmlen, sldns_buffer* pkt)
113 {
114 	size_t offset = 0;
115 	size_t len, oldpos;
116 	switch(rrset->type) {
117 		case LDNS_RR_TYPE_MB:
118 		case LDNS_RR_TYPE_MD:
119 		case LDNS_RR_TYPE_MF:
120 		case LDNS_RR_TYPE_NS:
121 			offset = 0;
122 			break;
123 		case LDNS_RR_TYPE_MX:
124 		case LDNS_RR_TYPE_KX:
125 			offset = 2;
126 			break;
127 		case LDNS_RR_TYPE_SRV:
128 			offset = 6;
129 			break;
130 		case LDNS_RR_TYPE_NAPTR:
131 			/* TODO: NAPTR not supported, glue stripped off */
132 			return 0;
133 		default:
134 			return 0;
135 	}
136 	len = sldns_read_uint16(rr->ttl_data+sizeof(uint32_t));
137 	if(len < offset+1)
138 		return 0; /* rdata field too small */
139 	*nm = rr->ttl_data+sizeof(uint32_t)+sizeof(uint16_t)+offset;
140 	oldpos = sldns_buffer_position(pkt);
141 	sldns_buffer_set_position(pkt, (size_t)(*nm - sldns_buffer_begin(pkt)));
142 	*nmlen = pkt_dname_len(pkt);
143 	sldns_buffer_set_position(pkt, oldpos);
144 	if(*nmlen == 0)
145 		return 0;
146 	return 1;
147 }
148 
149 /** Place mark on rrsets in additional section they are OK */
150 static void
151 mark_additional_rrset(sldns_buffer* pkt, struct msg_parse* msg,
152 	struct rrset_parse* rrset)
153 {
154 	/* Mark A and AAAA for NS as appropriate additional section info. */
155 	uint8_t* nm = NULL;
156 	size_t nmlen = 0;
157 	struct rr_parse* rr;
158 
159 	if(!has_additional(rrset->type))
160 		return;
161 	for(rr = rrset->rr_first; rr; rr = rr->next) {
162 		if(get_additional_name(rrset, rr, &nm, &nmlen, pkt)) {
163 			/* mark A */
164 			hashvalue_type h = pkt_hash_rrset(pkt, nm,
165 				LDNS_RR_TYPE_A, rrset->rrset_class, 0);
166 			struct rrset_parse* r = msgparse_hashtable_lookup(
167 				msg, pkt, h, 0, nm, nmlen,
168 				LDNS_RR_TYPE_A, rrset->rrset_class);
169 			if(r && r->section == LDNS_SECTION_ADDITIONAL) {
170 				r->flags |= RRSET_SCRUB_OK;
171 			}
172 
173 			/* mark AAAA */
174 			h = pkt_hash_rrset(pkt, nm, LDNS_RR_TYPE_AAAA,
175 				rrset->rrset_class, 0);
176 			r = msgparse_hashtable_lookup(msg, pkt, h, 0, nm,
177 				nmlen, LDNS_RR_TYPE_AAAA, rrset->rrset_class);
178 			if(r && r->section == LDNS_SECTION_ADDITIONAL) {
179 				r->flags |= RRSET_SCRUB_OK;
180 			}
181 		}
182 	}
183 }
184 
185 /** Get target name of a CNAME */
186 static int
187 parse_get_cname_target(struct rrset_parse* rrset, uint8_t** sname,
188 	size_t* snamelen, sldns_buffer* pkt)
189 {
190 	size_t oldpos, dlen;
191 	if(rrset->rr_count != 1) {
192 		struct rr_parse* sig;
193 		verbose(VERB_ALGO, "Found CNAME rrset with "
194 			"size > 1: %u", (unsigned)rrset->rr_count);
195 		/* use the first CNAME! */
196 		rrset->rr_count = 1;
197 		rrset->size = rrset->rr_first->size;
198 		for(sig=rrset->rrsig_first; sig; sig=sig->next)
199 			rrset->size += sig->size;
200 		rrset->rr_last = rrset->rr_first;
201 		rrset->rr_first->next = NULL;
202 	}
203 	if(rrset->rr_first->size < sizeof(uint16_t)+1)
204 		return 0; /* CNAME rdata too small */
205 	*sname = rrset->rr_first->ttl_data + sizeof(uint32_t)
206 		+ sizeof(uint16_t); /* skip ttl, rdatalen */
207 	*snamelen = rrset->rr_first->size - sizeof(uint16_t);
208 
209 	if(rrset->rr_first->outside_packet) {
210 		if(!dname_valid(*sname, *snamelen))
211 			return 0;
212 		return 1;
213 	}
214 	oldpos = sldns_buffer_position(pkt);
215 	sldns_buffer_set_position(pkt, (size_t)(*sname - sldns_buffer_begin(pkt)));
216 	dlen = pkt_dname_len(pkt);
217 	sldns_buffer_set_position(pkt, oldpos);
218 	if(dlen == 0)
219 		return 0; /* parse fail on the rdata name */
220 	*snamelen = dlen;
221 	return 1;
222 }
223 
224 /** Synthesize CNAME from DNAME, false if too long */
225 static int
226 synth_cname(uint8_t* qname, size_t qnamelen, struct rrset_parse* dname_rrset,
227 	uint8_t* alias, size_t* aliaslen, sldns_buffer* pkt)
228 {
229 	/* we already know that sname is a strict subdomain of DNAME owner */
230 	uint8_t* dtarg = NULL;
231 	size_t dtarglen;
232 	if(!parse_get_cname_target(dname_rrset, &dtarg, &dtarglen, pkt))
233 		return 0;
234 	if(qnamelen <= dname_rrset->dname_len)
235 		return 0;
236 	if(qnamelen == 0)
237 		return 0;
238 	log_assert(qnamelen > dname_rrset->dname_len);
239 	/* DNAME from com. to net. with qname example.com. -> example.net. */
240 	/* so: \3com\0 to \3net\0 and qname \7example\3com\0 */
241 	*aliaslen = qnamelen + dtarglen - dname_rrset->dname_len;
242 	if(*aliaslen > LDNS_MAX_DOMAINLEN)
243 		return 0; /* should have been RCODE YXDOMAIN */
244 	/* decompress dnames into buffer, we know it fits */
245 	dname_pkt_copy(pkt, alias, qname);
246 	dname_pkt_copy(pkt, alias+(qnamelen-dname_rrset->dname_len), dtarg);
247 	return 1;
248 }
249 
250 /** synthesize a CNAME rrset */
251 static struct rrset_parse*
252 synth_cname_rrset(uint8_t** sname, size_t* snamelen, uint8_t* alias,
253 	size_t aliaslen, struct regional* region, struct msg_parse* msg,
254 	struct rrset_parse* rrset, struct rrset_parse* prev,
255 	struct rrset_parse* nx, sldns_buffer* pkt)
256 {
257 	struct rrset_parse* cn = (struct rrset_parse*)regional_alloc(region,
258 		sizeof(struct rrset_parse));
259 	if(!cn)
260 		return NULL;
261 	memset(cn, 0, sizeof(*cn));
262 	cn->rr_first = (struct rr_parse*)regional_alloc(region,
263 		sizeof(struct rr_parse));
264 	if(!cn->rr_first)
265 		return NULL;
266 	cn->rr_last = cn->rr_first;
267 	/* CNAME from sname to alias */
268 	cn->dname = (uint8_t*)regional_alloc(region, *snamelen);
269 	if(!cn->dname)
270 		return NULL;
271 	dname_pkt_copy(pkt, cn->dname, *sname);
272 	cn->dname_len = *snamelen;
273 	cn->type = LDNS_RR_TYPE_CNAME;
274 	cn->section = rrset->section;
275 	cn->rrset_class = rrset->rrset_class;
276 	cn->rr_count = 1;
277 	cn->size = sizeof(uint16_t) + aliaslen;
278 	cn->hash=pkt_hash_rrset(pkt, cn->dname, cn->type, cn->rrset_class, 0);
279 	/* allocate TTL + rdatalen + uncompressed dname */
280 	memset(cn->rr_first, 0, sizeof(struct rr_parse));
281 	cn->rr_first->outside_packet = 1;
282 	cn->rr_first->ttl_data = (uint8_t*)regional_alloc(region,
283 		sizeof(uint32_t)+sizeof(uint16_t)+aliaslen);
284 	if(!cn->rr_first->ttl_data)
285 		return NULL;
286 	sldns_write_uint32(cn->rr_first->ttl_data, 0); /* TTL = 0 */
287 	sldns_write_uint16(cn->rr_first->ttl_data+4, aliaslen);
288 	memmove(cn->rr_first->ttl_data+6, alias, aliaslen);
289 	cn->rr_first->size = sizeof(uint16_t)+aliaslen;
290 
291 	/* link it in */
292 	cn->rrset_all_next = nx;
293 	if(prev)
294 		prev->rrset_all_next = cn;
295 	else	msg->rrset_first = cn;
296 	if(nx == NULL)
297 		msg->rrset_last = cn;
298 	msg->rrset_count ++;
299 	msg->an_rrsets++;
300 	/* it is not inserted in the msg hashtable. */
301 
302 	*sname = cn->rr_first->ttl_data + sizeof(uint32_t)+sizeof(uint16_t);
303 	*snamelen = aliaslen;
304 	return cn;
305 }
306 
307 /** check if DNAME applies to a name */
308 static int
309 pkt_strict_sub(sldns_buffer* pkt, uint8_t* sname, uint8_t* dr)
310 {
311 	uint8_t buf1[LDNS_MAX_DOMAINLEN+1];
312 	uint8_t buf2[LDNS_MAX_DOMAINLEN+1];
313 	/* decompress names */
314 	dname_pkt_copy(pkt, buf1, sname);
315 	dname_pkt_copy(pkt, buf2, dr);
316 	return dname_strict_subdomain_c(buf1, buf2);
317 }
318 
319 /** check subdomain with decompression */
320 static int
321 pkt_sub(sldns_buffer* pkt, uint8_t* comprname, uint8_t* zone)
322 {
323 	uint8_t buf[LDNS_MAX_DOMAINLEN+1];
324 	dname_pkt_copy(pkt, buf, comprname);
325 	return dname_subdomain_c(buf, zone);
326 }
327 
328 /** check subdomain with decompression, compressed is parent */
329 static int
330 sub_of_pkt(sldns_buffer* pkt, uint8_t* zone, uint8_t* comprname)
331 {
332 	uint8_t buf[LDNS_MAX_DOMAINLEN+1];
333 	dname_pkt_copy(pkt, buf, comprname);
334 	return dname_subdomain_c(zone, buf);
335 }
336 
337 /** Check if there are SOA records in the authority section (negative) */
338 static int
339 soa_in_auth(struct msg_parse* msg)
340 {
341 	struct rrset_parse* rrset;
342 	for(rrset = msg->rrset_first; rrset; rrset = rrset->rrset_all_next)
343 		if(rrset->type == LDNS_RR_TYPE_SOA &&
344 			rrset->section == LDNS_SECTION_AUTHORITY)
345 			return 1;
346 	return 0;
347 }
348 
349 /** Check if type is allowed in the authority section */
350 static int
351 type_allowed_in_authority_section(uint16_t tp)
352 {
353 	if(tp == LDNS_RR_TYPE_SOA || tp == LDNS_RR_TYPE_NS ||
354 		tp == LDNS_RR_TYPE_DS || tp == LDNS_RR_TYPE_NSEC ||
355 		tp == LDNS_RR_TYPE_NSEC3)
356 		return 1;
357 	return 0;
358 }
359 
360 /** Check if type is allowed in the additional section */
361 static int
362 type_allowed_in_additional_section(uint16_t tp)
363 {
364 	if(tp == LDNS_RR_TYPE_A || tp == LDNS_RR_TYPE_AAAA)
365 		return 1;
366 	return 0;
367 }
368 
369 /**
370  * This routine normalizes a response. This includes removing "irrelevant"
371  * records from the answer and additional sections and (re)synthesizing
372  * CNAMEs from DNAMEs, if present.
373  *
374  * @param pkt: packet.
375  * @param msg: msg to normalize.
376  * @param qinfo: original query.
377  * @param region: where to allocate synthesized CNAMEs.
378  * @param env: module env with config options.
379  * @return 0 on error.
380  */
381 static int
382 scrub_normalize(sldns_buffer* pkt, struct msg_parse* msg,
383 	struct query_info* qinfo, struct regional* region,
384 	struct module_env* env)
385 {
386 	uint8_t* sname = qinfo->qname;
387 	size_t snamelen = qinfo->qname_len;
388 	struct rrset_parse* rrset, *prev, *nsset=NULL;
389 
390 	if(FLAGS_GET_RCODE(msg->flags) != LDNS_RCODE_NOERROR &&
391 		FLAGS_GET_RCODE(msg->flags) != LDNS_RCODE_NXDOMAIN)
392 		return 1;
393 
394 	/* For the ANSWER section, remove all "irrelevant" records and add
395 	 * synthesized CNAMEs from DNAMEs
396 	 * This will strip out-of-order CNAMEs as well. */
397 
398 	/* walk through the parse packet rrset list, keep track of previous
399 	 * for insert and delete ease, and examine every RRset */
400 	prev = NULL;
401 	rrset = msg->rrset_first;
402 	while(rrset && rrset->section == LDNS_SECTION_ANSWER) {
403 		if(rrset->type == LDNS_RR_TYPE_DNAME &&
404 			pkt_strict_sub(pkt, sname, rrset->dname)) {
405 			/* check if next rrset is correct CNAME. else,
406 			 * synthesize a CNAME */
407 			struct rrset_parse* nx = rrset->rrset_all_next;
408 			uint8_t alias[LDNS_MAX_DOMAINLEN+1];
409 			size_t aliaslen = 0;
410 			if(rrset->rr_count != 1) {
411 				verbose(VERB_ALGO, "Found DNAME rrset with "
412 					"size > 1: %u",
413 					(unsigned)rrset->rr_count);
414 				return 0;
415 			}
416 			if(!synth_cname(sname, snamelen, rrset, alias,
417 				&aliaslen, pkt)) {
418 				verbose(VERB_ALGO, "synthesized CNAME "
419 					"too long");
420 				return 0;
421 			}
422 			if(nx && nx->type == LDNS_RR_TYPE_CNAME &&
423 			   dname_pkt_compare(pkt, sname, nx->dname) == 0) {
424 				/* check next cname */
425 				uint8_t* t = NULL;
426 				size_t tlen = 0;
427 				if(!parse_get_cname_target(nx, &t, &tlen, pkt))
428 					return 0;
429 				if(dname_pkt_compare(pkt, alias, t) == 0) {
430 					/* it's OK and better capitalized */
431 					prev = rrset;
432 					rrset = nx;
433 					continue;
434 				}
435 				/* synth ourselves */
436 			}
437 			/* synth a CNAME rrset */
438 			prev = synth_cname_rrset(&sname, &snamelen, alias,
439 				aliaslen, region, msg, rrset, rrset, nx, pkt);
440 			if(!prev) {
441 				log_err("out of memory synthesizing CNAME");
442 				return 0;
443 			}
444 			/* FIXME: resolve the conflict between synthesized
445 			 * CNAME ttls and the cache. */
446 			rrset = nx;
447 			continue;
448 
449 		}
450 
451 		/* The only records in the ANSWER section not allowed to */
452 		if(dname_pkt_compare(pkt, sname, rrset->dname) != 0) {
453 			remove_rrset("normalize: removing irrelevant RRset:",
454 				pkt, msg, prev, &rrset);
455 			continue;
456 		}
457 
458 		/* Follow the CNAME chain. */
459 		if(rrset->type == LDNS_RR_TYPE_CNAME) {
460 			struct rrset_parse* nx = rrset->rrset_all_next;
461 			uint8_t* oldsname = sname;
462 			/* see if the next one is a DNAME, if so, swap them */
463 			if(nx && nx->section == LDNS_SECTION_ANSWER &&
464 				nx->type == LDNS_RR_TYPE_DNAME &&
465 				nx->rr_count == 1 &&
466 				pkt_strict_sub(pkt, sname, nx->dname)) {
467 				/* there is a DNAME after this CNAME, it
468 				 * is in the ANSWER section, and the DNAME
469 				 * applies to the name we cover */
470 				/* check if the alias of the DNAME equals
471 				 * this CNAME */
472 				uint8_t alias[LDNS_MAX_DOMAINLEN+1];
473 				size_t aliaslen = 0;
474 				uint8_t* t = NULL;
475 				size_t tlen = 0;
476 				if(synth_cname(sname, snamelen, nx, alias,
477 					&aliaslen, pkt) &&
478 					parse_get_cname_target(rrset, &t, &tlen, pkt) &&
479 			   		dname_pkt_compare(pkt, alias, t) == 0) {
480 					/* the synthesized CNAME equals the
481 					 * current CNAME.  This CNAME is the
482 					 * one that the DNAME creates, and this
483 					 * CNAME is better capitalised */
484 					verbose(VERB_ALGO, "normalize: re-order of DNAME and its CNAME");
485 					if(prev) prev->rrset_all_next = nx;
486 					else msg->rrset_first = nx;
487 					if(nx->rrset_all_next == NULL)
488 						msg->rrset_last = rrset;
489 					rrset->rrset_all_next =
490 						nx->rrset_all_next;
491 					nx->rrset_all_next = rrset;
492 					/* prev = nx; unused, enable if there
493 					 * is other rrset removal code after
494 					 * this */
495 				}
496 			}
497 
498 			/* move to next name in CNAME chain */
499 			if(!parse_get_cname_target(rrset, &sname, &snamelen, pkt))
500 				return 0;
501 			prev = rrset;
502 			rrset = rrset->rrset_all_next;
503 			/* in CNAME ANY response, can have data after CNAME */
504 			if(qinfo->qtype == LDNS_RR_TYPE_ANY) {
505 				while(rrset && rrset->section ==
506 					LDNS_SECTION_ANSWER &&
507 					dname_pkt_compare(pkt, oldsname,
508 					rrset->dname) == 0) {
509 					prev = rrset;
510 					rrset = rrset->rrset_all_next;
511 				}
512 			}
513 			continue;
514 		}
515 
516 		/* Otherwise, make sure that the RRset matches the qtype. */
517 		if(qinfo->qtype != LDNS_RR_TYPE_ANY &&
518 			qinfo->qtype != rrset->type) {
519 			remove_rrset("normalize: removing irrelevant RRset:",
520 				pkt, msg, prev, &rrset);
521 			continue;
522 		}
523 
524 		/* Mark the additional names from relevant rrset as OK. */
525 		/* only for RRsets that match the query name, other ones
526 		 * will be removed by sanitize, so no additional for them */
527 		if(dname_pkt_compare(pkt, qinfo->qname, rrset->dname) == 0)
528 			mark_additional_rrset(pkt, msg, rrset);
529 
530 		prev = rrset;
531 		rrset = rrset->rrset_all_next;
532 	}
533 
534 	/* Mark additional names from AUTHORITY */
535 	while(rrset && rrset->section == LDNS_SECTION_AUTHORITY) {
536 		/* protect internals of recursor by making sure to del these */
537 		if(rrset->type==LDNS_RR_TYPE_DNAME ||
538 			rrset->type==LDNS_RR_TYPE_CNAME ||
539 			rrset->type==LDNS_RR_TYPE_A ||
540 			rrset->type==LDNS_RR_TYPE_AAAA) {
541 			remove_rrset("normalize: removing irrelevant "
542 				"RRset:", pkt, msg, prev, &rrset);
543 			continue;
544 		}
545 		/* Allowed list of types in the authority section */
546 		if(env->cfg->harden_unknown_additional &&
547 			!type_allowed_in_authority_section(rrset->type)) {
548 			remove_rrset("normalize: removing irrelevant "
549 				"RRset:", pkt, msg, prev, &rrset);
550 			continue;
551 		}
552 		/* only one NS set allowed in authority section */
553 		if(rrset->type==LDNS_RR_TYPE_NS) {
554 			/* NS set must be pertinent to the query */
555 			if(!sub_of_pkt(pkt, qinfo->qname, rrset->dname)) {
556 				remove_rrset("normalize: removing irrelevant "
557 					"RRset:", pkt, msg, prev, &rrset);
558 				continue;
559 			}
560 			/* we don't want NS sets for NXDOMAIN answers,
561 			 * because they could contain poisonous contents,
562 			 * from. eg. fragmentation attacks, inserted after
563 			 * long RRSIGs in the packet get to the packet
564 			 * border and such */
565 			/* also for NODATA answers */
566 			if(FLAGS_GET_RCODE(msg->flags) == LDNS_RCODE_NXDOMAIN ||
567 			   (FLAGS_GET_RCODE(msg->flags) == LDNS_RCODE_NOERROR
568 			    && soa_in_auth(msg) && msg->an_rrsets == 0)) {
569 				remove_rrset("normalize: removing irrelevant "
570 					"RRset:", pkt, msg, prev, &rrset);
571 				continue;
572 			}
573 			if(nsset == NULL) {
574 				nsset = rrset;
575 			} else {
576 				remove_rrset("normalize: removing irrelevant "
577 					"RRset:", pkt, msg, prev, &rrset);
578 				continue;
579 			}
580 		}
581 		/* if this is type DS and we query for type DS we just got
582 		 * a referral answer for our type DS query, fix packet */
583 		if(rrset->type==LDNS_RR_TYPE_DS &&
584 			qinfo->qtype == LDNS_RR_TYPE_DS &&
585 			dname_pkt_compare(pkt, qinfo->qname, rrset->dname) == 0) {
586 			rrset->section = LDNS_SECTION_ANSWER;
587 			msg->ancount = rrset->rr_count + rrset->rrsig_count;
588 			msg->nscount = 0;
589 			msg->arcount = 0;
590 			msg->an_rrsets = 1;
591 			msg->ns_rrsets = 0;
592 			msg->ar_rrsets = 0;
593 			msg->rrset_count = 1;
594 			msg->rrset_first = rrset;
595 			msg->rrset_last = rrset;
596 			rrset->rrset_all_next = NULL;
597 			return 1;
598 		}
599 		mark_additional_rrset(pkt, msg, rrset);
600 		prev = rrset;
601 		rrset = rrset->rrset_all_next;
602 	}
603 
604 	/* For each record in the additional section, remove it if it is an
605 	 * address record and not in the collection of additional names
606 	 * found in ANSWER and AUTHORITY. */
607 	/* These records have not been marked OK previously */
608 	while(rrset && rrset->section == LDNS_SECTION_ADDITIONAL) {
609 		if(rrset->type==LDNS_RR_TYPE_A ||
610 			rrset->type==LDNS_RR_TYPE_AAAA)
611 		{
612 			if((rrset->flags & RRSET_SCRUB_OK)) {
613 				/* remove flag to clean up flags variable */
614 				rrset->flags &= ~RRSET_SCRUB_OK;
615 			} else {
616 				remove_rrset("normalize: removing irrelevant "
617 					"RRset:", pkt, msg, prev, &rrset);
618 				continue;
619 			}
620 		}
621 		/* protect internals of recursor by making sure to del these */
622 		if(rrset->type==LDNS_RR_TYPE_DNAME ||
623 			rrset->type==LDNS_RR_TYPE_CNAME ||
624 			rrset->type==LDNS_RR_TYPE_NS) {
625 			remove_rrset("normalize: removing irrelevant "
626 				"RRset:", pkt, msg, prev, &rrset);
627 			continue;
628 		}
629 		/* Allowed list of types in the additional section */
630 		if(env->cfg->harden_unknown_additional &&
631 			!type_allowed_in_additional_section(rrset->type)) {
632 			remove_rrset("normalize: removing irrelevant "
633 				"RRset:", pkt, msg, prev, &rrset);
634 			continue;
635 		}
636 		prev = rrset;
637 		rrset = rrset->rrset_all_next;
638 	}
639 
640 	return 1;
641 }
642 
643 /**
644  * Store potential poison in the cache (only if hardening disabled).
645  * The rrset is stored in the cache but removed from the message.
646  * So that it will be used for infrastructure purposes, but not be
647  * returned to the client.
648  * @param pkt: packet
649  * @param msg: message parsed
650  * @param env: environment with cache
651  * @param rrset: to store.
652  */
653 static void
654 store_rrset(sldns_buffer* pkt, struct msg_parse* msg, struct module_env* env,
655 	struct rrset_parse* rrset)
656 {
657 	struct ub_packed_rrset_key* k;
658 	struct packed_rrset_data* d;
659 	struct rrset_ref ref;
660 	time_t now = *env->now;
661 
662 	k = alloc_special_obtain(env->alloc);
663 	if(!k)
664 		return;
665 	k->entry.data = NULL;
666 	if(!parse_copy_decompress_rrset(pkt, msg, rrset, NULL, k)) {
667 		alloc_special_release(env->alloc, k);
668 		return;
669 	}
670 	d = (struct packed_rrset_data*)k->entry.data;
671 	packed_rrset_ttl_add(d, now);
672 	ref.key = k;
673 	ref.id = k->id;
674 	/*ignore ret: it was in the cache, ref updated */
675 	(void)rrset_cache_update(env->rrset_cache, &ref, env->alloc, now);
676 }
677 
678 /**
679  * Check if right hand name in NSEC is within zone
680  * @param pkt: the packet buffer for decompression.
681  * @param rrset: the NSEC rrset
682  * @param zonename: the zone name.
683  * @return true if BAD.
684  */
685 static int sanitize_nsec_is_overreach(sldns_buffer* pkt,
686 	struct rrset_parse* rrset, uint8_t* zonename)
687 {
688 	struct rr_parse* rr;
689 	uint8_t* rhs;
690 	size_t len;
691 	log_assert(rrset->type == LDNS_RR_TYPE_NSEC);
692 	for(rr = rrset->rr_first; rr; rr = rr->next) {
693 		size_t pos = sldns_buffer_position(pkt);
694 		size_t rhspos;
695 		rhs = rr->ttl_data+4+2;
696 		len = sldns_read_uint16(rr->ttl_data+4);
697 		rhspos = rhs-sldns_buffer_begin(pkt);
698 		sldns_buffer_set_position(pkt, rhspos);
699 		if(pkt_dname_len(pkt) == 0) {
700 			/* malformed */
701 			sldns_buffer_set_position(pkt, pos);
702 			return 1;
703 		}
704 		if(sldns_buffer_position(pkt)-rhspos > len) {
705 			/* outside of rdata boundaries */
706 			sldns_buffer_set_position(pkt, pos);
707 			return 1;
708 		}
709 		sldns_buffer_set_position(pkt, pos);
710 		if(!pkt_sub(pkt, rhs, zonename)) {
711 			/* overreaching */
712 			return 1;
713 		}
714 	}
715 	/* all NSEC RRs OK */
716 	return 0;
717 }
718 
719 /**
720  * Given a response event, remove suspect RRsets from the response.
721  * "Suspect" rrsets are potentially poison. Note that this routine expects
722  * the response to be in a "normalized" state -- that is, all "irrelevant"
723  * RRsets have already been removed, CNAMEs are in order, etc.
724  *
725  * @param pkt: packet.
726  * @param msg: msg to normalize.
727  * @param qinfo: the question originally asked.
728  * @param zonename: name of server zone.
729  * @param env: module environment with config and cache.
730  * @param ie: iterator environment with private address data.
731  * @return 0 on error.
732  */
733 static int
734 scrub_sanitize(sldns_buffer* pkt, struct msg_parse* msg,
735 	struct query_info* qinfo, uint8_t* zonename, struct module_env* env,
736 	struct iter_env* ie)
737 {
738 	int del_addi = 0; /* if additional-holding rrsets are deleted, we
739 		do not trust the normalized additional-A-AAAA any more */
740 	struct rrset_parse* rrset, *prev;
741 	prev = NULL;
742 	rrset = msg->rrset_first;
743 
744 	/* the first DNAME is allowed to stay. It needs checking before
745 	 * it can be used from the cache. After normalization, an initial
746 	 * DNAME will have a correctly synthesized CNAME after it. */
747 	if(rrset && rrset->type == LDNS_RR_TYPE_DNAME &&
748 		rrset->section == LDNS_SECTION_ANSWER &&
749 		pkt_strict_sub(pkt, qinfo->qname, rrset->dname) &&
750 		pkt_sub(pkt, rrset->dname, zonename)) {
751 		prev = rrset; /* DNAME allowed to stay in answer section */
752 		rrset = rrset->rrset_all_next;
753 	}
754 
755 	/* remove all records from the answer section that are
756 	 * not the same domain name as the query domain name.
757 	 * The answer section should contain rrsets with the same name
758 	 * as the question. For DNAMEs a CNAME has been synthesized.
759 	 * Wildcards have the query name in answer section.
760 	 * ANY queries get query name in answer section.
761 	 * Remainders of CNAME chains are cut off and resolved by iterator. */
762 	while(rrset && rrset->section == LDNS_SECTION_ANSWER) {
763 		if(dname_pkt_compare(pkt, qinfo->qname, rrset->dname) != 0) {
764 			if(has_additional(rrset->type)) del_addi = 1;
765 			remove_rrset("sanitize: removing extraneous answer "
766 				"RRset:", pkt, msg, prev, &rrset);
767 			continue;
768 		}
769 		prev = rrset;
770 		rrset = rrset->rrset_all_next;
771 	}
772 
773 	/* At this point, we brutally remove ALL rrsets that aren't
774 	 * children of the originating zone. The idea here is that,
775 	 * as far as we know, the server that we contacted is ONLY
776 	 * authoritative for the originating zone. It, of course, MAY
777 	 * be authoritative for any other zones, and of course, MAY
778 	 * NOT be authoritative for some subdomains of the originating
779 	 * zone. */
780 	prev = NULL;
781 	rrset = msg->rrset_first;
782 	while(rrset) {
783 
784 		/* remove private addresses */
785 		if( (rrset->type == LDNS_RR_TYPE_A ||
786 			rrset->type == LDNS_RR_TYPE_AAAA)) {
787 
788 			/* do not set servfail since this leads to too
789 			 * many drops of other people using rfc1918 space */
790 			/* also do not remove entire rrset, unless all records
791 			 * in it are bad */
792 			if(priv_rrset_bad(ie->priv, pkt, rrset)) {
793 				remove_rrset(NULL, pkt, msg, prev, &rrset);
794 				continue;
795 			}
796 		}
797 
798 		/* skip DNAME records -- they will always be followed by a
799 		 * synthesized CNAME, which will be relevant.
800 		 * FIXME: should this do something differently with DNAME
801 		 * rrsets NOT in Section.ANSWER? */
802 		/* But since DNAME records are also subdomains of the zone,
803 		 * same check can be used */
804 
805 		if(!pkt_sub(pkt, rrset->dname, zonename)) {
806 			if(msg->an_rrsets == 0 &&
807 				rrset->type == LDNS_RR_TYPE_NS &&
808 				rrset->section == LDNS_SECTION_AUTHORITY &&
809 				FLAGS_GET_RCODE(msg->flags) ==
810 				LDNS_RCODE_NOERROR && !soa_in_auth(msg) &&
811 				sub_of_pkt(pkt, zonename, rrset->dname)) {
812 				/* noerror, nodata and this NS rrset is above
813 				 * the zone. This is LAME!
814 				 * Leave in the NS for lame classification. */
815 				/* remove everything from the additional
816 				 * (we dont want its glue that was approved
817 				 * during the normalize action) */
818 				del_addi = 1;
819 			} else if(!env->cfg->harden_glue && (
820 				rrset->type == LDNS_RR_TYPE_A ||
821 				rrset->type == LDNS_RR_TYPE_AAAA)) {
822 				/* store in cache! Since it is relevant
823 				 * (from normalize) it will be picked up
824 				 * from the cache to be used later */
825 				store_rrset(pkt, msg, env, rrset);
826 				remove_rrset("sanitize: storing potential "
827 				"poison RRset:", pkt, msg, prev, &rrset);
828 				continue;
829 			} else {
830 				if(has_additional(rrset->type)) del_addi = 1;
831 				remove_rrset("sanitize: removing potential "
832 				"poison RRset:", pkt, msg, prev, &rrset);
833 				continue;
834 			}
835 		}
836 		if(del_addi && rrset->section == LDNS_SECTION_ADDITIONAL) {
837 			remove_rrset("sanitize: removing potential "
838 			"poison reference RRset:", pkt, msg, prev, &rrset);
839 			continue;
840 		}
841 		/* check if right hand side of NSEC is within zone */
842 		if(rrset->type == LDNS_RR_TYPE_NSEC &&
843 			sanitize_nsec_is_overreach(pkt, rrset, zonename)) {
844 			remove_rrset("sanitize: removing overreaching NSEC "
845 				"RRset:", pkt, msg, prev, &rrset);
846 			continue;
847 		}
848 		prev = rrset;
849 		rrset = rrset->rrset_all_next;
850 	}
851 	return 1;
852 }
853 
854 int
855 scrub_message(sldns_buffer* pkt, struct msg_parse* msg,
856 	struct query_info* qinfo, uint8_t* zonename, struct regional* region,
857 	struct module_env* env, struct iter_env* ie)
858 {
859 	/* basic sanity checks */
860 	log_nametypeclass(VERB_ALGO, "scrub for", zonename, LDNS_RR_TYPE_NS,
861 		qinfo->qclass);
862 	if(msg->qdcount > 1)
863 		return 0;
864 	if( !(msg->flags&BIT_QR) )
865 		return 0;
866 	msg->flags &= ~(BIT_AD|BIT_Z); /* force off bit AD and Z */
867 
868 	/* make sure that a query is echoed back when NOERROR or NXDOMAIN */
869 	/* this is not required for basic operation but is a forgery
870 	 * resistance (security) feature */
871 	if((FLAGS_GET_RCODE(msg->flags) == LDNS_RCODE_NOERROR ||
872 		FLAGS_GET_RCODE(msg->flags) == LDNS_RCODE_NXDOMAIN) &&
873 		msg->qdcount == 0)
874 		return 0;
875 
876 	/* if a query is echoed back, make sure it is correct. Otherwise,
877 	 * this may be not a reply to our query. */
878 	if(msg->qdcount == 1) {
879 		if(dname_pkt_compare(pkt, msg->qname, qinfo->qname) != 0)
880 			return 0;
881 		if(msg->qtype != qinfo->qtype || msg->qclass != qinfo->qclass)
882 			return 0;
883 	}
884 
885 	/* normalize the response, this cleans up the additional.  */
886 	if(!scrub_normalize(pkt, msg, qinfo, region, env))
887 		return 0;
888 	/* delete all out-of-zone information */
889 	if(!scrub_sanitize(pkt, msg, qinfo, zonename, env, ie))
890 		return 0;
891 	return 1;
892 }
893