1#!/usr/bin/perl 2# 3# Copyright (C) 2011, 2012 Internet Systems Consortium, Inc. ("ISC") 4# 5# Permission to use, copy, modify, and/or distribute this software for any 6# purpose with or without fee is hereby granted, provided that the above 7# copyright notice and this permission notice appear in all copies. 8# 9# THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH 10# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY 11# AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, 12# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM 13# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE 14# OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR 15# PERFORMANCE OF THIS SOFTWARE. 16 17# Id: ans.pl,v 1.2 2011/08/31 06:49:10 marka Exp 18 19# 20# This is the name server from hell. It provides canned 21# responses based on pattern matching the queries, and 22# can be reprogrammed on-the-fly over a TCP connection. 23# 24# The server listens for control connections on port 5301. 25# A control connection is a TCP stream of lines like 26# 27# /pattern/ 28# name ttl type rdata 29# name ttl type rdata 30# ... 31# /pattern/ 32# name ttl type rdata 33# name ttl type rdata 34# ... 35# 36# There can be any number of patterns, each associated 37# with any number of response RRs. Each pattern is a 38# Perl regular expression. 39# 40# Each incoming query is converted into a string of the form 41# "qname qtype" (the printable query domain name, space, 42# printable query type) and matched against each pattern. 43# 44# The first pattern matching the query is selected, and 45# the RR following the pattern line are sent in the 46# answer section of the response. 47# 48# Each new control connection causes the current set of 49# patterns and responses to be cleared before adding new 50# ones. 51# 52# The server handles UDP and TCP queries. Zone transfer 53# responses work, but must fit in a single 64 k message. 54# 55# Now you can add TSIG, just specify key/key data with: 56# 57# /pattern <key> <key_data>/ 58# name ttl type rdata 59# name ttl type rdata 60# 61# Note that this data will still be sent with any request for 62# pattern, only this data will be signed. Currently, this is only 63# done for TCP. 64 65 66use IO::File; 67use IO::Socket; 68use Data::Dumper; 69use Net::DNS; 70use Net::DNS::Packet; 71use strict; 72 73# Ignore SIGPIPE so we won't fail if peer closes a TCP socket early 74local $SIG{PIPE} = 'IGNORE'; 75 76# Flush logged output after every line 77local $| = 1; 78 79my $server_addr = "10.53.0.4"; 80 81my $udpsock = IO::Socket::INET->new(LocalAddr => "$server_addr", 82 LocalPort => 5300, Proto => "udp", Reuse => 1) or die "$!"; 83 84my $tcpsock = IO::Socket::INET->new(LocalAddr => "$server_addr", 85 LocalPort => 5300, Proto => "tcp", Listen => 5, Reuse => 1) or die "$!"; 86 87print "listening on $server_addr:5300.\n"; 88 89my $pidf = new IO::File "ans.pid", "w" or die "cannot open pid file: $!"; 90print $pidf "$$\n" or die "cannot write pid file: $!"; 91$pidf->close or die "cannot close pid file: $!";; 92sub rmpid { unlink "ans.pid"; exit 1; }; 93 94$SIG{INT} = \&rmpid; 95$SIG{TERM} = \&rmpid; 96 97#my @answers = (); 98my @rules; 99sub handleUDP { 100 my ($buf) = @_; 101 my $packet; 102 103 if ($Net::DNS::VERSION > 0.68) { 104 $packet = new Net::DNS::Packet(\$buf, 0); 105 $@ and die $@; 106 } else { 107 my $err; 108 ($packet, $err) = new Net::DNS::Packet(\$buf, 0); 109 $err and die $err; 110 } 111 112 $packet->header->qr(1); 113 $packet->header->aa(1); 114 115 my @questions = $packet->question; 116 my $qname = $questions[0]->qname; 117 my $qtype = $questions[0]->qtype; 118 119 # get the existing signature if any, and clear the additional section 120 my $prev_tsig; 121 while (my $rr = $packet->pop("additional")) { 122 if ($rr->type eq "TSIG") { 123 $prev_tsig = $rr; 124 } 125 } 126 127 my $r; 128 foreach $r (@rules) { 129 my $pattern = $r->{pattern}; 130 my($dbtype, $key_name, $key_data) = split(/ /,$pattern); 131 print "[handleUDP] $dbtype, $key_name, $key_data \n"; 132 if ("$qname $qtype" =~ /$dbtype/) { 133 my $a; 134 foreach $a (@{$r->{answer}}) { 135 $packet->push("answer", $a); 136 } 137 if(defined($key_name) && defined($key_data)) { 138 # Sign the packet 139 print " Signing the response with " . 140 "$key_name/$key_data\n"; 141 my $tsig = Net::DNS::RR-> 142 new("$key_name TSIG $key_data"); 143 144 # These kluges are necessary because Net::DNS 145 # doesn't know how to sign responses. We 146 # clear compnames so that the TSIG key and 147 # algorithm name won't be compressed, and 148 # add one to arcount because the signing 149 # function will attempt to decrement it, 150 # which is incorrect in a response. Finally 151 # we set request_mac to the previous digest. 152 $packet->{"compnames"} = {}; 153 $packet->{"header"}{"arcount"} += 1; 154 if (defined($prev_tsig)) { 155 my $rmac = pack('n H*', 156 $prev_tsig->mac_size, 157 $prev_tsig->mac); 158 $tsig->{"request_mac"} = 159 unpack("H*", $rmac); 160 } 161 162 $packet->sign_tsig($tsig); 163 } 164 last; 165 } 166 } 167 #$packet->print; 168 169 return $packet->data; 170} 171 172# namelen: 173# given a stream of data, reads a DNS-formatted name and returns its 174# total length, thus making it possible to skip past it. 175sub namelen { 176 my ($data) = @_; 177 my $len = 0; 178 my $label_len = 0; 179 do { 180 $label_len = unpack("c", $data); 181 $data = substr($data, $label_len + 1); 182 $len += $label_len + 1; 183 } while ($label_len != 0); 184 return ($len); 185} 186 187# packetlen: 188# given a stream of data, reads a DNS wire-format packet and returns 189# its total length, making it possible to skip past it. 190sub packetlen { 191 my ($data) = @_; 192 my $q; 193 my $rr; 194 195 my ($header, $offset) = Net::DNS::Header->parse(\$data); 196 for (1 .. $header->qdcount) { 197 ($q, $offset) = Net::DNS::Question->parse(\$data, $offset); 198 } 199 for (1 .. $header->ancount) { 200 ($rr, $offset) = Net::DNS::RR->parse(\$data, $offset); 201 } 202 for (1 .. $header->nscount) { 203 ($rr, $offset) = Net::DNS::RR->parse(\$data, $offset); 204 } 205 for (1 .. $header->arcount) { 206 ($rr, $offset) = Net::DNS::RR->parse(\$data, $offset); 207 } 208 return $offset; 209} 210 211# sign_tcp_continuation: 212# This is a hack to correct the problem that Net::DNS has no idea how 213# to sign multiple-message TCP responses. Several data that are included 214# in the digest when signing a query or the first message of a response are 215# omitted when signing subsequent messages in a TCP stream. 216# 217# Net::DNS::Packet->sign_tsig() has the ability to use a custom signing 218# function (specified by calling Packet->sign_func()). We use this 219# function as the signing function for TCP continuations, and it removes 220# the unwanted data from the digest before calling the default sign_hmac 221# function. 222sub sign_tcp_continuation { 223 my ($key, $data) = @_; 224 225 # copy out first two bytes: size of the previous MAC 226 my $rmacsize = unpack("n", $data); 227 $data = substr($data, 2); 228 229 # copy out previous MAC 230 my $rmac = substr($data, 0, $rmacsize); 231 $data = substr($data, $rmacsize); 232 233 # try parsing out the packet information 234 my $plen = packetlen($data); 235 my $pdata = substr($data, 0, $plen); 236 $data = substr($data, $plen); 237 238 # remove the keyname, ttl, class, and algorithm name 239 $data = substr($data, namelen($data)); 240 $data = substr($data, 6); 241 $data = substr($data, namelen($data)); 242 243 # preserve the TSIG data 244 my $tdata = substr($data, 0, 8); 245 246 # prepare a new digest and sign with it 247 $data = pack("n", $rmacsize) . $rmac . $pdata . $tdata; 248 return Net::DNS::RR::TSIG::sign_hmac($key, $data); 249} 250 251sub handleTCP { 252 my ($buf) = @_; 253 my $packet; 254 255 if ($Net::DNS::VERSION > 0.68) { 256 $packet = new Net::DNS::Packet(\$buf, 0); 257 $@ and die $@; 258 } else { 259 my $err; 260 ($packet, $err) = new Net::DNS::Packet(\$buf, 0); 261 $err and die $err; 262 } 263 264 $packet->header->qr(1); 265 $packet->header->aa(1); 266 267 my @questions = $packet->question; 268 my $qname = $questions[0]->qname; 269 my $qtype = $questions[0]->qtype; 270 271 # get the existing signature if any, and clear the additional section 272 my $prev_tsig; 273 my $signer; 274 while (my $rr = $packet->pop("additional")) { 275 if ($rr->type eq "TSIG") { 276 $prev_tsig = $rr; 277 } 278 } 279 280 my @results = (); 281 my $count_these = 0; 282 283 my $r; 284 foreach $r (@rules) { 285 my $pattern = $r->{pattern}; 286 my($dbtype, $key_name, $key_data) = split(/ /,$pattern); 287 print "[handleTCP] $dbtype, $key_name, $key_data \n"; 288 if ("$qname $qtype" =~ /$dbtype/) { 289 $count_these++; 290 my $a; 291 foreach $a (@{$r->{answer}}) { 292 $packet->push("answer", $a); 293 } 294 if(defined($key_name) && defined($key_data)) { 295 # sign the packet 296 print " Signing the data with " . 297 "$key_name/$key_data\n"; 298 299 my $tsig = Net::DNS::RR-> 300 new("$key_name TSIG $key_data"); 301 302 # These kluges are necessary because Net::DNS 303 # doesn't know how to sign responses. We 304 # clear compnames so that the TSIG key and 305 # algorithm name won't be compressed, and 306 # add one to arcount because the signing 307 # function will attempt to decrement it, 308 # which is incorrect in a response. Finally 309 # we set request_mac to the previous digest. 310 $packet->{"compnames"} = {}; 311 $packet->{"header"}{"arcount"} += 1; 312 if (defined($prev_tsig)) { 313 my $rmac = pack('n H*', 314 $prev_tsig->mac_size, 315 $prev_tsig->mac); 316 $tsig->{"request_mac"} = 317 unpack("H*", $rmac); 318 } 319 320 $tsig->sign_func($signer) if defined($signer); 321 $packet->sign_tsig($tsig); 322 $signer = \&sign_tcp_continuation; 323 324 my $copy = 325 Net::DNS::Packet->new(\($packet->data)); 326 $prev_tsig = $copy->pop("additional"); 327 } 328 #$packet->print; 329 push(@results,$packet->data); 330 $packet = new Net::DNS::Packet(\$buf, 0); 331 $packet->header->qr(1); 332 $packet->header->aa(1); 333 } 334 } 335 print " A total of $count_these patterns matched\n"; 336 return \@results; 337} 338 339# Main 340my $rin; 341my $rout; 342for (;;) { 343 $rin = ''; 344 vec($rin, fileno($tcpsock), 1) = 1; 345 vec($rin, fileno($udpsock), 1) = 1; 346 347 select($rout = $rin, undef, undef, undef); 348 349 if (vec($rout, fileno($udpsock), 1)) { 350 printf "UDP request\n"; 351 my $buf; 352 $udpsock->recv($buf, 512); 353 } elsif (vec($rout, fileno($tcpsock), 1)) { 354 my $conn = $tcpsock->accept; 355 my $buf; 356 for (;;) { 357 my $lenbuf; 358 my $n = $conn->sysread($lenbuf, 2); 359 last unless $n == 2; 360 my $len = unpack("n", $lenbuf); 361 $n = $conn->sysread($buf, $len); 362 } 363 sleep(1); 364 } 365} 366