ans.pl 12.6 KB
Newer Older
1 2
#!/usr/bin/perl
#
Mark Andrews's avatar
Mark Andrews committed
3 4 5 6 7 8 9 10 11 12 13 14 15
# Copyright (C) 2011, 2012  Internet Systems Consortium, Inc. ("ISC")
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
# AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
# OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE.
16

Automatic Updater's avatar
Automatic Updater committed
17
# $Id: ans.pl,v 1.6 2012/02/22 23:47:34 tbox Exp $
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72

#
# This is the name server from hell.  It provides canned
# responses based on pattern matching the queries, and
# can be reprogrammed on-the-fly over a TCP connection.
#
# The server listens for control connections on port 5301.
# A control connection is a TCP stream of lines like
#
#  /pattern/
#  name ttl type rdata
#  name ttl type rdata
#  ...
#  /pattern/
#  name ttl type rdata
#  name ttl type rdata
#  ...
#
# There can be any number of patterns, each associated
# with any number of response RRs.  Each pattern is a
# Perl regular expression.
#
# Each incoming query is converted into a string of the form
# "qname qtype" (the printable query domain name, space,
# printable query type) and matched against each pattern.
#
# The first pattern matching the query is selected, and
# the RR following the pattern line are sent in the
# answer section of the response.
#
# Each new control connection causes the current set of
# patterns and responses to be cleared before adding new
# ones.
#
# The server handles UDP and TCP queries.  Zone transfer
# responses work, but must fit in a single 64 k message.
#
# Now you can add TSIG, just specify key/key data with:
#
#  /pattern <key> <key_data>/
#  name ttl type rdata
#  name ttl type rdata
#
#  Note that this data will still be sent with any request for
#  pattern, only this data will be signed. Currently, this is only
#  done for TCP.


use IO::File;
use IO::Socket;
use Data::Dumper;
use Net::DNS;
use Net::DNS::Packet;
use strict;

73 74 75 76 77 78
# Ignore SIGPIPE so we won't fail if peer closes a TCP socket early
local $SIG{PIPE} = 'IGNORE';

# Flush logged output after every line
local $| = 1;

79 80 81 82
# We default to listening on 10.53.0.2 for historical reasons
# XXX: we should also be able to specify IPv6
my $server_addr = "10.53.0.2";
if (@ARGV > 0) {
83
	$server_addr = @ARGV[0];
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
}

# XXX: we should also be able to set the port numbers to listen on.
my $ctlsock = IO::Socket::INET->new(LocalAddr => "$server_addr",
   LocalPort => 5301, Proto => "tcp", Listen => 5, Reuse => 1) or die "$!";

my $udpsock = IO::Socket::INET->new(LocalAddr => "$server_addr",
   LocalPort => 5300, Proto => "udp", Reuse => 1) or die "$!";

my $tcpsock = IO::Socket::INET->new(LocalAddr => "$server_addr",
   LocalPort => 5300, Proto => "tcp", Listen => 5, Reuse => 1) or die "$!";

print "listening on $server_addr:5300,5301.\n";

my $pidf = new IO::File "ans.pid", "w" or die "cannot open pid file: $!";
print $pidf "$$\n" or die "cannot write pid file: $!";
$pidf->close or die "cannot close pid file: $!";;
sub rmpid { unlink "ans.pid"; exit 1; };

$SIG{INT} = \&rmpid;
$SIG{TERM} = \&rmpid;

#my @answers = ();
my @rules;
sub handleUDP {
109
	my ($buf) = @_;
110
	my $request;
111

112 113 114 115 116 117 118 119
	if ($Net::DNS::VERSION > 0.68) {
		$request = new Net::DNS::Packet(\$buf, 0);
		$@ and die $@;
	} else {
		my $err;
		($request, $err) = new Net::DNS::Packet(\$buf, 0);
		$err and die $err;
	}
120

121 122 123 124 125
	my @questions = $request->question;
	my $qname = $questions[0]->qname;
	my $qtype = $questions[0]->qtype;
	my $qclass = $questions[0]->qclass;
	my $id = $request->header->id;
126

127 128 129 130
	my $packet = new Net::DNS::Packet($qname, $qtype, $qclass);
	$packet->header->qr(1);
	$packet->header->aa(1);
	$packet->header->id($id);
131

132 133 134 135 136 137 138
	# get the existing signature if any, and clear the additional section
	my $prev_tsig;
	while (my $rr = $request->pop("additional")) {
		if ($rr->type eq "TSIG") {
			$prev_tsig = $rr;
		}
	}
139

140 141 142
	my $r;
	foreach $r (@rules) {
		my $pattern = $r->{pattern};
143 144
		my($dbtype, $key_name, $key_data) = split(/ /,$pattern);
		print "[handleUDP] $dbtype, $key_name, $key_data \n";
145 146 147 148 149
		if ("$qname $qtype" =~ /$dbtype/) {
			my $a;
			foreach $a (@{$r->{answer}}) {
				$packet->push("answer", $a);
			}
150 151 152
			if(defined($key_name) && defined($key_data)) {
				# Sign the packet
				print "  Signing the response with " .
153 154 155 156 157 158 159 160 161 162 163 164
				      "$key_name/$key_data\n";
				my $tsig = Net::DNS::RR->
					new("$key_name TSIG $key_data");

				# These kluges are necessary because Net::DNS
				# doesn't know how to sign responses.  We
				# clear compnames so that the TSIG key and
				# algorithm name won't be compressed, and
				# add one to arcount because the signing
				# function will attempt to decrement it,
				# which is incorrect in a response. Finally
				# we set request_mac to the previous digest.
165 166 167 168
				$packet->{"compnames"} = {}
					if ($Net::DNS::VERSION < 0.70);
				$packet->{"header"}{"arcount"} += 1
					if ($Net::DNS::VERSION < 0.70);
169 170
				if (defined($prev_tsig)) {
					my $rmac = pack('n H*',
171
						length($prev_tsig->mac)/2,
172 173 174 175 176
						$prev_tsig->mac);
					$tsig->{"request_mac"} =
						unpack("H*", $rmac);
				}
				
177 178
				$packet->sign_tsig($tsig);
			}
179 180 181 182
			last;
		}
	}
	#$packet->print;
183

184
	return $packet->data;
185 186 187 188 189 190
}

# namelen:
# given a stream of data, reads a DNS-formatted name and returns its
# total length, thus making it possible to skip past it.
sub namelen {
191 192 193 194 195 196 197 198 199
	my ($data) = @_;
	my $len = 0;
	my $label_len = 0;
	do {
		$label_len = unpack("c", $data);
		$data = substr($data, $label_len + 1);
		$len += $label_len + 1;
	} while ($label_len != 0);
	return ($len);
200 201 202 203 204 205
}

# packetlen:
# given a stream of data, reads a DNS wire-format packet and returns
# its total length, making it possible to skip past it.
sub packetlen {
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
	my ($data) = @_;
	my $q;
	my $rr;
	my $header;
	my $offset;

	#
	# decode/encode were introduced in Net::DNS 0.68
	# parse is no longer a method and calling it here makes perl croak.
	#
	my $decode = 0;
	$decode = 1 if ($Net::DNS::VERSION >= 0.68);

	if ($decode) {
		($header, $offset) = Net::DNS::Header->decode(\$data);
	} else {
		($header, $offset) = Net::DNS::Header->parse(\$data);
	}
		
	for (1 .. $header->qdcount) {
		if ($decode) {
			($q, $offset) =
				 Net::DNS::Question->decode(\$data, $offset);
		} else {
			($q, $offset) =
				 Net::DNS::Question->parse(\$data, $offset);
		}
	}
	for (1 .. $header->ancount) {
		if ($decode) {
			($q, $offset) = Net::DNS::RR->decode(\$data, $offset);
		} else {
			($q, $offset) = Net::DNS::RR->parse(\$data, $offset);
		}
	}
	for (1 .. $header->nscount) {
		if ($decode) {
			($q, $offset) = Net::DNS::RR->decode(\$data, $offset);
		} else {
			($q, $offset) = Net::DNS::RR->parse(\$data, $offset);
		}
	}
	for (1 .. $header->arcount) {
		if ($decode) {
			($q, $offset) = Net::DNS::RR->decode(\$data, $offset);
		} else {
			($q, $offset) = Net::DNS::RR->parse(\$data, $offset);
		}
	}
	return $offset;
256 257 258 259 260 261 262 263 264 265 266 267 268 269
}

# sign_tcp_continuation:
# This is a hack to correct the problem that Net::DNS has no idea how
# to sign multiple-message TCP responses.  Several data that are included
# in the digest when signing a query or the first message of a response are
# omitted when signing subsequent messages in a TCP stream.
#
# Net::DNS::Packet->sign_tsig() has the ability to use a custom signing
# function (specified by calling Packet->sign_func()).  We use this
# function as the signing function for TCP continuations, and it removes
# the unwanted data from the digest before calling the default sign_hmac
# function.
sub sign_tcp_continuation {
270
	my ($key, $data) = @_;
271

272 273 274
	# copy out first two bytes: size of the previous MAC
	my $rmacsize = unpack("n", $data);
	$data = substr($data, 2);
275

276 277 278
	# copy out previous MAC
	my $rmac = substr($data, 0, $rmacsize);
	$data = substr($data, $rmacsize);
279

280 281 282 283
	# try parsing out the packet information
	my $plen = packetlen($data);
	my $pdata = substr($data, 0, $plen);
	$data = substr($data, $plen);
284

285 286 287 288
	# remove the keyname, ttl, class, and algorithm name
	$data = substr($data, namelen($data));
	$data = substr($data, 6);
	$data = substr($data, namelen($data));
289

290 291
	# preserve the TSIG data
	my $tdata = substr($data, 0, 8);
292

293 294 295
	# prepare a new digest and sign with it
	$data = pack("n", $rmacsize) . $rmac . $pdata . $tdata;
	return Net::DNS::RR::TSIG::sign_hmac($key, $data);
296 297 298 299
}

sub handleTCP {
	my ($buf) = @_;
300
	my $request;
301

302 303 304 305 306 307 308 309
	if ($Net::DNS::VERSION > 0.68) {
		$request = new Net::DNS::Packet(\$buf, 0);
		$@ and die $@;
	} else {
		my $err;
		($request, $err) = new Net::DNS::Packet(\$buf, 0);
		$err and die $err;
	}
310
	
311
	my @questions = $request->question;
312 313
	my $qname = $questions[0]->qname;
	my $qtype = $questions[0]->qtype;
314 315
	my $qclass = $questions[0]->qclass;
	my $id = $request->header->id;
316

317 318 319 320 321 322 323 324
	my $packet = new Net::DNS::Packet($qname, $qtype, $qclass);
	$packet->header->qr(1);
	$packet->header->aa(1);
	$packet->header->id($id);

	# get the existing signature if any, and clear the additional section
	my $prev_tsig;
	my $signer;
325
	my $continuation = 0;
326 327 328 329 330
	while (my $rr = $request->pop("additional")) {
		if ($rr->type eq "TSIG") {
			$prev_tsig = $rr;
		}
	}
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348

	my @results = ();
	my $count_these = 0;

	my $r;
	foreach $r (@rules) {
		my $pattern = $r->{pattern};
		my($dbtype, $key_name, $key_data) = split(/ /,$pattern);
		print "[handleTCP] $dbtype, $key_name, $key_data \n";
		if ("$qname $qtype" =~ /$dbtype/) {
			$count_these++;
			my $a;
			foreach $a (@{$r->{answer}}) {
				$packet->push("answer", $a);
			}
			if(defined($key_name) && defined($key_data)) {
				# sign the packet
				print "  Signing the data with " . 
349 350 351 352 353 354 355 356 357 358 359 360 361
				      "$key_name/$key_data\n";

				my $tsig = Net::DNS::RR->
					new("$key_name TSIG $key_data");

				# These kluges are necessary because Net::DNS
				# doesn't know how to sign responses.  We
				# clear compnames so that the TSIG key and
				# algorithm name won't be compressed, and
				# add one to arcount because the signing
				# function will attempt to decrement it,
				# which is incorrect in a response. Finally
				# we set request_mac to the previous digest.
362 363 364 365
				$packet->{"compnames"} = {}
					if ($Net::DNS::VERSION < 0.70);
				$packet->{"header"}{"arcount"} += 1
					if ($Net::DNS::VERSION < 0.70);
366 367
				if (defined($prev_tsig)) {
					my $rmac = pack('n H*',
368
						length($prev_tsig->mac)/2,
369 370 371 372 373 374
						$prev_tsig->mac);
					$tsig->{"request_mac"} =
						unpack("H*", $rmac);
				}
				
				$tsig->sign_func($signer) if defined($signer);
375 376
				$tsig->continuation($continuation)
					if ($Net::DNS::VERSION >= 0.71);
377
				$packet->sign_tsig($tsig);
378 379 380
				$signer = \&sign_tcp_continuation
					if ($Net::DNS::VERSION < 0.70);
				$continuation = 1;
381

382 383 384
				my $copy =
					Net::DNS::Packet->new(\($packet->data));
				$prev_tsig = $copy->pop("additional");
385 386 387
			}
			#$packet->print;
			push(@results,$packet->data);
388
			$packet = new Net::DNS::Packet($qname, $qtype, $qclass);
389 390
			$packet->header->qr(1);
			$packet->header->aa(1);
391
			$packet->header->id($id);
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
		}
	}
	print " A total of $count_these patterns matched\n";
	return \@results;
}

# Main
my $rin;
my $rout;
for (;;) {
	$rin = '';
	vec($rin, fileno($ctlsock), 1) = 1;
	vec($rin, fileno($tcpsock), 1) = 1;
	vec($rin, fileno($udpsock), 1) = 1;

	select($rout = $rin, undef, undef, undef);

	if (vec($rout, fileno($ctlsock), 1)) {
		warn "ctl conn";
		my $conn = $ctlsock->accept;
		my $rule = ();
		@rules = ();
		while (my $line = $conn->getline) {
			chomp $line;
			if ($line =~ m!^/(.*)/$!) {
				$rule = { pattern => $1, answer => [] };
				push(@rules, $rule);
			} else {
				push(@{$rule->{answer}},
				     new Net::DNS::RR($line));
			}
		}
		$conn->close;
425 426 427 428
		#print Dumper(@rules);
		#print "+=+=+ $rules[0]->{'pattern'}\n";
		#print "+=+=+ $rules[0]->{'answer'}->[0]->{'rname'}\n";
		#print "+=+=+ $rules[0]->{'answer'}->[0]\n";
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
	} elsif (vec($rout, fileno($udpsock), 1)) {
		printf "UDP request\n";
		my $buf;
		$udpsock->recv($buf, 512);
		my $result = handleUDP($buf);
		my $num_chars = $udpsock->send($result);
		print "  Sent $num_chars bytes via UDP\n";	
	} elsif (vec($rout, fileno($tcpsock), 1)) {
		my $conn = $tcpsock->accept;
		my $buf;
		for (;;) {
			my $lenbuf;
			my $n = $conn->sysread($lenbuf, 2);
			last unless $n == 2;
			my $len = unpack("n", $lenbuf);
			$n = $conn->sysread($buf, $len);
			last unless $n == $len;
			print "TCP request\n";
			my $result = handleTCP($buf);
			foreach my $response (@$result) {
				$len = length($response);
				$n = $conn->syswrite(pack("n", $len), 2);
				$n = $conn->syswrite($response, $len);
				print "    Sent: $n chars via TCP\n";
			}
		}
		$conn->close;
	}
}