1 /*
2  * testpkts. Data file parse for test packets, and query matching.
3  *
4  * Data storage for specially crafted replies for testing purposes.
5  *
6  * (c) NLnet Labs, 2005, 2006, 2007, 2008
7  * See the file LICENSE for the license
8  */
9 
10 /**
11  * \file
12  * This is a debugging aid. It is not efficient, especially
13  * with a long config file, but it can give any reply to any query.
14  * This can help the developer pre-script replies for queries.
15  *
16  * You can specify a packet RR by RR with header flags to return.
17  *
18  * Missing features:
19  *		- matching content different from reply content.
20  *		- find way to adjust mangled packets?
21  */
22 
23 #include "config.h"
24 #include <errno.h>
25 #include <stdarg.h>
26 #include <ctype.h>
27 #include "testcode/testpkts.h"
28 #include "util/net_help.h"
29 #include "sldns/sbuffer.h"
30 #include "sldns/rrdef.h"
31 #include "sldns/pkthdr.h"
32 #include "sldns/str2wire.h"
33 #include "sldns/wire2str.h"
34 
35 /** max size of a packet */
36 #define MAX_PACKETLEN 65536
37 /** max line length */
38 #define MAX_LINE   10240
39 /** string to show in warnings and errors */
40 static const char* prog_name = "testpkts";
41 
42 #ifndef UTIL_LOG_H
43 /** verbosity definition for compat */
44 enum verbosity_value { NO_VERBOSE=0 };
45 #endif
46 /** logging routine, provided by caller */
47 void verbose(enum verbosity_value lvl, const char* msg, ...) ATTR_FORMAT(printf, 2, 3);
48 static void error(const char* msg, ...) ATTR_NORETURN;
49 
50 /** print error and exit */
error(const char * msg,...)51 static void error(const char* msg, ...)
52 {
53 	va_list args;
54 	va_start(args, msg);
55 	fprintf(stderr, "%s error: ", prog_name);
56 	vfprintf(stderr, msg, args);
57 	fprintf(stderr, "\n");
58 	fflush(stderr);
59 	va_end(args);
60 	exit(EXIT_FAILURE);
61 }
62 
63 /** return if string is empty or comment */
isendline(char c)64 static int isendline(char c)
65 {
66 	if(c == ';' || c == '#'
67 		|| c == '\n' || c == 0)
68 		return 1;
69 	return 0;
70 }
71 
72 /** true if the string starts with the keyword given. Moves the str ahead.
73  * @param str: before keyword, afterwards after keyword and spaces.
74  * @param keyword: the keyword to match
75  * @return: true if keyword present. False otherwise, and str unchanged.
76 */
str_keyword(char ** str,const char * keyword)77 static int str_keyword(char** str, const char* keyword)
78 {
79 	size_t len = strlen(keyword);
80 	assert(str && keyword);
81 	if(strncmp(*str, keyword, len) != 0)
82 		return 0;
83 	*str += len;
84 	while(isspace((unsigned char)**str))
85 		(*str)++;
86 	return 1;
87 }
88 
89 /** Add reply packet to entry */
90 static struct reply_packet*
entry_add_reply(struct entry * entry)91 entry_add_reply(struct entry* entry)
92 {
93 	struct reply_packet* pkt = (struct reply_packet*)malloc(
94 		sizeof(struct reply_packet));
95 	struct reply_packet ** p = &entry->reply_list;
96 	if(!pkt) error("out of memory");
97 	pkt->next = NULL;
98 	pkt->packet_sleep = 0;
99 	pkt->reply_pkt = NULL;
100 	pkt->reply_from_hex = NULL;
101 	pkt->raw_ednsdata = NULL;
102 	/* link at end */
103 	while(*p)
104 		p = &((*p)->next);
105 	*p = pkt;
106 	return pkt;
107 }
108 
109 /** parse MATCH line */
matchline(char * line,struct entry * e)110 static void matchline(char* line, struct entry* e)
111 {
112 	char* parse = line;
113 	while(*parse) {
114 		if(isendline(*parse))
115 			return;
116 		if(str_keyword(&parse, "opcode")) {
117 			e->match_opcode = 1;
118 		} else if(str_keyword(&parse, "qtype")) {
119 			e->match_qtype = 1;
120 		} else if(str_keyword(&parse, "qname")) {
121 			e->match_qname = 1;
122 		} else if(str_keyword(&parse, "rcode")) {
123 			e->match_rcode = 1;
124 		} else if(str_keyword(&parse, "question")) {
125 			e->match_question = 1;
126 		} else if(str_keyword(&parse, "answer")) {
127 			e->match_answer = 1;
128 		} else if(str_keyword(&parse, "subdomain")) {
129 			e->match_subdomain = 1;
130 		} else if(str_keyword(&parse, "all_noedns")) {
131 			e->match_all_noedns = 1;
132 		} else if(str_keyword(&parse, "all")) {
133 			e->match_all = 1;
134 		} else if(str_keyword(&parse, "ttl")) {
135 			e->match_ttl = 1;
136 		} else if(str_keyword(&parse, "DO")) {
137 			e->match_do = 1;
138 		} else if(str_keyword(&parse, "noedns")) {
139 			e->match_noedns = 1;
140 		} else if(str_keyword(&parse, "ednsdata")) {
141 			e->match_ednsdata_raw = 1;
142 		} else if(str_keyword(&parse, "client_cookie")) {
143 			e->match_client_cookie = 1;
144 		} else if(str_keyword(&parse, "server_cookie")) {
145 			e->match_server_cookie = 1;
146 		} else if(str_keyword(&parse, "UDP")) {
147 			e->match_transport = transport_udp;
148 		} else if(str_keyword(&parse, "TCP")) {
149 			e->match_transport = transport_tcp;
150 		} else if(str_keyword(&parse, "serial")) {
151 			e->match_serial = 1;
152 			if(*parse != '=' && *parse != ':')
153 				error("expected = or : in MATCH: %s", line);
154 			parse++;
155 			e->ixfr_soa_serial = (uint32_t)strtol(parse, (char**)&parse, 10);
156 			while(isspace((unsigned char)*parse))
157 				parse++;
158 		} else if(str_keyword(&parse, "ede")) {
159 			e->match_ede = 1;
160 			if(*parse != '=' && *parse != ':')
161 				error("expected = or : in MATCH: %s", line);
162 			parse++;
163 			while(isspace((unsigned char)*parse))
164 				parse++;
165 			if(str_keyword(&parse, "any")) {
166 				e->match_ede_any = 1;
167 			} else {
168 				e->ede_info_code = (uint16_t)strtol(parse,
169 					(char**)&parse, 10);
170 			}
171 			while(isspace((unsigned char)*parse))
172 				parse++;
173 		} else {
174 			error("could not parse MATCH: '%s'", parse);
175 		}
176 	}
177 }
178 
179 /** parse REPLY line */
replyline(char * line,uint8_t * reply,size_t reply_len,int * do_flag)180 static void replyline(char* line, uint8_t* reply, size_t reply_len,
181 	int* do_flag)
182 {
183 	char* parse = line;
184 	if(reply_len < LDNS_HEADER_SIZE) error("packet too short for header");
185 	while(*parse) {
186 		if(isendline(*parse))
187 			return;
188 			/* opcodes */
189 		if(str_keyword(&parse, "QUERY")) {
190 			LDNS_OPCODE_SET(reply, LDNS_PACKET_QUERY);
191 		} else if(str_keyword(&parse, "IQUERY")) {
192 			LDNS_OPCODE_SET(reply, LDNS_PACKET_IQUERY);
193 		} else if(str_keyword(&parse, "STATUS")) {
194 			LDNS_OPCODE_SET(reply, LDNS_PACKET_STATUS);
195 		} else if(str_keyword(&parse, "NOTIFY")) {
196 			LDNS_OPCODE_SET(reply, LDNS_PACKET_NOTIFY);
197 		} else if(str_keyword(&parse, "UPDATE")) {
198 			LDNS_OPCODE_SET(reply, LDNS_PACKET_UPDATE);
199 			/* rcodes */
200 		} else if(str_keyword(&parse, "NOERROR")) {
201 			LDNS_RCODE_SET(reply, LDNS_RCODE_NOERROR);
202 		} else if(str_keyword(&parse, "FORMERR")) {
203 			LDNS_RCODE_SET(reply, LDNS_RCODE_FORMERR);
204 		} else if(str_keyword(&parse, "SERVFAIL")) {
205 			LDNS_RCODE_SET(reply, LDNS_RCODE_SERVFAIL);
206 		} else if(str_keyword(&parse, "NXDOMAIN")) {
207 			LDNS_RCODE_SET(reply, LDNS_RCODE_NXDOMAIN);
208 		} else if(str_keyword(&parse, "NOTIMPL")) {
209 			LDNS_RCODE_SET(reply, LDNS_RCODE_NOTIMPL);
210 		} else if(str_keyword(&parse, "REFUSED")) {
211 			LDNS_RCODE_SET(reply, LDNS_RCODE_REFUSED);
212 		} else if(str_keyword(&parse, "YXDOMAIN")) {
213 			LDNS_RCODE_SET(reply, LDNS_RCODE_YXDOMAIN);
214 		} else if(str_keyword(&parse, "YXRRSET")) {
215 			LDNS_RCODE_SET(reply, LDNS_RCODE_YXRRSET);
216 		} else if(str_keyword(&parse, "NXRRSET")) {
217 			LDNS_RCODE_SET(reply, LDNS_RCODE_NXRRSET);
218 		} else if(str_keyword(&parse, "NOTAUTH")) {
219 			LDNS_RCODE_SET(reply, LDNS_RCODE_NOTAUTH);
220 		} else if(str_keyword(&parse, "NOTZONE")) {
221 			LDNS_RCODE_SET(reply, LDNS_RCODE_NOTZONE);
222 			/* flags */
223 		} else if(str_keyword(&parse, "QR")) {
224 			LDNS_QR_SET(reply);
225 		} else if(str_keyword(&parse, "AA")) {
226 			LDNS_AA_SET(reply);
227 		} else if(str_keyword(&parse, "TC")) {
228 			LDNS_TC_SET(reply);
229 		} else if(str_keyword(&parse, "RD")) {
230 			LDNS_RD_SET(reply);
231 		} else if(str_keyword(&parse, "CD")) {
232 			LDNS_CD_SET(reply);
233 		} else if(str_keyword(&parse, "RA")) {
234 			LDNS_RA_SET(reply);
235 		} else if(str_keyword(&parse, "AD")) {
236 			LDNS_AD_SET(reply);
237 		} else if(str_keyword(&parse, "DO")) {
238 			*do_flag = 1;
239 		} else {
240 			error("could not parse REPLY: '%s'", parse);
241 		}
242 	}
243 }
244 
245 /** parse ADJUST line */
adjustline(char * line,struct entry * e,struct reply_packet * pkt)246 static void adjustline(char* line, struct entry* e,
247 	struct reply_packet* pkt)
248 {
249 	char* parse = line;
250 	while(*parse) {
251 		if(isendline(*parse))
252 			return;
253 		if(str_keyword(&parse, "copy_id")) {
254 			e->copy_id = 1;
255 		} else if(str_keyword(&parse, "copy_query")) {
256 			e->copy_query = 1;
257 		} else if(str_keyword(&parse, "copy_ednsdata_assume_clientsubnet")) {
258 			e->copy_ednsdata_assume_clientsubnet = 1;
259 		} else if(str_keyword(&parse, "increment_ecs_scope")) {
260 			e->increment_ecs_scope = 1;
261 		} else if(str_keyword(&parse, "sleep=")) {
262 			e->sleeptime = (unsigned int) strtol(parse, (char**)&parse, 10);
263 			while(isspace((unsigned char)*parse))
264 				parse++;
265 		} else if(str_keyword(&parse, "packet_sleep=")) {
266 			pkt->packet_sleep = (unsigned int) strtol(parse, (char**)&parse, 10);
267 			while(isspace((unsigned char)*parse))
268 				parse++;
269 		} else {
270 			error("could not parse ADJUST: '%s'", parse);
271 		}
272 	}
273 }
274 
275 /** create new entry */
new_entry(void)276 static struct entry* new_entry(void)
277 {
278 	struct entry* e = (struct entry*)malloc(sizeof(struct entry));
279 	if(!e) error("out of memory");
280 	memset(e, 0, sizeof(*e));
281 	e->match_opcode = 0;
282 	e->match_qtype = 0;
283 	e->match_qname = 0;
284 	e->match_rcode = 0;
285 	e->match_question = 0;
286 	e->match_answer = 0;
287 	e->match_subdomain = 0;
288 	e->match_all = 0;
289 	e->match_all_noedns = 0;
290 	e->match_ttl = 0;
291 	e->match_do = 0;
292 	e->match_noedns = 0;
293 	e->match_serial = 0;
294 	e->ixfr_soa_serial = 0;
295 	e->match_ede = 0;
296 	e->match_ede_any = 0;
297 	e->ede_info_code = -1;
298 	e->match_transport = transport_any;
299 	e->reply_list = NULL;
300 	e->copy_id = 0;
301 	e->copy_query = 0;
302 	e->copy_ednsdata_assume_clientsubnet = 0;
303 	e->increment_ecs_scope = 0;
304 	e->sleeptime = 0;
305 	e->next = NULL;
306 	return e;
307 }
308 
309 /**
310  * Converts a hex string to binary data
311  * @param hexstr: string of hex.
312  * @param len: is the length of the string
313  * @param buf: is the buffer to store the result in
314  * @param offset: is the starting position in the result buffer
315  * @param buf_len: is the length of buf.
316  * @return This function returns the length of the result
317  */
318 static size_t
hexstr2bin(char * hexstr,int len,uint8_t * buf,size_t offset,size_t buf_len)319 hexstr2bin(char *hexstr, int len, uint8_t *buf, size_t offset, size_t buf_len)
320 {
321 	char c;
322 	int i;
323 	uint8_t int8 = 0;
324 	int sec = 0;
325 	size_t bufpos = 0;
326 
327 	if (len % 2 != 0) {
328 		return 0;
329 	}
330 
331 	for (i=0; i<len; i++) {
332 		c = hexstr[i];
333 
334 		/* case insensitive, skip spaces */
335 		if (c != ' ') {
336 			if (c >= '0' && c <= '9') {
337 				int8 += c & 0x0f;
338 			} else if (c >= 'a' && c <= 'z') {
339 				int8 += (c & 0x0f) + 9;
340 			} else if (c >= 'A' && c <= 'Z') {
341 				int8 += (c & 0x0f) + 9;
342 			} else {
343 				return 0;
344 			}
345 
346 			if (sec == 0) {
347 				int8 = int8 << 4;
348 				sec = 1;
349 			} else {
350 				if (bufpos + offset + 1 <= buf_len) {
351 					buf[bufpos+offset] = int8;
352 					int8 = 0;
353 					sec = 0;
354 					bufpos++;
355 				} else {
356 					fprintf(stderr, "Buffer too small in hexstr2bin");
357 				}
358 			}
359 		}
360         }
361         return bufpos;
362 }
363 
364 /** convert hex buffer to binary buffer */
365 static sldns_buffer *
hex_buffer2wire(sldns_buffer * data_buffer)366 hex_buffer2wire(sldns_buffer *data_buffer)
367 {
368 	sldns_buffer *wire_buffer = NULL;
369 	int c;
370 
371 	/* stat hack
372 	 * 0 = normal
373 	 * 1 = comment (skip to end of line)
374 	 * 2 = unprintable character found, read binary data directly
375 	 */
376 	size_t data_buf_pos = 0;
377 	int state = 0;
378 	uint8_t *hexbuf;
379 	int hexbufpos = 0;
380 	size_t wirelen;
381 	uint8_t *data_wire = (uint8_t *) sldns_buffer_begin(data_buffer);
382 	uint8_t *wire = (uint8_t*)malloc(MAX_PACKETLEN);
383 	if(!wire) error("out of memory");
384 
385 	hexbuf = (uint8_t*)malloc(MAX_PACKETLEN);
386 	if(!hexbuf) error("out of memory");
387 	for (data_buf_pos = 0; data_buf_pos < sldns_buffer_position(data_buffer); data_buf_pos++) {
388 		c = (int) data_wire[data_buf_pos];
389 
390 		if (state < 2 && !isascii((unsigned char)c)) {
391 			/*verbose("non ascii character found in file: (%d) switching to raw mode\n", c);*/
392 			state = 2;
393 		}
394 		switch (state) {
395 			case 0:
396 				if (	(c >= '0' && c <= '9') ||
397 					(c >= 'a' && c <= 'f') ||
398 					(c >= 'A' && c <= 'F') )
399 				{
400 					if (hexbufpos >= MAX_PACKETLEN) {
401 						error("buffer overflow");
402 						free(hexbuf);
403 						return 0;
404 
405 					}
406 					hexbuf[hexbufpos] = (uint8_t) c;
407 					hexbufpos++;
408 				} else if (c == ';') {
409 					state = 1;
410 				} else if (c == ' ' || c == '\t' || c == '\n') {
411 					/* skip whitespace */
412 				}
413 				break;
414 			case 1:
415 				if (c == '\n' || c == EOF) {
416 					state = 0;
417 				}
418 				break;
419 			case 2:
420 				if (hexbufpos >= MAX_PACKETLEN) {
421 					error("buffer overflow");
422 					free(hexbuf);
423 					return 0;
424 				}
425 				hexbuf[hexbufpos] = (uint8_t) c;
426 				hexbufpos++;
427 				break;
428 		}
429 	}
430 
431 	if (hexbufpos >= MAX_PACKETLEN) {
432 		/*verbose("packet size reached\n");*/
433 	}
434 
435 	/* lenient mode: length must be multiple of 2 */
436 	if (hexbufpos % 2 != 0) {
437 		if (hexbufpos >= MAX_PACKETLEN) {
438 			error("buffer overflow");
439 			free(hexbuf);
440 			return 0;
441 		}
442 		hexbuf[hexbufpos] = (uint8_t) '0';
443 		hexbufpos++;
444 	}
445 
446 	if (state < 2) {
447 		wirelen = hexstr2bin((char *) hexbuf, hexbufpos, wire, 0, MAX_PACKETLEN);
448 		wire_buffer = sldns_buffer_new(wirelen);
449 		sldns_buffer_new_frm_data(wire_buffer, wire, wirelen);
450 	} else {
451 		error("Incomplete hex data, not at byte boundary\n");
452 	}
453 	free(wire);
454 	free(hexbuf);
455 	return wire_buffer;
456 }
457 
458 /** parse ORIGIN */
459 static void
get_origin(const char * name,struct sldns_file_parse_state * pstate,char * parse)460 get_origin(const char* name, struct sldns_file_parse_state* pstate, char* parse)
461 {
462 	/* snip off rest of the text so as to make the parse work in ldns */
463 	char* end;
464 	char store;
465 	int status;
466 
467 	end=parse;
468 	while(!isspace((unsigned char)*end) && !isendline(*end))
469 		end++;
470 	store = *end;
471 	*end = 0;
472 	verbose(3, "parsing '%s'\n", parse);
473 	pstate->origin_len = sizeof(pstate->origin);
474 	status = sldns_str2wire_dname_buf(parse, pstate->origin,
475 		&pstate->origin_len);
476 	*end = store;
477 	if(status != 0)
478 		error("%s line %d:\n\t%s: %s", name, pstate->lineno,
479 			sldns_get_errorstr_parse(status), parse);
480 }
481 
482 /** add RR to packet */
add_rr(char * rrstr,uint8_t * pktbuf,size_t pktsize,size_t * pktlen,struct sldns_file_parse_state * pstate,sldns_pkt_section add_section,const char * fname)483 static void add_rr(char* rrstr, uint8_t* pktbuf, size_t pktsize,
484 	size_t* pktlen, struct sldns_file_parse_state* pstate,
485 	sldns_pkt_section add_section, const char* fname)
486 {
487 	/* it must be a RR, parse and add to packet. */
488 	size_t rr_len = pktsize - *pktlen;
489 	size_t dname_len = 0;
490 	int status;
491 	uint8_t* origin = pstate->origin_len?pstate->origin:0;
492 	uint8_t* prev = pstate->prev_rr_len?pstate->prev_rr:0;
493 	if(*pktlen > pktsize || *pktlen < LDNS_HEADER_SIZE)
494 		error("packet overflow");
495 
496 	/* parse RR */
497 	if(add_section == LDNS_SECTION_QUESTION)
498 		status = sldns_str2wire_rr_question_buf(rrstr, pktbuf+*pktlen,
499 			&rr_len, &dname_len, origin, pstate->origin_len,
500 			prev, pstate->prev_rr_len);
501 	else status = sldns_str2wire_rr_buf(rrstr, pktbuf+*pktlen, &rr_len,
502 			&dname_len, pstate->default_ttl, origin,
503 			pstate->origin_len, prev, pstate->prev_rr_len);
504 	if(status != 0)
505 		error("%s line %d:%d %s\n\t%s", fname, pstate->lineno,
506 			LDNS_WIREPARSE_OFFSET(status),
507 			sldns_get_errorstr_parse(status), rrstr);
508 	*pktlen += rr_len;
509 
510 	/* increase RR count */
511 	if(add_section == LDNS_SECTION_QUESTION)
512 		sldns_write_uint16(pktbuf+4, LDNS_QDCOUNT(pktbuf)+1);
513 	else if(add_section == LDNS_SECTION_ANSWER)
514 		sldns_write_uint16(pktbuf+6, LDNS_ANCOUNT(pktbuf)+1);
515 	else if(add_section == LDNS_SECTION_AUTHORITY)
516 		sldns_write_uint16(pktbuf+8, LDNS_NSCOUNT(pktbuf)+1);
517 	else if(add_section == LDNS_SECTION_ADDITIONAL)
518 		sldns_write_uint16(pktbuf+10, LDNS_ARCOUNT(pktbuf)+1);
519 	else error("internal error bad section %d", (int)add_section);
520 }
521 
522 /* add EDNS 4096 opt record */
523 static void
add_edns(uint8_t * pktbuf,size_t pktsize,int do_flag,uint8_t * ednsdata,uint16_t ednslen,size_t * pktlen)524 add_edns(uint8_t* pktbuf, size_t pktsize, int do_flag, uint8_t *ednsdata,
525 	uint16_t ednslen, size_t* pktlen)
526 {
527 	uint8_t edns[] = {0x00, /* root label */
528 		0x00, LDNS_RR_TYPE_OPT, /* type */
529 		0x04, 0xD0, /* class is UDPSIZE 1232 */
530 		0x00, /* TTL[0] is ext rcode */
531 		0x00, /* TTL[1] is edns version */
532 		(uint8_t)(do_flag?0x80:0x00), 0x00, /* TTL[2-3] is edns flags, DO */
533 		(uint8_t)((ednslen >> 8) & 0xff),
534 		(uint8_t)(ednslen  & 0xff), /* rdatalength */
535 	};
536 	if(*pktlen < LDNS_HEADER_SIZE)
537 		return;
538 	if(*pktlen + sizeof(edns) + ednslen > pktsize)
539 		error("not enough space for EDNS OPT record");
540 	memmove(pktbuf+*pktlen, edns, sizeof(edns));
541 	if(ednsdata && ednslen)
542 		memmove(pktbuf+*pktlen+sizeof(edns), ednsdata, ednslen);
543 	sldns_write_uint16(pktbuf+10, LDNS_ARCOUNT(pktbuf)+1);
544 	*pktlen += (sizeof(edns) + ednslen);
545 }
546 
547 /* Reads one entry from file. Returns entry or NULL on error. */
548 struct entry*
read_entry(FILE * in,const char * name,struct sldns_file_parse_state * pstate,int skip_whitespace)549 read_entry(FILE* in, const char* name, struct sldns_file_parse_state* pstate,
550 	int skip_whitespace)
551 {
552 	struct entry* current = NULL;
553 	char line[MAX_LINE];
554 	char* parse;
555 	sldns_pkt_section add_section = LDNS_SECTION_QUESTION;
556 	struct reply_packet *cur_reply = NULL;
557 	int reading_hex = 0;
558 	int reading_hex_ednsdata = 0;
559 	sldns_buffer* hex_data_buffer = NULL;
560 	sldns_buffer* hex_ednsdata_buffer = NULL;
561 	uint8_t pktbuf[MAX_PACKETLEN];
562 	size_t pktlen = LDNS_HEADER_SIZE;
563 	int do_flag = 0; /* DO flag in EDNS */
564 	memset(pktbuf, 0, pktlen); /* ID = 0, FLAGS="", and rr counts 0 */
565 
566 	while(fgets(line, (int)sizeof(line), in) != NULL) {
567 		line[MAX_LINE-1] = 0;
568 		parse = line;
569 		pstate->lineno++;
570 
571 		while(isspace((unsigned char)*parse))
572 			parse++;
573 		/* test for keywords */
574 		if(isendline(*parse))
575 			continue; /* skip comment and empty lines */
576 		if(str_keyword(&parse, "ENTRY_BEGIN")) {
577 			if(current) {
578 				error("%s line %d: previous entry does not ENTRY_END",
579 					name, pstate->lineno);
580 			}
581 			current = new_entry();
582 			current->lineno = pstate->lineno;
583 			cur_reply = entry_add_reply(current);
584 			continue;
585 		} else if(str_keyword(&parse, "$ORIGIN")) {
586 			get_origin(name, pstate, parse);
587 			continue;
588 		} else if(str_keyword(&parse, "$TTL")) {
589 			pstate->default_ttl = (uint32_t)atoi(parse);
590 			continue;
591 		}
592 
593 		/* working inside an entry */
594 		if(!current) {
595 			error("%s line %d: expected ENTRY_BEGIN but got %s",
596 				name, pstate->lineno, line);
597 		}
598 		if(str_keyword(&parse, "MATCH")) {
599 			matchline(parse, current);
600 		} else if(str_keyword(&parse, "REPLY")) {
601 			replyline(parse, pktbuf, pktlen, &do_flag);
602 		} else if(str_keyword(&parse, "ADJUST")) {
603 			adjustline(parse, current, cur_reply);
604 		} else if(str_keyword(&parse, "EXTRA_PACKET")) {
605 			/* copy current packet into buffer */
606 			cur_reply->reply_pkt = memdup(pktbuf, pktlen);
607 			cur_reply->reply_len = pktlen;
608 			if(!cur_reply->reply_pkt)
609 				error("out of memory");
610 			cur_reply = entry_add_reply(current);
611 			/* clear for next packet */
612 			pktlen = LDNS_HEADER_SIZE;
613 			memset(pktbuf, 0, pktlen); /* ID = 0, FLAGS="", and rr counts 0 */
614 		} else if(str_keyword(&parse, "SECTION")) {
615 			if(str_keyword(&parse, "QUESTION"))
616 				add_section = LDNS_SECTION_QUESTION;
617 			else if(str_keyword(&parse, "ANSWER"))
618 				add_section = LDNS_SECTION_ANSWER;
619 			else if(str_keyword(&parse, "AUTHORITY"))
620 				add_section = LDNS_SECTION_AUTHORITY;
621 			else if(str_keyword(&parse, "ADDITIONAL"))
622 				add_section = LDNS_SECTION_ADDITIONAL;
623 			else error("%s line %d: bad section %s", name, pstate->lineno, parse);
624 		} else if(str_keyword(&parse, "HEX_ANSWER_BEGIN")) {
625 			hex_data_buffer = sldns_buffer_new(MAX_PACKETLEN);
626 			reading_hex = 1;
627 		} else if(str_keyword(&parse, "HEX_ANSWER_END")) {
628 			if(!reading_hex) {
629 				error("%s line %d: HEX_ANSWER_END read but no HEX_ANSWER_BEGIN keyword seen", name, pstate->lineno);
630 			}
631 			reading_hex = 0;
632 			cur_reply->reply_from_hex = hex_buffer2wire(hex_data_buffer);
633 			sldns_buffer_free(hex_data_buffer);
634 			hex_data_buffer = NULL;
635 		} else if(reading_hex) {
636 			sldns_buffer_printf(hex_data_buffer, "%s", line);
637 		} else if(str_keyword(&parse, "HEX_EDNSDATA_BEGIN")) {
638 			hex_ednsdata_buffer = sldns_buffer_new(MAX_PACKETLEN);
639 			reading_hex_ednsdata = 1;
640 		} else if(str_keyword(&parse, "HEX_EDNSDATA_END")) {
641 			if (!reading_hex_ednsdata) {
642 				error("%s line %d: HEX_EDNSDATA_END read but no"
643 					"HEX_EDNSDATA_BEGIN keyword seen", name, pstate->lineno);
644 			}
645 			reading_hex_ednsdata = 0;
646 			cur_reply->raw_ednsdata = hex_buffer2wire(hex_ednsdata_buffer);
647 			sldns_buffer_free(hex_ednsdata_buffer);
648 			hex_ednsdata_buffer = NULL;
649 		} else if(reading_hex_ednsdata) {
650 			sldns_buffer_printf(hex_ednsdata_buffer, "%s", line);
651 		} else if(str_keyword(&parse, "ENTRY_END")) {
652 			if(hex_data_buffer)
653 				sldns_buffer_free(hex_data_buffer);
654 			if(hex_ednsdata_buffer)
655 				sldns_buffer_free(hex_ednsdata_buffer);
656 			if(pktlen != 0) {
657 				if(do_flag || cur_reply->raw_ednsdata) {
658 					if(cur_reply->raw_ednsdata &&
659 						sldns_buffer_limit(cur_reply->raw_ednsdata))
660 						add_edns(pktbuf, sizeof(pktbuf), do_flag,
661 							sldns_buffer_begin(cur_reply->raw_ednsdata),
662 							(uint16_t)sldns_buffer_limit(cur_reply->raw_ednsdata),
663 							&pktlen);
664 					else
665 						add_edns(pktbuf, sizeof(pktbuf), do_flag,
666 							NULL, 0, &pktlen);
667 				}
668 				cur_reply->reply_pkt = memdup(pktbuf, pktlen);
669 				cur_reply->reply_len = pktlen;
670 				if(!cur_reply->reply_pkt)
671 					error("out of memory");
672 			}
673 			return current;
674 		} else {
675 			add_rr(skip_whitespace?parse:line, pktbuf,
676 				sizeof(pktbuf), &pktlen, pstate, add_section,
677 				name);
678 		}
679 
680 	}
681 	if(reading_hex) {
682 		error("%s: End of file reached while still reading hex, "
683 			"missing HEX_ANSWER_END\n", name);
684 	}
685 	if(reading_hex_ednsdata) {
686 		error("%s: End of file reached while still reading edns data, "
687 			"missing HEX_EDNSDATA_END\n", name);
688 	}
689 	if(current) {
690 		error("%s: End of file reached while reading entry. "
691 			"missing ENTRY_END\n", name);
692 	}
693 	return 0;
694 }
695 
696 /* reads the canned reply file and returns a list of structs */
697 struct entry*
read_datafile(const char * name,int skip_whitespace)698 read_datafile(const char* name, int skip_whitespace)
699 {
700 	struct entry* list = NULL;
701 	struct entry* last = NULL;
702 	struct entry* current = NULL;
703 	FILE *in;
704 	struct sldns_file_parse_state pstate;
705 	int entry_num = 0;
706 	memset(&pstate, 0, sizeof(pstate));
707 
708 	if((in=fopen(name, "r")) == NULL) {
709 		error("could not open file %s: %s", name, strerror(errno));
710 	}
711 
712 	while((current = read_entry(in, name, &pstate, skip_whitespace)))
713 	{
714 		if(last)
715 			last->next = current;
716 		else	list = current;
717 		last = current;
718 		entry_num ++;
719 	}
720 	verbose(1, "%s: Read %d entries\n", prog_name, entry_num);
721 
722 	fclose(in);
723 	return list;
724 }
725 
726 /** get qtype from packet */
get_qtype(uint8_t * pkt,size_t pktlen)727 static sldns_rr_type get_qtype(uint8_t* pkt, size_t pktlen)
728 {
729 	uint8_t* d;
730 	size_t dl, sl=0;
731 	char* snull = NULL;
732 	int comprloop = 0;
733 	if(pktlen < LDNS_HEADER_SIZE)
734 		return 0;
735 	if(LDNS_QDCOUNT(pkt) == 0)
736 		return 0;
737 	/* skip over dname with dname-scan routine */
738 	d = pkt+LDNS_HEADER_SIZE;
739 	dl = pktlen-LDNS_HEADER_SIZE;
740 	(void)sldns_wire2str_dname_scan(&d, &dl, &snull, &sl, pkt, pktlen, &comprloop);
741 	if(dl < 2)
742 		return 0;
743 	return sldns_read_uint16(d);
744 }
745 
746 /** get qtype from packet */
get_qname_len(uint8_t * pkt,size_t pktlen)747 static size_t get_qname_len(uint8_t* pkt, size_t pktlen)
748 {
749 	uint8_t* d;
750 	size_t dl, sl=0;
751 	char* snull = NULL;
752 	int comprloop = 0;
753 	if(pktlen < LDNS_HEADER_SIZE)
754 		return 0;
755 	if(LDNS_QDCOUNT(pkt) == 0)
756 		return 0;
757 	/* skip over dname with dname-scan routine */
758 	d = pkt+LDNS_HEADER_SIZE;
759 	dl = pktlen-LDNS_HEADER_SIZE;
760 	(void)sldns_wire2str_dname_scan(&d, &dl, &snull, &sl, pkt, pktlen, &comprloop);
761 	return pktlen-dl-LDNS_HEADER_SIZE;
762 }
763 
764 /** returns owner from packet */
get_qname(uint8_t * pkt,size_t pktlen)765 static uint8_t* get_qname(uint8_t* pkt, size_t pktlen)
766 {
767 	if(pktlen < LDNS_HEADER_SIZE)
768 		return NULL;
769 	if(LDNS_QDCOUNT(pkt) == 0)
770 		return NULL;
771 	return pkt+LDNS_HEADER_SIZE;
772 }
773 
774 /** returns opcode from packet */
get_opcode(uint8_t * pkt,size_t pktlen)775 static int get_opcode(uint8_t* pkt, size_t pktlen)
776 {
777 	if(pktlen < LDNS_HEADER_SIZE)
778 		return 0;
779 	return (int)LDNS_OPCODE_WIRE(pkt);
780 }
781 
782 /** returns rcode from packet */
get_rcode(uint8_t * pkt,size_t pktlen)783 static int get_rcode(uint8_t* pkt, size_t pktlen)
784 {
785 	if(pktlen < LDNS_HEADER_SIZE)
786 		return 0;
787 	return (int)LDNS_RCODE_WIRE(pkt);
788 }
789 
790 /** get authority section SOA serial value */
get_serial(uint8_t * p,size_t plen)791 static uint32_t get_serial(uint8_t* p, size_t plen)
792 {
793 	uint8_t* walk = p;
794 	size_t walk_len = plen, sl=0;
795 	char* snull = NULL;
796 	uint16_t i;
797 	int comprloop = 0;
798 
799 	if(walk_len < LDNS_HEADER_SIZE)
800 		return 0;
801 	walk += LDNS_HEADER_SIZE;
802 	walk_len -= LDNS_HEADER_SIZE;
803 
804 	/* skip other records with wire2str_scan */
805 	for(i=0; i < LDNS_QDCOUNT(p); i++)
806 		(void)sldns_wire2str_rrquestion_scan(&walk, &walk_len,
807 			&snull, &sl, p, plen, &comprloop);
808 	for(i=0; i < LDNS_ANCOUNT(p); i++)
809 		(void)sldns_wire2str_rr_scan(&walk, &walk_len, &snull, &sl,
810 			p, plen, &comprloop);
811 
812 	/* walk through authority section */
813 	for(i=0; i < LDNS_NSCOUNT(p); i++) {
814 		/* if this is SOA then get serial, skip compressed dname */
815 		uint8_t* dstart = walk;
816 		size_t dlen = walk_len;
817 		(void)sldns_wire2str_dname_scan(&dstart, &dlen, &snull, &sl,
818 			p, plen, &comprloop);
819 		if(dlen >= 2 && sldns_read_uint16(dstart) == LDNS_RR_TYPE_SOA) {
820 			/* skip type, class, TTL, rdatalen */
821 			if(dlen < 10)
822 				return 0;
823 			if(dlen < 10 + (size_t)sldns_read_uint16(dstart+8))
824 				return 0;
825 			dstart += 10;
826 			dlen -= 10;
827 			/* check third rdf */
828 			(void)sldns_wire2str_dname_scan(&dstart, &dlen, &snull,
829 				&sl, p, plen, &comprloop);
830 			(void)sldns_wire2str_dname_scan(&dstart, &dlen, &snull,
831 				&sl, p, plen, &comprloop);
832 			if(dlen < 4)
833 				return 0;
834 			verbose(3, "found serial %u in msg. ",
835 				(int)sldns_read_uint32(dstart));
836 			return sldns_read_uint32(dstart);
837 		}
838 		/* move to next RR */
839 		(void)sldns_wire2str_rr_scan(&walk, &walk_len, &snull, &sl,
840 			p, plen, &comprloop);
841 	}
842 	return 0;
843 }
844 
845 /** get ptr to EDNS OPT record (and remaining length); after the type u16 */
846 static int
pkt_find_edns_opt(uint8_t ** p,size_t * plen)847 pkt_find_edns_opt(uint8_t** p, size_t* plen)
848 {
849 	/* walk over the packet with scan routines */
850 	uint8_t* w = *p;
851 	size_t wlen = *plen, sl=0;
852 	char* snull = NULL;
853 	uint16_t i;
854 	int comprloop = 0;
855 
856 	if(wlen < LDNS_HEADER_SIZE)
857 		return 0;
858 	w += LDNS_HEADER_SIZE;
859 	wlen -= LDNS_HEADER_SIZE;
860 
861 	/* skip other records with wire2str_scan */
862 	for(i=0; i < LDNS_QDCOUNT(*p); i++)
863 		(void)sldns_wire2str_rrquestion_scan(&w, &wlen, &snull, &sl,
864 			*p, *plen, &comprloop);
865 	for(i=0; i < LDNS_ANCOUNT(*p); i++)
866 		(void)sldns_wire2str_rr_scan(&w, &wlen, &snull, &sl, *p, *plen, &comprloop);
867 	for(i=0; i < LDNS_NSCOUNT(*p); i++)
868 		(void)sldns_wire2str_rr_scan(&w, &wlen, &snull, &sl, *p, *plen, &comprloop);
869 
870 	/* walk through additional section */
871 	for(i=0; i < LDNS_ARCOUNT(*p); i++) {
872 		/* if this is OPT then done */
873 		uint8_t* dstart = w;
874 		size_t dlen = wlen;
875 		(void)sldns_wire2str_dname_scan(&dstart, &dlen, &snull, &sl,
876 			*p, *plen, &comprloop);
877 		if(dlen >= 2 && sldns_read_uint16(dstart) == LDNS_RR_TYPE_OPT) {
878 			*p = dstart+2;
879 			*plen = dlen-2;
880 			return 1;
881 		}
882 		/* move to next RR */
883 		(void)sldns_wire2str_rr_scan(&w, &wlen, &snull, &sl, *p, *plen, &comprloop);
884 	}
885 	return 0;
886 }
887 
888 /** return true if the packet has EDNS OPT record */
889 static int
get_has_edns(uint8_t * pkt,size_t len)890 get_has_edns(uint8_t* pkt, size_t len)
891 {
892 	/* use arguments as temporary variables */
893 	return pkt_find_edns_opt(&pkt, &len);
894 }
895 
896 /** return true if the DO flag is set */
897 static int
get_do_flag(uint8_t * pkt,size_t len)898 get_do_flag(uint8_t* pkt, size_t len)
899 {
900 	uint16_t edns_bits;
901 	uint8_t* walk = pkt;
902 	size_t walk_len = len;
903 	if(!pkt_find_edns_opt(&walk, &walk_len)) {
904 		return 0;
905 	}
906 	if(walk_len < 6)
907 		return 0; /* malformed */
908 	edns_bits = sldns_read_uint16(walk+4);
909 	return (int)(edns_bits&LDNS_EDNS_MASK_DO_BIT);
910 }
911 
912 /** Snips the specified EDNS option out of the OPT record and puts it in the
913  *  provided buffer. The buffer should be able to hold any opt data ie 65535.
914  *  Returns the length of the option written,
915  *  or 0 if not found, else -1 on error. */
916 static int
pkt_snip_edns_option(uint8_t * pkt,size_t len,sldns_edns_option code,uint8_t * buf)917 pkt_snip_edns_option(uint8_t* pkt, size_t len, sldns_edns_option code,
918 	uint8_t* buf)
919 {
920 	uint8_t *rdata, *opt_position = pkt;
921 	uint16_t rdlen, optlen;
922 	size_t remaining = len;
923 	if(!pkt_find_edns_opt(&opt_position, &remaining)) return 0;
924 	if(remaining < 8) return -1; /* malformed */
925 	rdlen = sldns_read_uint16(opt_position+6);
926 	rdata = opt_position + 8;
927 	while(rdlen > 0) {
928 		if(rdlen < 4) return -1; /* malformed */
929 		optlen = sldns_read_uint16(rdata+2);
930 		if(sldns_read_uint16(rdata) == code) {
931 			/* save data to buf for caller inspection */
932 			memmove(buf, rdata+4, optlen);
933 			/* snip option from packet; assumes len is correct */
934 			memmove(rdata, rdata+4+optlen,
935 				(pkt+len)-(rdata+4+optlen));
936 			/* update OPT size */
937 			sldns_write_uint16(opt_position+6,
938 				sldns_read_uint16(opt_position+6)-(4+optlen));
939 			return optlen;
940 		}
941 		rdlen -= 4 + optlen;
942 		rdata += 4 + optlen;
943 	}
944 	return 0;
945 }
946 
947 /** Snips the EDE option out of the OPT record and returns the EDNS EDE
948  *  INFO-CODE if found, else -1 */
949 static int
extract_ede(uint8_t * pkt,size_t len)950 extract_ede(uint8_t* pkt, size_t len)
951 {
952 	uint8_t buf[65535];
953 	int buflen = pkt_snip_edns_option(pkt, len, LDNS_EDNS_EDE, buf);
954 	if(buflen < 2 /*ede without text at minimum*/) return -1;
955 	return sldns_read_uint16(buf);
956 }
957 
958 /** Snips the DNS Cookie option out of the OPT record and puts it in the
959  *  provided cookie buffer (should be at least 24 octets).
960  *  Returns the length of the cookie if found, else -1. */
961 static int
extract_cookie(uint8_t * pkt,size_t len,uint8_t * cookie)962 extract_cookie(uint8_t* pkt, size_t len, uint8_t* cookie)
963 {
964 	uint8_t buf[65535];
965 	int buflen = pkt_snip_edns_option(pkt, len, LDNS_EDNS_COOKIE, buf);
966 	if(buflen != 8 /*client cookie*/ &&
967 		buflen != 8 + 16 /*server cookie*/) return -1;
968 	memcpy(cookie, buf, buflen);
969 	return buflen;
970 }
971 
972 /** zero TTLs in packet */
973 static void
zerottls(uint8_t * pkt,size_t pktlen)974 zerottls(uint8_t* pkt, size_t pktlen)
975 {
976 	uint8_t* walk = pkt;
977 	size_t walk_len = pktlen, sl=0;
978 	char* snull = NULL;
979 	uint16_t i;
980 	uint16_t num = LDNS_ANCOUNT(pkt)+LDNS_NSCOUNT(pkt)+LDNS_ARCOUNT(pkt);
981 	int comprloop = 0;
982 	if(walk_len < LDNS_HEADER_SIZE)
983 		return;
984 	walk += LDNS_HEADER_SIZE;
985 	walk_len -= LDNS_HEADER_SIZE;
986 	for(i=0; i < LDNS_QDCOUNT(pkt); i++)
987 		(void)sldns_wire2str_rrquestion_scan(&walk, &walk_len,
988 			&snull, &sl, pkt, pktlen, &comprloop);
989 	for(i=0; i < num; i++) {
990 		/* wipe TTL */
991 		uint8_t* dstart = walk;
992 		size_t dlen = walk_len;
993 		(void)sldns_wire2str_dname_scan(&dstart, &dlen, &snull, &sl,
994 			pkt, pktlen, &comprloop);
995 		if(dlen < 8)
996 			return;
997 		sldns_write_uint32(dstart+4, 0);
998 		/* go to next RR */
999 		(void)sldns_wire2str_rr_scan(&walk, &walk_len, &snull, &sl,
1000 			pkt, pktlen, &comprloop);
1001 	}
1002 }
1003 
1004 /** get one line (\n) from a string, move next to after the \n, zero \n */
1005 static int
get_line(char ** s,char ** n)1006 get_line(char** s, char** n)
1007 {
1008 	/* at end of string? end */
1009 	if(*n == NULL || **n == 0)
1010 		return 0;
1011 	/* result starts at next string */
1012 	*s = *n;
1013 	/* find \n after that */
1014 	*n = strchr(*s, '\n');
1015 	if(*n && **n != 0) {
1016 		/* terminate line */
1017 		(*n)[0] = 0;
1018 		(*n)++;
1019 	}
1020 	return 1;
1021 }
1022 
1023 /** match two RR sections without ordering */
1024 static int
match_noloc_section(char ** q,char ** nq,char ** p,char ** np,uint16_t num)1025 match_noloc_section(char** q, char** nq, char** p, char** np, uint16_t num)
1026 {
1027 	/* for max number of RRs in packet */
1028 	const uint16_t numarray = 3000;
1029 	char* qlines[numarray], *plines[numarray];
1030 	uint16_t i, j, numq=0, nump=0;
1031 	if(num > numarray) fatal_exit("too many RRs");
1032 	/* gather lines */
1033 	for(i=0; i<num; i++) {
1034 		get_line(q, nq);
1035 		get_line(p, np);
1036 		qlines[numq++] = *q;
1037 		plines[nump++] = *p;
1038 	}
1039 	/* see if they are all present in the other */
1040 	for(i=0; i<num; i++) {
1041 		int found = 0;
1042 		for(j=0; j<num; j++) {
1043 			if(strcmp(qlines[i], plines[j]) == 0) {
1044 				found = 1;
1045 				break;
1046 			}
1047 		}
1048 		if(!found) {
1049 			verbose(3, "comparenoloc: failed for %s", qlines[i]);
1050 			return 0;
1051 		}
1052 	}
1053 	return 1;
1054 }
1055 
1056 /** match two strings for unordered equality of RRs and everything else */
1057 static int
match_noloc(char * q,char * p,uint8_t * q_pkt,size_t q_pkt_len,uint8_t * p_pkt,size_t p_pkt_len)1058 match_noloc(char* q, char* p, uint8_t* q_pkt, size_t q_pkt_len,
1059 	uint8_t* p_pkt, size_t p_pkt_len)
1060 {
1061 	char* nq = q, *np = p;
1062 	/* if no header, compare bytes */
1063 	if(p_pkt_len < LDNS_HEADER_SIZE || q_pkt_len < LDNS_HEADER_SIZE) {
1064 		if(p_pkt_len != q_pkt_len) return 0;
1065 		return memcmp(p, q, p_pkt_len);
1066 	}
1067 	/* compare RR counts */
1068 	if(LDNS_QDCOUNT(p_pkt) != LDNS_QDCOUNT(q_pkt))
1069 		return 0;
1070 	if(LDNS_ANCOUNT(p_pkt) != LDNS_ANCOUNT(q_pkt))
1071 		return 0;
1072 	if(LDNS_NSCOUNT(p_pkt) != LDNS_NSCOUNT(q_pkt))
1073 		return 0;
1074 	if(LDNS_ARCOUNT(p_pkt) != LDNS_ARCOUNT(q_pkt))
1075 		return 0;
1076 	/* get a line from both; compare; at sections do section */
1077 	get_line(&q, &nq);
1078 	get_line(&p, &np);
1079 	if(strcmp(q, p) != 0) {
1080 		/* header line opcode, rcode, id */
1081 		return 0;
1082 	}
1083 	get_line(&q, &nq);
1084 	get_line(&p, &np);
1085 	if(strcmp(q, p) != 0) {
1086 		/* header flags, rr counts */
1087 		return 0;
1088 	}
1089 	/* ;; QUESTION SECTION */
1090 	get_line(&q, &nq);
1091 	get_line(&p, &np);
1092 	if(strcmp(q, p) != 0) return 0;
1093 	if(!match_noloc_section(&q, &nq, &p, &np, LDNS_QDCOUNT(p_pkt)))
1094 		return 0;
1095 
1096 	/* empty line and ;; ANSWER SECTION */
1097 	get_line(&q, &nq);
1098 	get_line(&p, &np);
1099 	if(strcmp(q, p) != 0) return 0;
1100 	get_line(&q, &nq);
1101 	get_line(&p, &np);
1102 	if(strcmp(q, p) != 0) return 0;
1103 	if(!match_noloc_section(&q, &nq, &p, &np, LDNS_ANCOUNT(p_pkt)))
1104 		return 0;
1105 
1106 	/* empty line and ;; AUTHORITY SECTION */
1107 	get_line(&q, &nq);
1108 	get_line(&p, &np);
1109 	if(strcmp(q, p) != 0) return 0;
1110 	get_line(&q, &nq);
1111 	get_line(&p, &np);
1112 	if(strcmp(q, p) != 0) return 0;
1113 	if(!match_noloc_section(&q, &nq, &p, &np, LDNS_NSCOUNT(p_pkt)))
1114 		return 0;
1115 
1116 	/* empty line and ;; ADDITIONAL SECTION */
1117 	get_line(&q, &nq);
1118 	get_line(&p, &np);
1119 	if(strcmp(q, p) != 0) return 0;
1120 	get_line(&q, &nq);
1121 	get_line(&p, &np);
1122 	if(strcmp(q, p) != 0) return 0;
1123 	if(!match_noloc_section(&q, &nq, &p, &np, LDNS_ARCOUNT(p_pkt)))
1124 		return 0;
1125 
1126 	return 1;
1127 }
1128 
1129 /** lowercase domain name - does not follow compression pointers */
lowercase_dname(uint8_t ** p,size_t * remain)1130 static void lowercase_dname(uint8_t** p, size_t* remain)
1131 {
1132 	unsigned i, llen;
1133 	if(*remain == 0) return;
1134 	while(**p != 0) {
1135 		/* compressed? */
1136 		if((**p & 0xc0) == 0xc0) {
1137 			*p += 2;
1138 			*remain -= 2;
1139 			return;
1140 		}
1141 		llen = (unsigned int)**p;
1142 		*p += 1;
1143 		*remain -= 1;
1144 		if(*remain < llen)
1145 			llen = (unsigned int)*remain;
1146 		for(i=0; i<llen; i++) {
1147 			(*p)[i] = (uint8_t)tolower((int)(*p)[i]);
1148 		}
1149 		*p += llen;
1150 		*remain -= llen;
1151 		if(*remain == 0) return;
1152 	}
1153 	/* skip root label */
1154 	*p += 1;
1155 	*remain -= 1;
1156 }
1157 
1158 /** lowercase rdata of type */
lowercase_rdata(uint8_t ** p,size_t * remain,uint16_t rdatalen,uint16_t t)1159 static void lowercase_rdata(uint8_t** p, size_t* remain,
1160 	uint16_t rdatalen, uint16_t t)
1161 {
1162 	const sldns_rr_descriptor *desc = sldns_rr_descript(t);
1163 	uint8_t dname_count = 0;
1164 	size_t i = 0;
1165 	size_t rdataremain = rdatalen;
1166 	if(!desc) {
1167 		/* unknown type */
1168 		*p += rdatalen;
1169 		*remain -= rdatalen;
1170 		return;
1171 	}
1172 	while(dname_count < desc->_dname_count) {
1173 		sldns_rdf_type f = sldns_rr_descriptor_field_type(desc, i++);
1174 		if(f == LDNS_RDF_TYPE_DNAME) {
1175 			lowercase_dname(p, &rdataremain);
1176 			dname_count++;
1177 		} else if(f == LDNS_RDF_TYPE_STR) {
1178 			uint8_t len;
1179 			if(rdataremain == 0) return;
1180 			len = **p;
1181 			*p += len+1;
1182 			rdataremain -= len+1;
1183 		} else {
1184 			int len = 0;
1185 			switch(f) {
1186 			case LDNS_RDF_TYPE_CLASS:
1187 			case LDNS_RDF_TYPE_ALG:
1188 			case LDNS_RDF_TYPE_INT8:
1189 				len = 1;
1190 				break;
1191 			case LDNS_RDF_TYPE_INT16:
1192 			case LDNS_RDF_TYPE_TYPE:
1193 			case LDNS_RDF_TYPE_CERT_ALG:
1194 				len = 2;
1195 				break;
1196 			case LDNS_RDF_TYPE_INT32:
1197 			case LDNS_RDF_TYPE_TIME:
1198 			case LDNS_RDF_TYPE_A:
1199 			case LDNS_RDF_TYPE_PERIOD:
1200 				len = 4;
1201 				break;
1202 			case LDNS_RDF_TYPE_TSIGTIME:
1203 				len = 6;
1204 				break;
1205 			case LDNS_RDF_TYPE_AAAA:
1206 				len = 16;
1207 				break;
1208 			default: error("bad rdf type in lowercase %d", (int)f);
1209 			}
1210 			*p += len;
1211 			rdataremain -= len;
1212 		}
1213 	}
1214 	/* skip remainder of rdata */
1215 	*p += rdataremain;
1216 	*remain -= rdatalen;
1217 }
1218 
1219 /** lowercase all names in the message */
lowercase_pkt(uint8_t * pkt,size_t pktlen)1220 static void lowercase_pkt(uint8_t* pkt, size_t pktlen)
1221 {
1222 	uint16_t i;
1223 	uint8_t* p = pkt;
1224 	size_t remain = pktlen;
1225 	uint16_t t, rdatalen;
1226 	if(pktlen < LDNS_HEADER_SIZE)
1227 		return;
1228 	p += LDNS_HEADER_SIZE;
1229 	remain -= LDNS_HEADER_SIZE;
1230 	for(i=0; i<LDNS_QDCOUNT(pkt); i++) {
1231 		lowercase_dname(&p, &remain);
1232 		if(remain < 4) return;
1233 		p += 4;
1234 		remain -= 4;
1235 	}
1236 	for(i=0; i<LDNS_ANCOUNT(pkt)+LDNS_NSCOUNT(pkt)+LDNS_ARCOUNT(pkt); i++) {
1237 		lowercase_dname(&p, &remain);
1238 		if(remain < 10) return;
1239 		t = sldns_read_uint16(p);
1240 		rdatalen = sldns_read_uint16(p+8);
1241 		p += 10;
1242 		remain -= 10;
1243 		if(remain < rdatalen) return;
1244 		lowercase_rdata(&p, &remain, rdatalen, t);
1245 	}
1246 }
1247 
1248 /** match question section of packet */
1249 static int
match_question(uint8_t * q,size_t qlen,uint8_t * p,size_t plen,int mttl)1250 match_question(uint8_t* q, size_t qlen, uint8_t* p, size_t plen, int mttl)
1251 {
1252 	char* qstr, *pstr, *s, *qcmpstr, *pcmpstr;
1253 	uint8_t* qb = q, *pb = p;
1254 	int r;
1255 	/* zero TTLs */
1256 	qb = memdup(q, qlen);
1257 	pb = memdup(p, plen);
1258 	if(!qb || !pb) error("out of memory");
1259 	if(!mttl) {
1260 		zerottls(qb, qlen);
1261 		zerottls(pb, plen);
1262 	}
1263 	lowercase_pkt(qb, qlen);
1264 	lowercase_pkt(pb, plen);
1265 	qstr = sldns_wire2str_pkt(qb, qlen);
1266 	pstr = sldns_wire2str_pkt(pb, plen);
1267 	if(!qstr || !pstr) error("cannot pkt2string");
1268 
1269 	/* remove before ;; QUESTION */
1270 	s = strstr(qstr, ";; QUESTION SECTION");
1271 	qcmpstr = s;
1272 	s = strstr(pstr, ";; QUESTION SECTION");
1273 	pcmpstr = s;
1274 	if(!qcmpstr && !pcmpstr) {
1275 		free(qstr);
1276 		free(pstr);
1277 		free(qb);
1278 		free(pb);
1279 		return 1;
1280 	}
1281 	if(!qcmpstr || !pcmpstr) {
1282 		free(qstr);
1283 		free(pstr);
1284 		free(qb);
1285 		free(pb);
1286 		return 0;
1287 	}
1288 
1289 	/* remove after answer section, (;; ANS, ;; AUTH, ;; ADD  ..) */
1290 	s = strstr(qcmpstr, ";; ANSWER SECTION");
1291 	if(!s) s = strstr(qcmpstr, ";; AUTHORITY SECTION");
1292 	if(!s) s = strstr(qcmpstr, ";; ADDITIONAL SECTION");
1293 	if(!s) s = strstr(qcmpstr, ";; MSG SIZE");
1294 	if(s) *s = 0;
1295 	s = strstr(pcmpstr, ";; ANSWER SECTION");
1296 	if(!s) s = strstr(pcmpstr, ";; AUTHORITY SECTION");
1297 	if(!s) s = strstr(pcmpstr, ";; ADDITIONAL SECTION");
1298 	if(!s) s = strstr(pcmpstr, ";; MSG SIZE");
1299 	if(s) *s = 0;
1300 
1301 	r = (strcmp(qcmpstr, pcmpstr) == 0);
1302 
1303 	if(!r) {
1304 		verbose(3, "mismatch question section '%s' and '%s'",
1305 			qcmpstr, pcmpstr);
1306 	}
1307 
1308 	free(qstr);
1309 	free(pstr);
1310 	free(qb);
1311 	free(pb);
1312 	return r;
1313 }
1314 
1315 /** match answer section of packet */
1316 static int
match_answer(uint8_t * q,size_t qlen,uint8_t * p,size_t plen,int mttl)1317 match_answer(uint8_t* q, size_t qlen, uint8_t* p, size_t plen, int mttl)
1318 {
1319 	char* qstr, *pstr, *s, *qcmpstr, *pcmpstr;
1320 	uint8_t* qb = q, *pb = p;
1321 	int r;
1322 	/* zero TTLs */
1323 	qb = memdup(q, qlen);
1324 	pb = memdup(p, plen);
1325 	if(!qb || !pb) error("out of memory");
1326 	if(!mttl) {
1327 		zerottls(qb, qlen);
1328 		zerottls(pb, plen);
1329 	}
1330 	lowercase_pkt(qb, qlen);
1331 	lowercase_pkt(pb, plen);
1332 	qstr = sldns_wire2str_pkt(qb, qlen);
1333 	pstr = sldns_wire2str_pkt(pb, plen);
1334 	if(!qstr || !pstr) error("cannot pkt2string");
1335 
1336 	/* remove before ;; ANSWER */
1337 	s = strstr(qstr, ";; ANSWER SECTION");
1338 	qcmpstr = s;
1339 	s = strstr(pstr, ";; ANSWER SECTION");
1340 	pcmpstr = s;
1341 	if(!qcmpstr && !pcmpstr) {
1342 		free(qstr);
1343 		free(pstr);
1344 		free(qb);
1345 		free(pb);
1346 		return 1;
1347 	}
1348 	if(!qcmpstr || !pcmpstr) {
1349 		free(qstr);
1350 		free(pstr);
1351 		free(qb);
1352 		free(pb);
1353 		return 0;
1354 	}
1355 
1356 	/* remove after answer section, (;; AUTH, ;; ADD, ;; MSG size ..) */
1357 	s = strstr(qcmpstr, ";; AUTHORITY SECTION");
1358 	if(!s) s = strstr(qcmpstr, ";; ADDITIONAL SECTION");
1359 	if(!s) s = strstr(qcmpstr, ";; MSG SIZE");
1360 	if(s) *s = 0;
1361 	s = strstr(pcmpstr, ";; AUTHORITY SECTION");
1362 	if(!s) s = strstr(pcmpstr, ";; ADDITIONAL SECTION");
1363 	if(!s) s = strstr(pcmpstr, ";; MSG SIZE");
1364 	if(s) *s = 0;
1365 
1366 	r = (strcmp(qcmpstr, pcmpstr) == 0);
1367 
1368 	if(!r) {
1369 		verbose(3, "mismatch answer section '%s' and '%s'",
1370 			qcmpstr, pcmpstr);
1371 	}
1372 
1373 	free(qstr);
1374 	free(pstr);
1375 	free(qb);
1376 	free(pb);
1377 	return r;
1378 }
1379 
1380 /** ignore EDNS lines in the string by overwriting them with what's left or
1381  *  zero out if at end of the string */
1382 static int
ignore_edns_lines(char * str)1383 ignore_edns_lines(char* str) {
1384 	char* edns = str, *n;
1385 	size_t str_len = strlen(str);
1386 	while((edns = strstr(edns, "; EDNS"))) {
1387 		n = strchr(edns, '\n');
1388 		if(!n) {
1389 			/* EDNS at end of string; zero */
1390 			*edns = 0;
1391 			break;
1392 		}
1393 		memmove(edns, n+1, str_len-(n-str));
1394 	}
1395 	return 1;
1396 }
1397 
1398 /** match all of the packet */
1399 int
match_all(uint8_t * q,size_t qlen,uint8_t * p,size_t plen,int mttl,int noloc,int noedns)1400 match_all(uint8_t* q, size_t qlen, uint8_t* p, size_t plen, int mttl,
1401 	int noloc, int noedns)
1402 {
1403 	char* qstr, *pstr;
1404 	uint8_t* qb = q, *pb = p;
1405 	int r;
1406 	qb = memdup(q, qlen);
1407 	pb = memdup(p, plen);
1408 	if(!qb || !pb) error("out of memory");
1409 	/* zero TTLs */
1410 	if(!mttl) {
1411 		zerottls(qb, qlen);
1412 		zerottls(pb, plen);
1413 	}
1414 	lowercase_pkt(qb, qlen);
1415 	lowercase_pkt(pb, plen);
1416 	qstr = sldns_wire2str_pkt(qb, qlen);
1417 	pstr = sldns_wire2str_pkt(pb, plen);
1418 	if(!qstr || !pstr) error("cannot pkt2string");
1419 	/* should we ignore EDNS lines? */
1420 	if(noedns) {
1421 		ignore_edns_lines(qstr);
1422 		ignore_edns_lines(pstr);
1423 	}
1424 	r = (strcmp(qstr, pstr) == 0);
1425 	if(!r) {
1426 		/* remove ;; MSG SIZE (at end of string) */
1427 		char* s = strstr(qstr, ";; MSG SIZE");
1428 		if(s) *s=0;
1429 		s = strstr(pstr, ";; MSG SIZE");
1430 		if(s) *s=0;
1431 		r = (strcmp(qstr, pstr) == 0);
1432 		if(!r && !noloc && !noedns) {
1433 			/* we are going to fail, see if the cause is EDNS */
1434 			char* a = strstr(qstr, "; EDNS");
1435 			char* b = strstr(pstr, "; EDNS");
1436 			if( (a&&!b) || (b&&!a) ) {
1437 				verbose(3, "mismatch in EDNS\n");
1438 			}
1439 		}
1440 	}
1441 	if(!r && noloc) {
1442 		/* check for reordered sections */
1443 		r = match_noloc(qstr, pstr, q, qlen, p, plen);
1444 	}
1445 	if(!r) {
1446 		verbose(3, "mismatch pkt '%s' and '%s'", qstr, pstr);
1447 	}
1448 	free(qstr);
1449 	free(pstr);
1450 	free(qb);
1451 	free(pb);
1452 	return r;
1453 }
1454 
1455 /** see if domain names are equal */
equal_dname(uint8_t * q,size_t qlen,uint8_t * p,size_t plen)1456 static int equal_dname(uint8_t* q, size_t qlen, uint8_t* p, size_t plen)
1457 {
1458 	uint8_t* qn = get_qname(q, qlen);
1459 	uint8_t* pn = get_qname(p, plen);
1460 	char qs[512], ps[512];
1461 	size_t qslen = sizeof(qs), pslen = sizeof(ps);
1462 	char* qss = qs, *pss = ps;
1463 	int comprloop = 0;
1464 	if(!qn || !pn)
1465 		return 0;
1466 	(void)sldns_wire2str_dname_scan(&qn, &qlen, &qss, &qslen, q, qlen, &comprloop);
1467 	(void)sldns_wire2str_dname_scan(&pn, &plen, &pss, &pslen, p, plen, &comprloop);
1468 	return (strcmp(qs, ps) == 0);
1469 }
1470 
1471 /** see if domain names are subdomain q of p */
subdomain_dname(uint8_t * q,size_t qlen,uint8_t * p,size_t plen)1472 static int subdomain_dname(uint8_t* q, size_t qlen, uint8_t* p, size_t plen)
1473 {
1474 	/* we use the tostring routines so as to test unbound's routines
1475 	 * with something else */
1476 	uint8_t* qn = get_qname(q, qlen);
1477 	uint8_t* pn = get_qname(p, plen);
1478 	char qs[5120], ps[5120];
1479 	size_t qslen = sizeof(qs), pslen = sizeof(ps);
1480 	char* qss = qs, *pss = ps;
1481 	int comprloop = 0;
1482 	if(!qn || !pn)
1483 		return 0;
1484 	/* decompresses domain names */
1485 	(void)sldns_wire2str_dname_scan(&qn, &qlen, &qss, &qslen, q, qlen, &comprloop);
1486 	(void)sldns_wire2str_dname_scan(&pn, &plen, &pss, &pslen, p, plen, &comprloop);
1487 	/* same: false, (strict subdomain check)??? */
1488 	if(strcmp(qs, ps) == 0)
1489 		return 1;
1490 	/* qs must end in ps, at a dot, without \ in front */
1491 	qslen = strlen(qs);
1492 	pslen = strlen(ps);
1493 	if(qslen > pslen && strcmp(qs + (qslen-pslen), ps) == 0 &&
1494 		qslen + 2 >= pslen && /* space for label and dot */
1495 		qs[qslen-pslen-1] == '.') {
1496 		unsigned int slashcount = 0;
1497 		size_t i = qslen-pslen-2;
1498 		while(i>0 && qs[i]=='\\') {
1499 			i++;
1500 			slashcount++;
1501 		}
1502 		if(slashcount%1 == 1) return 0; /* . preceded by \ */
1503 		return 1;
1504 	}
1505 	return 0;
1506 }
1507 
1508 /** Match OPT RDATA (not the EDNS payload size or flags) */
1509 static int
match_ednsdata(uint8_t * q,size_t qlen,uint8_t * p,size_t plen)1510 match_ednsdata(uint8_t* q, size_t qlen, uint8_t* p, size_t plen)
1511 {
1512 	uint8_t* walk_q = q;
1513 	size_t walk_qlen = qlen;
1514 	uint8_t* walk_p = p;
1515 	size_t walk_plen = plen;
1516 
1517 	if(!pkt_find_edns_opt(&walk_q, &walk_qlen))
1518 		walk_qlen = 0;
1519 	if(!pkt_find_edns_opt(&walk_p, &walk_plen))
1520 		walk_plen = 0;
1521 
1522 	/* class + ttl + rdlen = 8 */
1523 	if(walk_qlen <= 8 && walk_plen <= 8) {
1524 		verbose(3, "NO edns opt, move on");
1525 		return 1;
1526 	}
1527 	if(walk_qlen != walk_plen)
1528 		return 0;
1529 
1530 	return (memcmp(walk_p+8, walk_q+8, walk_qlen-8) == 0);
1531 }
1532 
1533 /* finds entry in list, or returns NULL */
1534 struct entry*
find_match(struct entry * entries,uint8_t * query_pkt,size_t len,enum transport_type transport)1535 find_match(struct entry* entries, uint8_t* query_pkt, size_t len,
1536 	enum transport_type transport)
1537 {
1538 	struct entry* p = entries;
1539 	uint8_t* reply, *query_pkt_orig;
1540 	size_t rlen, query_pkt_orig_len;
1541 	/* Keep the original packet; it may be modified */
1542 	query_pkt_orig = memdup(query_pkt, len);
1543 	query_pkt_orig_len = len;
1544 	for(p=entries; p; p=p->next) {
1545 		verbose(3, "comparepkt: ");
1546 		reply = p->reply_list->reply_pkt;
1547 		rlen = p->reply_list->reply_len;
1548 		/* Restore the original packet for each entry */
1549 		memcpy(query_pkt, query_pkt_orig, query_pkt_orig_len);
1550 		/* EDE should be first since it may modify the query_pkt */
1551 		if(p->match_ede) {
1552 			int info_code = extract_ede(query_pkt, len);
1553 			if(info_code == -1) {
1554 				verbose(3, "bad EDE. Expected but not found\n");
1555 				continue;
1556 			} else if(!p->match_ede_any &&
1557 				(uint16_t)info_code != p->ede_info_code) {
1558 				verbose(3, "bad EDE INFO-CODE. Expected: %d, "
1559 					"and got: %d\n", (int)p->ede_info_code,
1560 					info_code);
1561 				continue;
1562 			}
1563 		}
1564 		/* Cookies could also modify the query_pkt; keep them early */
1565 		if(p->match_client_cookie || p->match_server_cookie) {
1566 			uint8_t cookie[24];
1567 			int cookie_len = extract_cookie(query_pkt, len,
1568 				cookie);
1569 			if(cookie_len == -1) {
1570 				verbose(3, "bad DNS Cookie. "
1571 					"Expected but not found\n");
1572 				continue;
1573 			} else if(p->match_client_cookie &&
1574 				cookie_len != 8) {
1575 				verbose(3, "bad DNS Cookie. Expected client "
1576 					"cookie of length 8.");
1577 				continue;
1578 			} else if((p->match_server_cookie) &&
1579 				cookie_len != 24) {
1580 				verbose(3, "bad DNS Cookie. Expected server "
1581 					"cookie of length 24.");
1582 				continue;
1583 			}
1584 		}
1585 		if(p->match_opcode && get_opcode(query_pkt, len) !=
1586 			get_opcode(reply, rlen)) {
1587 			verbose(3, "bad opcode\n");
1588 			continue;
1589 		}
1590 		if(p->match_qtype && get_qtype(query_pkt, len) !=
1591 			get_qtype(reply, rlen)) {
1592 			verbose(3, "bad qtype %d %d\n", get_qtype(query_pkt, len), get_qtype(reply, rlen));
1593 			continue;
1594 		}
1595 		if(p->match_qname) {
1596 			if(!equal_dname(query_pkt, len, reply, rlen)) {
1597 				verbose(3, "bad qname\n");
1598 				continue;
1599 			}
1600 		}
1601 		if(p->match_rcode) {
1602 			if(get_rcode(query_pkt, len) != get_rcode(reply, rlen)) {
1603 				char *r1 = sldns_wire2str_rcode(get_rcode(query_pkt, len));
1604 				char *r2 = sldns_wire2str_rcode(get_rcode(reply, rlen));
1605 				verbose(3, "bad rcode %s instead of %s\n",
1606 					r1, r2);
1607 				free(r1);
1608 				free(r2);
1609 				continue;
1610 			}
1611 		}
1612 		if(p->match_question) {
1613 			if(!match_question(query_pkt, len, reply, rlen,
1614 				(int)p->match_ttl)) {
1615 				verbose(3, "bad question section\n");
1616 				continue;
1617 			}
1618 		}
1619 		if(p->match_answer) {
1620 			if(!match_answer(query_pkt, len, reply, rlen,
1621 				(int)p->match_ttl)) {
1622 				verbose(3, "bad answer section\n");
1623 				continue;
1624 			}
1625 		}
1626 		if(p->match_subdomain) {
1627 			if(!subdomain_dname(query_pkt, len, reply, rlen)) {
1628 				verbose(3, "bad subdomain\n");
1629 				continue;
1630 			}
1631 		}
1632 		if(p->match_serial && get_serial(query_pkt, len) != p->ixfr_soa_serial) {
1633 				verbose(3, "bad serial\n");
1634 				continue;
1635 		}
1636 		if(p->match_do && !get_do_flag(query_pkt, len)) {
1637 			verbose(3, "no DO bit set\n");
1638 			continue;
1639 		}
1640 		if(p->match_noedns && get_has_edns(query_pkt, len)) {
1641 			verbose(3, "bad; EDNS OPT present\n");
1642 			continue;
1643 		}
1644 		if(p->match_ednsdata_raw &&
1645 				!match_ednsdata(query_pkt, len, reply, rlen)) {
1646 			verbose(3, "bad EDNS data match.\n");
1647 			continue;
1648 		}
1649 		if(p->match_transport != transport_any && p->match_transport != transport) {
1650 			verbose(3, "bad transport\n");
1651 			continue;
1652 		}
1653 		if(p->match_all_noedns && !match_all(query_pkt, len, reply,
1654 			rlen, (int)p->match_ttl, 0, 1)) {
1655 			verbose(3, "bad all_noedns match\n");
1656 			continue;
1657 		}
1658 		if(p->match_all && !match_all(query_pkt, len, reply, rlen,
1659 			(int)p->match_ttl, 0, 0)) {
1660 			verbose(3, "bad allmatch\n");
1661 			continue;
1662 		}
1663 		verbose(3, "match!\n");
1664 		/* Restore the original packet */
1665 		memcpy(query_pkt, query_pkt_orig, query_pkt_orig_len);
1666 		free(query_pkt_orig);
1667 		return p;
1668 	}
1669 	/* Restore the original packet */
1670 	memcpy(query_pkt, query_pkt_orig, query_pkt_orig_len);
1671 	free(query_pkt_orig);
1672 	return NULL;
1673 }
1674 
1675 void
adjust_packet(struct entry * match,uint8_t ** answer_pkt,size_t * answer_len,uint8_t * query_pkt,size_t query_len)1676 adjust_packet(struct entry* match, uint8_t** answer_pkt, size_t *answer_len,
1677 	uint8_t* query_pkt, size_t query_len)
1678 {
1679 	uint8_t* orig = *answer_pkt;
1680 	size_t origlen = *answer_len;
1681 	uint8_t* res;
1682 	size_t reslen;
1683 
1684 	/* perform the copy; if possible; must be uncompressed */
1685 	if(match->copy_query && origlen >= LDNS_HEADER_SIZE &&
1686 		query_len >= LDNS_HEADER_SIZE && LDNS_QDCOUNT(query_pkt)!=0
1687 		&& LDNS_QDCOUNT(orig)==0) {
1688 		/* no qname in output packet, insert it */
1689 		size_t dlen = get_qname_len(query_pkt, query_len);
1690 		reslen = origlen + dlen + 4;
1691 		res = (uint8_t*)malloc(reslen);
1692 		if(!res) {
1693 			verbose(1, "out of memory; send without adjust\n");
1694 			return;
1695 		}
1696 		/* copy the header, query, remainder */
1697 		memcpy(res, orig, LDNS_HEADER_SIZE);
1698 		memmove(res+LDNS_HEADER_SIZE, query_pkt+LDNS_HEADER_SIZE,
1699 			dlen+4);
1700 		memmove(res+LDNS_HEADER_SIZE+dlen+4, orig+LDNS_HEADER_SIZE,
1701 			reslen-(LDNS_HEADER_SIZE+dlen+4));
1702 		/* set QDCOUNT */
1703 		sldns_write_uint16(res+4, 1);
1704 	} else if(match->copy_query && origlen >= LDNS_HEADER_SIZE &&
1705 		query_len >= LDNS_HEADER_SIZE && LDNS_QDCOUNT(query_pkt)!=0
1706 		&& get_qname_len(orig, origlen) == 0) {
1707 		/* QDCOUNT(orig)!=0 but qlen == 0, therefore, an error */
1708 		verbose(1, "error: malformed qname; send without adjust\n");
1709 		res = memdup(orig, origlen);
1710 		reslen = origlen;
1711 	} else if(match->copy_query && origlen >= LDNS_HEADER_SIZE &&
1712 		query_len >= LDNS_HEADER_SIZE && LDNS_QDCOUNT(query_pkt)!=0
1713 		&& LDNS_QDCOUNT(orig)!=0) {
1714 		/* in this case olen != 0 and QDCOUNT(orig)!=0 */
1715 		/* copy query section */
1716 		size_t dlen = get_qname_len(query_pkt, query_len);
1717 		size_t olen = get_qname_len(orig, origlen);
1718 		reslen = origlen + dlen - olen;
1719 		res = (uint8_t*)malloc(reslen);
1720 		if(!res) {
1721 			verbose(1, "out of memory; send without adjust\n");
1722 			return;
1723 		}
1724 		/* copy the header, query, remainder */
1725 		memcpy(res, orig, LDNS_HEADER_SIZE);
1726 		memmove(res+LDNS_HEADER_SIZE, query_pkt+LDNS_HEADER_SIZE,
1727 			dlen+4);
1728 		memmove(res+LDNS_HEADER_SIZE+dlen+4,
1729 			orig+LDNS_HEADER_SIZE+olen+4,
1730 			reslen-(LDNS_HEADER_SIZE+dlen+4));
1731 	} else {
1732 		res = memdup(orig, origlen);
1733 		reslen = origlen;
1734 	}
1735 	if(!res) {
1736 		verbose(1, "out of memory; send without adjust\n");
1737 		return;
1738 	}
1739 	/* copy the ID */
1740 	if(match->copy_id && reslen >= 2 && query_len >= 2)
1741 		res[1] = query_pkt[1];
1742 	if(match->copy_id && reslen >= 1 && query_len >= 1)
1743 		res[0] = query_pkt[0];
1744 
1745 	if(match->copy_ednsdata_assume_clientsubnet) {
1746 		/** Assume there is only one EDNS option, which is ECS.
1747 		 * Copy source mask from query to scope mask in reply. Assume
1748 		 * rest of ECS data in response (eg address) matches the query.
1749 		 */
1750 		uint8_t* walk_q = orig;
1751 		size_t walk_qlen = origlen;
1752 		uint8_t* walk_p = res;
1753 		size_t walk_plen = reslen;
1754 
1755 		if(!pkt_find_edns_opt(&walk_q, &walk_qlen)) {
1756 			walk_qlen = 0;
1757 		}
1758 		if(!pkt_find_edns_opt(&walk_p, &walk_plen)) {
1759 			walk_plen = 0;
1760 		}
1761 		/* class + ttl + rdlen + optcode + optlen + ecs fam + ecs source
1762 		 * + ecs scope = index 15 */
1763 		if(walk_qlen >= 15 && walk_plen >= 15) {
1764 			walk_p[15] = walk_q[14];
1765 		}
1766 		if(match->increment_ecs_scope) {
1767 			walk_p[15]++;
1768 		}
1769 	}
1770 
1771 	if(match->sleeptime > 0) {
1772 		verbose(3, "sleeping for %d seconds\n", match->sleeptime);
1773 #ifdef HAVE_SLEEP
1774 		sleep(match->sleeptime);
1775 #else
1776 		Sleep(match->sleeptime * 1000);
1777 #endif
1778 	}
1779 	*answer_pkt = res;
1780 	*answer_len = reslen;
1781 }
1782 
1783 /*
1784  * Parses data buffer to a query, finds the correct answer
1785  * and calls the given function for every packet to send.
1786  */
1787 void
handle_query(uint8_t * inbuf,ssize_t inlen,struct entry * entries,int * count,enum transport_type transport,void (* sendfunc)(uint8_t *,size_t,void *),void * userdata,FILE * verbose_out)1788 handle_query(uint8_t* inbuf, ssize_t inlen, struct entry* entries, int* count,
1789 	enum transport_type transport, void (*sendfunc)(uint8_t*, size_t, void*),
1790 	void* userdata, FILE* verbose_out)
1791 {
1792 	struct reply_packet *p;
1793 	uint8_t *outbuf = NULL;
1794 	size_t outlen = 0;
1795 	struct entry* entry = NULL;
1796 
1797 	verbose(1, "query %d: id %d: %s %d bytes: ", ++(*count),
1798 		(int)(inlen>=2?LDNS_ID_WIRE(inbuf):0),
1799 		(transport==transport_tcp)?"TCP":"UDP", (int)inlen);
1800 	if(verbose_out) {
1801 		char* out = sldns_wire2str_pkt(inbuf, (size_t)inlen);
1802 		printf("%s\n", out);
1803 		free(out);
1804 	}
1805 
1806 	/* fill up answer packet */
1807 	entry = find_match(entries, inbuf, (size_t)inlen, transport);
1808 	if(!entry || !entry->reply_list) {
1809 		verbose(1, "no answer packet for this query, no reply.\n");
1810 		return;
1811 	}
1812 	for(p = entry->reply_list; p; p = p->next)
1813 	{
1814 		verbose(3, "Answer pkt:\n");
1815 		if (p->reply_from_hex) {
1816 			/* try to adjust the hex packet, if it can be
1817 			 * parsed, we can use adjust rules. if not,
1818 			 * send packet literally */
1819 			/* still try to adjust ID if others fail */
1820 			outlen = sldns_buffer_limit(p->reply_from_hex);
1821 			outbuf = sldns_buffer_begin(p->reply_from_hex);
1822 		} else {
1823 			outbuf = p->reply_pkt;
1824 			outlen = p->reply_len;
1825 		}
1826 		if(!outbuf) {
1827 			verbose(1, "out of memory\n");
1828 			return;
1829 		}
1830 		/* copies outbuf in memory allocation */
1831 		adjust_packet(entry, &outbuf, &outlen, inbuf, (size_t)inlen);
1832 		verbose(1, "Answer packet size: %u bytes.\n", (unsigned int)outlen);
1833 		if(verbose_out) {
1834 			char* out = sldns_wire2str_pkt(outbuf, outlen);
1835 			printf("%s\n", out);
1836 			free(out);
1837 		}
1838 		if(p->packet_sleep) {
1839 			verbose(3, "sleeping for next packet %d secs\n",
1840 				p->packet_sleep);
1841 #ifdef HAVE_SLEEP
1842 			sleep(p->packet_sleep);
1843 #else
1844 			Sleep(p->packet_sleep * 1000);
1845 #endif
1846 			verbose(3, "wakeup for next packet "
1847 				"(slept %d secs)\n", p->packet_sleep);
1848 		}
1849 		sendfunc(outbuf, outlen, userdata);
1850 		free(outbuf);
1851 		outbuf = NULL;
1852 		outlen = 0;
1853 	}
1854 }
1855 
1856 /** delete the list of reply packets */
delete_replylist(struct reply_packet * replist)1857 void delete_replylist(struct reply_packet* replist)
1858 {
1859 	struct reply_packet *p=replist, *np;
1860 	while(p) {
1861 		np = p->next;
1862 		free(p->reply_pkt);
1863 		sldns_buffer_free(p->reply_from_hex);
1864 		sldns_buffer_free(p->raw_ednsdata);
1865 		free(p);
1866 		p=np;
1867 	}
1868 }
1869 
delete_entry(struct entry * list)1870 void delete_entry(struct entry* list)
1871 {
1872 	struct entry *p=list, *np;
1873 	while(p) {
1874 		np = p->next;
1875 		delete_replylist(p->reply_list);
1876 		free(p);
1877 		p = np;
1878 	}
1879 }
1880