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