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