xref: /netbsd-src/external/mpl/bind/dist/bin/tests/system/ans.pl (revision e6c7e151de239c49d2e38720a061ed9d1fa99309)
1#!/usr/bin/perl
2#
3# Copyright (C) Internet Systems Consortium, Inc. ("ISC")
4#
5# This Source Code Form is subject to the terms of the Mozilla Public
6# License, v. 2.0. If a copy of the MPL was not distributed with this
7# file, You can obtain one at http://mozilla.org/MPL/2.0/.
8#
9# See the COPYRIGHT file distributed with this work for additional
10# information regarding copyright ownership.
11
12#
13# This is the name server from hell.  It provides canned
14# responses based on pattern matching the queries, and
15# can be reprogrammed on-the-fly over a TCP connection.
16#
17# The server listens for queries on port 5300 (or PORT).
18#
19# The server listens for control connections on port 5301 (or EXTRAPORT1).
20#
21# A control connection is a TCP stream of lines like
22#
23#  /pattern/
24#  name ttl type rdata
25#  name ttl type rdata
26#  ...
27#  /pattern/
28#  name ttl type rdata
29#  name ttl type rdata
30#  ...
31#
32# There can be any number of patterns, each associated
33# with any number of response RRs.  Each pattern is a
34# Perl regular expression.  If an empty pattern ("//") is
35# received, the server will ignore all incoming queries (TCP
36# connections will still be accepted, but both UDP queries
37# and TCP queries will not be responded to).  If a non-empty
38# pattern is then received over the same control connection,
39# default behavior is restored.
40#
41# Each incoming query is converted into a string of the form
42# "qname qtype" (the printable query domain name, space,
43# printable query type) and matched against each pattern.
44#
45# The first pattern matching the query is selected, and
46# the RR following the pattern line are sent in the
47# answer section of the response.
48#
49# Each new control connection causes the current set of
50# patterns and responses to be cleared before adding new
51# ones.
52#
53# The server handles UDP and TCP queries.  Zone transfer
54# responses work, but must fit in a single 64 k message.
55#
56# Now you can add TSIG, just specify key/key data with:
57#
58#  /pattern <key> <key_data>/
59#  name ttl type rdata
60#  name ttl type rdata
61#
62#  Note that this data will still be sent with any request for
63#  pattern, only this data will be signed. Currently, this is only
64#  done for TCP.
65
66
67use IO::File;
68use IO::Socket;
69use Data::Dumper;
70use Net::DNS;
71use Net::DNS::Packet;
72use strict;
73
74# Ignore SIGPIPE so we won't fail if peer closes a TCP socket early
75local $SIG{PIPE} = 'IGNORE';
76
77# Flush logged output after every line
78local $| = 1;
79
80# We default to listening on 10.53.0.2 for historical reasons
81# XXX: we should also be able to specify IPv6
82my $server_addr = "10.53.0.2";
83if (@ARGV > 0) {
84	$server_addr = @ARGV[0];
85}
86
87my $mainport = int($ENV{'PORT'});
88if (!$mainport) { $mainport = 5300; }
89my $ctrlport = int($ENV{'EXTRAPORT1'});
90if (!$ctrlport) { $ctrlport = 5301; }
91
92# XXX: we should also be able to set the port numbers to listen on.
93my $ctlsock = IO::Socket::INET->new(LocalAddr => "$server_addr",
94   LocalPort => $ctrlport, Proto => "tcp", Listen => 5, Reuse => 1) or die "$!";
95
96my $udpsock = IO::Socket::INET->new(LocalAddr => "$server_addr",
97   LocalPort => $mainport, Proto => "udp", Reuse => 1) or die "$!";
98
99my $tcpsock = IO::Socket::INET->new(LocalAddr => "$server_addr",
100   LocalPort => $mainport, Proto => "tcp", Listen => 5, Reuse => 1) or die "$!";
101
102print "listening on $server_addr:$mainport,$ctrlport.\n";
103print "Using Net::DNS $Net::DNS::VERSION\n";
104
105my $pidf = new IO::File "ans.pid", "w" or die "cannot open pid file: $!";
106print $pidf "$$\n" or die "cannot write pid file: $!";
107$pidf->close or die "cannot close pid file: $!";;
108sub rmpid { unlink "ans.pid"; exit 1; };
109
110$SIG{INT} = \&rmpid;
111$SIG{TERM} = \&rmpid;
112
113#my @answers = ();
114my @rules;
115my $udphandler;
116my $tcphandler;
117
118sub handleUDP {
119	my ($buf) = @_;
120	my $request;
121
122	if ($Net::DNS::VERSION > 0.68) {
123		$request = new Net::DNS::Packet(\$buf, 0);
124		$@ and die $@;
125	} else {
126		my $err;
127		($request, $err) = new Net::DNS::Packet(\$buf, 0);
128		$err and die $err;
129	}
130
131	my @questions = $request->question;
132	my $qname = $questions[0]->qname;
133	my $qtype = $questions[0]->qtype;
134	my $qclass = $questions[0]->qclass;
135	my $id = $request->header->id;
136
137	my $packet = new Net::DNS::Packet($qname, $qtype, $qclass);
138	$packet->header->qr(1);
139	$packet->header->aa(1);
140	$packet->header->id($id);
141
142	# get the existing signature if any, and clear the additional section
143	my $prev_tsig;
144	while (my $rr = $request->pop("additional")) {
145		$prev_tsig = $rr if ($rr->type eq "TSIG");
146	}
147
148	my $r;
149	foreach $r (@rules) {
150		my $pattern = $r->{pattern};
151		my($dbtype, $key_name, $key_data) = split(/ /,$pattern);
152		print "[handleUDP] $dbtype, $key_name, $key_data \n";
153		if ("$qname $qtype" =~ /$dbtype/) {
154			my $a;
155			foreach $a (@{$r->{answer}}) {
156				$packet->push("answer", $a);
157			}
158			if(defined($key_name) && defined($key_data)) {
159				my $tsig;
160				# Sign the packet
161				print "  Signing the response with " .
162				      "$key_name/$key_data\n";
163
164				if ($Net::DNS::VERSION < 0.69) {
165					$tsig = Net::DNS::RR->new(
166						   "$key_name TSIG $key_data");
167				} else {
168					$tsig = Net::DNS::RR->new(
169							name => $key_name,
170							type => 'TSIG',
171							key  => $key_data);
172				}
173
174				# These kluges are necessary because Net::DNS
175				# doesn't know how to sign responses.  We
176				# clear compnames so that the TSIG key and
177				# algorithm name won't be compressed, and
178				# add one to arcount because the signing
179				# function will attempt to decrement it,
180				# which is incorrect in a response. Finally
181				# we set request_mac to the previous digest.
182				$packet->{"compnames"} = {}
183					if ($Net::DNS::VERSION < 0.70);
184				$packet->{"header"}{"arcount"} += 1
185					if ($Net::DNS::VERSION < 0.70);
186				if (defined($prev_tsig)) {
187					if ($Net::DNS::VERSION < 0.73) {
188						my $rmac = pack('n H*',
189							length($prev_tsig->mac)/2,
190							$prev_tsig->mac);
191						$tsig->{"request_mac"} =
192							unpack("H*", $rmac);
193					} else {
194						$tsig->request_mac(
195							 $prev_tsig->mac);
196					}
197				}
198
199				$packet->sign_tsig($tsig);
200			}
201			last;
202		}
203	}
204	#$packet->print;
205
206	return $packet->data;
207}
208
209# namelen:
210# given a stream of data, reads a DNS-formatted name and returns its
211# total length, thus making it possible to skip past it.
212sub namelen {
213	my ($data) = @_;
214	my $len = 0;
215	my $label_len = 0;
216	do {
217		$label_len = unpack("c", $data);
218		$data = substr($data, $label_len + 1);
219		$len += $label_len + 1;
220	} while ($label_len != 0);
221	return ($len);
222}
223
224# packetlen:
225# given a stream of data, reads a DNS wire-format packet and returns
226# its total length, making it possible to skip past it.
227sub packetlen {
228	my ($data) = @_;
229	my $q;
230	my $rr;
231	my $header;
232	my $offset;
233
234	#
235	# decode/encode were introduced in Net::DNS 0.68
236	# parse is no longer a method and calling it here makes perl croak.
237	#
238	my $decode = 0;
239	$decode = 1 if ($Net::DNS::VERSION >= 0.68);
240
241	if ($decode) {
242		($header, $offset) = Net::DNS::Header->decode(\$data);
243	} else {
244		($header, $offset) = Net::DNS::Header->parse(\$data);
245	}
246
247	for (1 .. $header->qdcount) {
248		if ($decode) {
249			($q, $offset) =
250				 Net::DNS::Question->decode(\$data, $offset);
251		} else {
252			($q, $offset) =
253				 Net::DNS::Question->parse(\$data, $offset);
254		}
255	}
256	for (1 .. $header->ancount) {
257		if ($decode) {
258			($q, $offset) = Net::DNS::RR->decode(\$data, $offset);
259		} else {
260			($q, $offset) = Net::DNS::RR->parse(\$data, $offset);
261		}
262	}
263	for (1 .. $header->nscount) {
264		if ($decode) {
265			($q, $offset) = Net::DNS::RR->decode(\$data, $offset);
266		} else {
267			($q, $offset) = Net::DNS::RR->parse(\$data, $offset);
268		}
269	}
270	for (1 .. $header->arcount) {
271		if ($decode) {
272			($q, $offset) = Net::DNS::RR->decode(\$data, $offset);
273		} else {
274			($q, $offset) = Net::DNS::RR->parse(\$data, $offset);
275		}
276	}
277	return $offset;
278}
279
280# sign_tcp_continuation:
281# This is a hack to correct the problem that Net::DNS has no idea how
282# to sign multiple-message TCP responses.  Several data that are included
283# in the digest when signing a query or the first message of a response are
284# omitted when signing subsequent messages in a TCP stream.
285#
286# Net::DNS::Packet->sign_tsig() has the ability to use a custom signing
287# function (specified by calling Packet->sign_func()).  We use this
288# function as the signing function for TCP continuations, and it removes
289# the unwanted data from the digest before calling the default sign_hmac
290# function.
291sub sign_tcp_continuation {
292	my ($key, $data) = @_;
293
294	# copy out first two bytes: size of the previous MAC
295	my $rmacsize = unpack("n", $data);
296	$data = substr($data, 2);
297
298	# copy out previous MAC
299	my $rmac = substr($data, 0, $rmacsize);
300	$data = substr($data, $rmacsize);
301
302	# try parsing out the packet information
303	my $plen = packetlen($data);
304	my $pdata = substr($data, 0, $plen);
305	$data = substr($data, $plen);
306
307	# remove the keyname, ttl, class, and algorithm name
308	$data = substr($data, namelen($data));
309	$data = substr($data, 6);
310	$data = substr($data, namelen($data));
311
312	# preserve the TSIG data
313	my $tdata = substr($data, 0, 8);
314
315	# prepare a new digest and sign with it
316	$data = pack("n", $rmacsize) . $rmac . $pdata . $tdata;
317	return Net::DNS::RR::TSIG::sign_hmac($key, $data);
318}
319
320sub handleTCP {
321	my ($buf) = @_;
322	my $request;
323
324	if ($Net::DNS::VERSION > 0.68) {
325		$request = new Net::DNS::Packet(\$buf, 0);
326		$@ and die $@;
327	} else {
328		my $err;
329		($request, $err) = new Net::DNS::Packet(\$buf, 0);
330		$err and die $err;
331	}
332
333	my @questions = $request->question;
334	my $qname = $questions[0]->qname;
335	my $qtype = $questions[0]->qtype;
336	my $qclass = $questions[0]->qclass;
337	my $id = $request->header->id;
338
339	my $opaque;
340
341	my $packet = new Net::DNS::Packet($qname, $qtype, $qclass);
342	$packet->header->qr(1);
343	$packet->header->aa(1);
344	$packet->header->id($id);
345
346	# get the existing signature if any, and clear the additional section
347	my $prev_tsig;
348	my $signer;
349	my $continuation = 0;
350	if ($Net::DNS::VERSION < 0.81) {
351		while (my $rr = $request->pop("additional")) {
352			if ($rr->type eq "TSIG") {
353				$prev_tsig = $rr;
354			}
355		}
356	}
357
358	my @results = ();
359	my $count_these = 0;
360
361	my $r;
362	foreach $r (@rules) {
363		my $pattern = $r->{pattern};
364		my($dbtype, $key_name, $key_data) = split(/ /,$pattern);
365		print "[handleTCP] $dbtype, $key_name, $key_data \n";
366		if ("$qname $qtype" =~ /$dbtype/) {
367			$count_these++;
368			my $a;
369			foreach $a (@{$r->{answer}}) {
370				$packet->push("answer", $a);
371			}
372			if (defined($key_name) && defined($key_data)) {
373				my $tsig;
374				# sign the packet
375				print "  Signing the data with " .
376				      "$key_name/$key_data\n";
377
378				if ($Net::DNS::VERSION < 0.69) {
379					$tsig = Net::DNS::RR->new(
380						   "$key_name TSIG $key_data");
381				} elsif ($Net::DNS::VERSION >= 0.81 &&
382					 $continuation) {
383				} elsif ($Net::DNS::VERSION >= 0.75 &&
384					 $continuation) {
385					$tsig = $prev_tsig;
386				} else {
387					$tsig = Net::DNS::RR->new(
388							name => $key_name,
389							type => 'TSIG',
390							key  => $key_data);
391				}
392
393				# These kluges are necessary because Net::DNS
394				# doesn't know how to sign responses.  We
395				# clear compnames so that the TSIG key and
396				# algorithm name won't be compressed, and
397				# add one to arcount because the signing
398				# function will attempt to decrement it,
399				# which is incorrect in a response. Finally
400				# we set request_mac to the previous digest.
401				$packet->{"compnames"} = {}
402					if ($Net::DNS::VERSION < 0.70);
403				$packet->{"header"}{"arcount"} += 1
404					if ($Net::DNS::VERSION < 0.70);
405				if (defined($prev_tsig)) {
406					if ($Net::DNS::VERSION < 0.73) {
407						my $rmac = pack('n H*',
408							length($prev_tsig->mac)/2,
409							$prev_tsig->mac);
410						$tsig->{"request_mac"} =
411							unpack("H*", $rmac);
412					} elsif ($Net::DNS::VERSION < 0.81) {
413						$tsig->request_mac(
414							 $prev_tsig->mac);
415					}
416				}
417
418				$tsig->sign_func($signer) if defined($signer);
419				$tsig->continuation($continuation) if
420					 ($Net::DNS::VERSION >= 0.71 &&
421					  $Net::DNS::VERSION <= 0.74 );
422				if ($Net::DNS::VERSION < 0.81) {
423					$packet->sign_tsig($tsig);
424				} elsif ($continuation) {
425					$opaque = $packet->sign_tsig($opaque);
426				} else {
427					$opaque = $packet->sign_tsig($request);
428				}
429				$signer = \&sign_tcp_continuation
430					if ($Net::DNS::VERSION < 0.70);
431				$continuation = 1;
432
433				my $copy =
434					Net::DNS::Packet->new(\($packet->data));
435				$prev_tsig = $copy->pop("additional");
436			}
437			#$packet->print;
438			push(@results,$packet->data);
439			$packet = new Net::DNS::Packet($qname, $qtype, $qclass);
440			$packet->header->qr(1);
441			$packet->header->aa(1);
442			$packet->header->id($id);
443		}
444	}
445	print " A total of $count_these patterns matched\n";
446	return \@results;
447}
448
449# Main
450my $rin;
451my $rout;
452for (;;) {
453	$rin = '';
454	vec($rin, fileno($ctlsock), 1) = 1;
455	vec($rin, fileno($tcpsock), 1) = 1;
456	vec($rin, fileno($udpsock), 1) = 1;
457
458	select($rout = $rin, undef, undef, undef);
459
460	if (vec($rout, fileno($ctlsock), 1)) {
461		warn "ctl conn";
462		my $conn = $ctlsock->accept;
463		my $rule = ();
464		@rules = ();
465		while (my $line = $conn->getline) {
466			chomp $line;
467			if ($line =~ m!^/(.*)/$!) {
468				if (length($1) == 0) {
469					$udphandler = sub { return; };
470					$tcphandler = sub { return; };
471				} else {
472					$udphandler = \&handleUDP;
473					$tcphandler = \&handleTCP;
474					$rule = { pattern => $1, answer => [] };
475					push(@rules, $rule);
476				}
477			} else {
478				push(@{$rule->{answer}},
479				     new Net::DNS::RR($line));
480			}
481		}
482		$conn->close;
483		#print Dumper(@rules);
484		#print "+=+=+ $rules[0]->{'pattern'}\n";
485		#print "+=+=+ $rules[0]->{'answer'}->[0]->{'rname'}\n";
486		#print "+=+=+ $rules[0]->{'answer'}->[0]\n";
487	} elsif (vec($rout, fileno($udpsock), 1)) {
488		printf "UDP request\n";
489		my $buf;
490		$udpsock->recv($buf, 512);
491		my $result = &$udphandler($buf);
492		if (defined($result)) {
493			my $num_chars = $udpsock->send($result);
494			print "  Sent $num_chars bytes via UDP\n";
495		}
496	} elsif (vec($rout, fileno($tcpsock), 1)) {
497		my $conn = $tcpsock->accept;
498		my $buf;
499		for (;;) {
500			my $lenbuf;
501			my $n = $conn->sysread($lenbuf, 2);
502			last unless $n == 2;
503			my $len = unpack("n", $lenbuf);
504			$n = $conn->sysread($buf, $len);
505			last unless $n == $len;
506			print "TCP request\n";
507			my $result = &$tcphandler($buf);
508			if (defined($result)) {
509				foreach my $response (@$result) {
510					$len = length($response);
511					$n = $conn->syswrite(pack("n", $len), 2);
512					$n = $conn->syswrite($response, $len);
513					print "    Sent: $n chars via TCP\n";
514				}
515			}
516		}
517		$conn->close;
518	}
519}
520