xref: /netbsd-src/external/mpl/bind/dist/bin/tests/system/ans.pl (revision 9689912e6b171cbda866ec33f15ae94a04e2c02d)
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 NOTIMP <key> <key_data>/
69# /pattern NOTIMP/
70#
71# Return a NOTIMP response
72#
73# /pattern EDNS=NOTIMP <key> <key_data>/
74# /pattern EDNS=NOTIMP/
75#
76# Return a NOTIMP response to an EDNS request
77#
78# /pattern EDNS=FORMERR <key> <key_data>/
79# /pattern EDNS=FORMERR/
80#
81# Return a FORMERR response to an EDNS request
82#
83# /pattern bad-id <key> <key_data>/
84# /pattern bad-id/
85#
86# will add 50 to the message id of the response.
87
88
89use IO::File;
90use IO::Socket;
91use Data::Dumper;
92use Net::DNS;
93use Net::DNS::Packet;
94use strict;
95
96# Ignore SIGPIPE so we won't fail if peer closes a TCP socket early
97local $SIG{PIPE} = 'IGNORE';
98
99# Flush logged output after every line
100local $| = 1;
101
102# We default to listening on 10.53.0.2 for historical reasons
103# XXX: we should also be able to specify IPv6
104my $server_addr = "10.53.0.2";
105if (@ARGV > 0) {
106	$server_addr = @ARGV[0];
107}
108
109my $mainport = int($ENV{'PORT'});
110if (!$mainport) { $mainport = 5300; }
111my $ctrlport = int($ENV{'EXTRAPORT1'});
112if (!$ctrlport) { $ctrlport = 5301; }
113my $hmac_algorithm = $ENV{'DEFAULT_HMAC'};
114if (!defined($hmac_algorithm)) { $hmac_algorithm = "hmac-sha256"; }
115
116# XXX: we should also be able to set the port numbers to listen on.
117my $ctlsock = IO::Socket::INET->new(LocalAddr => "$server_addr",
118   LocalPort => $ctrlport, Proto => "tcp", Listen => 5, Reuse => 1) or die "$!";
119
120my $udpsock = IO::Socket::INET->new(LocalAddr => "$server_addr",
121   LocalPort => $mainport, Proto => "udp", Reuse => 1) or die "$!";
122
123my $tcpsock = IO::Socket::INET->new(LocalAddr => "$server_addr",
124   LocalPort => $mainport, Proto => "tcp", Listen => 5, Reuse => 1) or die "$!";
125
126print "listening on $server_addr:$mainport,$ctrlport.\n";
127print "Using Net::DNS $Net::DNS::VERSION\n";
128
129my $pidf = new IO::File "ans.pid", "w" or die "cannot open pid file: $!";
130print $pidf "$$\n" or die "cannot write pid file: $!";
131$pidf->close or die "cannot close pid file: $!";;
132sub rmpid { unlink "ans.pid"; exit 1; };
133
134$SIG{INT} = \&rmpid;
135$SIG{TERM} = \&rmpid;
136
137#my @answers = ();
138my @rules;
139my $udphandler;
140my $tcphandler;
141
142sub handleUDP {
143	my ($buf) = @_;
144	my $request;
145
146	if ($Net::DNS::VERSION > 0.68) {
147		$request = new Net::DNS::Packet(\$buf, 0);
148		$@ and die $@;
149	} else {
150		my $err;
151		($request, $err) = new Net::DNS::Packet(\$buf, 0);
152		$err and die $err;
153	}
154
155	my @questions = $request->question;
156	my $qname = $questions[0]->qname;
157	my $qtype = $questions[0]->qtype;
158	my $qclass = $questions[0]->qclass;
159	my $id = $request->header->id;
160
161	my $packet = new Net::DNS::Packet($qname, $qtype, $qclass);
162	$packet->header->qr(1);
163	$packet->header->aa(1);
164	$packet->header->id($id);
165
166	# get the existing signature if any, and clear the additional section
167	my $prev_tsig;
168	while (my $rr = $request->pop("additional")) {
169		$prev_tsig = $rr if ($rr->type eq "TSIG");
170	}
171
172	my $r;
173	foreach $r (@rules) {
174		my $pattern = $r->{pattern};
175		my($dbtype, $key_name, $key_data) = split(/ /,$pattern);
176		print "[handleUDP] $dbtype, $key_name, $key_data\n";
177		if ("$qname $qtype" =~ /$dbtype/) {
178			my $a;
179			foreach $a (@{$r->{answer}}) {
180				$packet->push("answer", $a);
181			}
182			if (defined($key_name) && defined($key_data)) {
183				my $tsig;
184				# Sign the packet
185				print "  Signing the response with " .
186				      "$key_name/$key_data\n";
187
188				if ($Net::DNS::VERSION < 0.69) {
189					$tsig = Net::DNS::RR->new(
190						   "$key_name TSIG $key_data");
191				} else {
192					$tsig = Net::DNS::RR->new(
193							name => $key_name,
194							algorithm => $hmac_algorithm,
195							type => 'TSIG',
196							key  => $key_data);
197				}
198
199				# These kluges are necessary because Net::DNS
200				# doesn't know how to sign responses.  We
201				# clear compnames so that the TSIG key and
202				# algorithm name won't be compressed, and
203				# add one to arcount because the signing
204				# function will attempt to decrement it,
205				# which is incorrect in a response. Finally
206				# we set request_mac to the previous digest.
207				$packet->{"compnames"} = {}
208					if ($Net::DNS::VERSION < 0.70);
209				$packet->{"header"}{"arcount"} += 1
210					if ($Net::DNS::VERSION < 0.70);
211				if (defined($prev_tsig)) {
212					if ($Net::DNS::VERSION < 0.73) {
213						my $rmac = pack('n H*',
214							length($prev_tsig->mac)/2,
215							$prev_tsig->mac);
216						$tsig->{"request_mac"} =
217							unpack("H*", $rmac);
218					} else {
219						$tsig->request_mac(
220							 $prev_tsig->mac);
221					}
222				}
223
224				$packet->sign_tsig($tsig);
225			}
226			last;
227		}
228	}
229	#$packet->print;
230
231	return $packet->data;
232}
233
234# namelen:
235# given a stream of data, reads a DNS-formatted name and returns its
236# total length, thus making it possible to skip past it.
237sub namelen {
238	my ($data) = @_;
239	my $len = 0;
240	my $label_len = 0;
241	do {
242		$label_len = unpack("c", $data);
243		$data = substr($data, $label_len + 1);
244		$len += $label_len + 1;
245	} while ($label_len != 0);
246	return ($len);
247}
248
249# packetlen:
250# given a stream of data, reads a DNS wire-format packet and returns
251# its total length, making it possible to skip past it.
252sub packetlen {
253	my ($data) = @_;
254	my $q;
255	my $rr;
256	my $header;
257	my $offset;
258
259	#
260	# decode/encode were introduced in Net::DNS 0.68
261	# parse is no longer a method and calling it here makes perl croak.
262	#
263	my $decode = 0;
264	$decode = 1 if ($Net::DNS::VERSION >= 0.68);
265
266	if ($decode) {
267		($header, $offset) = Net::DNS::Header->decode(\$data);
268	} else {
269		($header, $offset) = Net::DNS::Header->parse(\$data);
270	}
271
272	for (1 .. $header->qdcount) {
273		if ($decode) {
274			($q, $offset) =
275				 Net::DNS::Question->decode(\$data, $offset);
276		} else {
277			($q, $offset) =
278				 Net::DNS::Question->parse(\$data, $offset);
279		}
280	}
281	for (1 .. $header->ancount) {
282		if ($decode) {
283			($q, $offset) = Net::DNS::RR->decode(\$data, $offset);
284		} else {
285			($q, $offset) = Net::DNS::RR->parse(\$data, $offset);
286		}
287	}
288	for (1 .. $header->nscount) {
289		if ($decode) {
290			($q, $offset) = Net::DNS::RR->decode(\$data, $offset);
291		} else {
292			($q, $offset) = Net::DNS::RR->parse(\$data, $offset);
293		}
294	}
295	for (1 .. $header->arcount) {
296		if ($decode) {
297			($q, $offset) = Net::DNS::RR->decode(\$data, $offset);
298		} else {
299			($q, $offset) = Net::DNS::RR->parse(\$data, $offset);
300		}
301	}
302	return $offset;
303}
304
305# sign_tcp_continuation:
306# This is a hack to correct the problem that Net::DNS has no idea how
307# to sign multiple-message TCP responses.  Several data that are included
308# in the digest when signing a query or the first message of a response are
309# omitted when signing subsequent messages in a TCP stream.
310#
311# Net::DNS::Packet->sign_tsig() has the ability to use a custom signing
312# function (specified by calling Packet->sign_func()).  We use this
313# function as the signing function for TCP continuations, and it removes
314# the unwanted data from the digest before calling the default sign_hmac
315# function.
316sub sign_tcp_continuation {
317	my ($key, $data) = @_;
318
319	# copy out first two bytes: size of the previous MAC
320	my $rmacsize = unpack("n", $data);
321	$data = substr($data, 2);
322
323	# copy out previous MAC
324	my $rmac = substr($data, 0, $rmacsize);
325	$data = substr($data, $rmacsize);
326
327	# try parsing out the packet information
328	my $plen = packetlen($data);
329	my $pdata = substr($data, 0, $plen);
330	$data = substr($data, $plen);
331
332	# remove the keyname, ttl, class, and algorithm name
333	$data = substr($data, namelen($data));
334	$data = substr($data, 6);
335	$data = substr($data, namelen($data));
336
337	# preserve the TSIG data
338	my $tdata = substr($data, 0, 8);
339
340	# prepare a new digest and sign with it
341	$data = pack("n", $rmacsize) . $rmac . $pdata . $tdata;
342	return Net::DNS::RR::TSIG::sign_hmac($key, $data);
343}
344
345sub handleTCP {
346	my ($buf) = @_;
347	my $request;
348
349	if ($Net::DNS::VERSION > 0.68) {
350		$request = new Net::DNS::Packet(\$buf, 0);
351		$@ and die $@;
352	} else {
353		my $err;
354		($request, $err) = new Net::DNS::Packet(\$buf, 0);
355		$err and die $err;
356	}
357
358	my @questions = $request->question;
359	my $qname = $questions[0]->qname;
360	my $qtype = $questions[0]->qtype;
361	my $qclass = $questions[0]->qclass;
362	my $id = $request->header->id;
363	my @additional = $request->additional;
364	my $has_opt = 0;
365	foreach (@additional) {
366		$has_opt = 1 if (ref($_) eq 'Net::DNS::RR::OPT');
367	}
368
369	my $opaque;
370
371	my $packet = new Net::DNS::Packet($qname, $qtype, $qclass);
372	$packet->header->qr(1);
373	$packet->header->aa(1);
374	$packet->header->id($id);
375
376	# get the existing signature if any, and clear the additional section
377	my $prev_tsig;
378	my $signer;
379	my $continuation = 0;
380	if ($Net::DNS::VERSION < 0.81) {
381		while (my $rr = $request->pop("additional")) {
382			if ($rr->type eq "TSIG") {
383				$prev_tsig = $rr;
384			}
385		}
386	}
387
388	my @results = ();
389	my $count_these = 0;
390
391	my $r;
392	foreach $r (@rules) {
393		my $pattern = $r->{pattern};
394		my($dbtype, $key_name, $key_data, $tname) = split(/ /,$pattern);
395		print "[handleTCP] $dbtype, $key_name, $key_data, $tname \n";
396		if ("$qname $qtype" =~ /$dbtype/) {
397			$count_these++;
398			my $a;
399			my $done = 0;
400
401			while (defined($key_name) &&
402			       ($key_name eq "NOTIMP" || $key_name eq "EDNS=NOTIMP" ||
403				$key_name eq "EDNS=FORMERR" || $key_name eq "bad-id")) {
404
405				if (defined($key_name) && $key_name eq "NOTIMP") {
406					$packet->header->rcode('NOTIMP') if (!$done);
407					$key_name = $key_data;
408					($key_data, $tname) = split(/ /,$tname);
409					$done = 1;
410				}
411
412				if (defined($key_name) && $key_name eq "EDNS=NOTIMP") {
413					if ($has_opt) {
414						$packet->header->rcode('NOTIMP') if (!$done);
415						$done = 1;
416					}
417					$key_name = $key_data;
418					($key_data, $tname) = split(/ /,$tname);
419				}
420
421				if (defined($key_name) && $key_name eq "EDNS=FORMERR") {
422					if ($has_opt) {
423						$packet->header->rcode('FORMERR') if (!$done);
424						$done = 1;
425					}
426					$key_name = $key_data;
427					($key_data, $tname) = split(/ /,$tname);
428				}
429
430				if (defined($key_name) && $key_name eq "bad-id") {
431					$packet->header->id(($id+50)%0xffff);
432					$key_name = $key_data;
433					($key_data, $tname) = split(/ /,$tname);
434				}
435			}
436
437			if (!$done) {
438				foreach $a (@{$r->{answer}}) {
439					$packet->push("answer", $a);
440				}
441			}
442
443			if (defined($key_name) && defined($key_data)) {
444				my $tsig;
445				# sign the packet
446				print "  Signing the data with " .
447				      "$key_name/$key_data\n";
448
449				if ($Net::DNS::VERSION < 0.69) {
450					$tsig = Net::DNS::RR->new(
451						   "$key_name TSIG $key_data");
452					$tsig->algorithm = $hmac_algorithm;
453				} elsif ($Net::DNS::VERSION >= 0.81 &&
454					 $continuation) {
455				} elsif ($Net::DNS::VERSION >= 0.75 &&
456					 $continuation) {
457					$tsig = $prev_tsig;
458				} else {
459					$tsig = Net::DNS::RR->new(
460							name => $key_name,
461							algorithm => $hmac_algorithm,
462							type => 'TSIG',
463							key  => $key_data);
464				}
465
466				# These kluges are necessary because Net::DNS
467				# doesn't know how to sign responses.  We
468				# clear compnames so that the TSIG key and
469				# algorithm name won't be compressed, and
470				# add one to arcount because the signing
471				# function will attempt to decrement it,
472				# which is incorrect in a response. Finally
473				# we set request_mac to the previous digest.
474				$packet->{"compnames"} = {}
475					if ($Net::DNS::VERSION < 0.70);
476				$packet->{"header"}{"arcount"} += 1
477					if ($Net::DNS::VERSION < 0.70);
478				if (defined($prev_tsig)) {
479					if ($Net::DNS::VERSION < 0.73) {
480						my $rmac = pack('n H*',
481							length($prev_tsig->mac)/2,
482							$prev_tsig->mac);
483						$tsig->{"request_mac"} =
484							unpack("H*", $rmac);
485					} elsif ($Net::DNS::VERSION < 0.81) {
486						$tsig->request_mac(
487							 $prev_tsig->mac);
488					}
489				}
490
491				$tsig->sign_func($signer) if defined($signer);
492				$tsig->continuation($continuation) if
493					 ($Net::DNS::VERSION >= 0.71 &&
494					  $Net::DNS::VERSION <= 0.74 );
495				if ($Net::DNS::VERSION < 0.81) {
496					$packet->sign_tsig($tsig);
497				} elsif ($continuation) {
498					$opaque = $packet->sign_tsig($opaque);
499				} else {
500					$opaque = $packet->sign_tsig($request);
501				}
502				$signer = \&sign_tcp_continuation
503					if ($Net::DNS::VERSION < 0.70);
504				$continuation = 1;
505
506				my $copy =
507					Net::DNS::Packet->new(\($packet->data));
508				$prev_tsig = $copy->pop("additional");
509			}
510			#$packet->print;
511			push(@results,$packet->data);
512			last if ($done);
513			if ($tname eq "") {
514				$tname = $qname;
515			}
516			$packet = new Net::DNS::Packet($tname, $qtype, $qclass);
517			$packet->header->qr(1);
518			$packet->header->aa(1);
519			$packet->header->id($id);
520		}
521	}
522	print " A total of $count_these patterns matched\n";
523	return \@results;
524}
525
526# Main
527my $rin;
528my $rout;
529for (;;) {
530	$rin = '';
531	vec($rin, fileno($ctlsock), 1) = 1;
532	vec($rin, fileno($tcpsock), 1) = 1;
533	vec($rin, fileno($udpsock), 1) = 1;
534
535	select($rout = $rin, undef, undef, undef);
536
537	if (vec($rout, fileno($ctlsock), 1)) {
538		warn "ctl conn";
539		my $conn = $ctlsock->accept;
540		my $rule = ();
541		@rules = ();
542		while (my $line = $conn->getline) {
543			chomp $line;
544			if ($line =~ m!^/(.*)/$!) {
545				if (length($1) == 0) {
546					$udphandler = sub { return; };
547					$tcphandler = sub { return; };
548				} else {
549					$udphandler = \&handleUDP;
550					$tcphandler = \&handleTCP;
551					$rule = { pattern => $1, answer => [] };
552					push(@rules, $rule);
553				}
554			} else {
555				push(@{$rule->{answer}},
556				     new Net::DNS::RR($line));
557			}
558		}
559		$conn->close;
560		#print Dumper(@rules);
561		#print "+=+=+ $rules[0]->{'pattern'}\n";
562		#print "+=+=+ $rules[0]->{'answer'}->[0]->{'rname'}\n";
563		#print "+=+=+ $rules[0]->{'answer'}->[0]\n";
564	} elsif (vec($rout, fileno($udpsock), 1)) {
565		printf "UDP request\n";
566		my $buf;
567		$udpsock->recv($buf, 512);
568		my $result = &$udphandler($buf);
569		if (defined($result)) {
570			my $num_chars = $udpsock->send($result);
571			print "  Sent $num_chars bytes via UDP\n";
572		}
573	} elsif (vec($rout, fileno($tcpsock), 1)) {
574		my $conn = $tcpsock->accept;
575		my $buf;
576		for (;;) {
577			my $lenbuf;
578			my $n = $conn->sysread($lenbuf, 2);
579			last unless $n == 2;
580			my $len = unpack("n", $lenbuf);
581			$n = $conn->sysread($buf, $len);
582			last unless $n == $len;
583			print "TCP request\n";
584			my $result = &$tcphandler($buf);
585			if (defined($result)) {
586				foreach my $response (@$result) {
587					$len = length($response);
588					$n = $conn->syswrite(pack("n", $len), 2);
589					$n = $conn->syswrite($response, $len);
590					print "    Sent: $n chars via TCP\n";
591				}
592			}
593		}
594		$conn->close;
595	}
596}
597