1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 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 73 74 75 76 77 78 79 80 81 82 83 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 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 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 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 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 425 426 427 428 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 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
|
#!/usr/bin/perl
#
# mkrdns - Make Reverse DNS - Version 2.1
#
# By: Theo Van Dinter (felicity@mkrdns.org, tvd@colltech.com) (c) 1998-2001
# Revision Info: $Id: mkrdns,v 1.44 2001/07/12 15:13:44 felicity Stab $
#
# The goal of this script is to automatically generate new reverse IP
# mapping zone files for DNS/BIND. It's been done before, but there
# always seems to be something which makes it not workable in my
# environment. This script should hopefully fix that.
#
# Feel free to subscribe to the mkrdns mailing list by sending a message
# to "majordomo@mkrdns.org" with the message body "subscribe mkrdns <addr>".
# The list is available to discuss mkrdns-related topics (mkrdns, DNS,
# etc.) and is also used to announce new versions of mkrdns.
#
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
use strict;
use Getopt::Long;
use POSIX qw(strftime);
# User Specified variables (commandline)
my($debug) = 0; # display debugging information (user)
my($help) = 0; # help screen (user)
my($bootfile) = ""; # configuration file to use (user)
my($ext) = ""; # extension for output files (user)
my($quiet) = 0; # show errors only, or warnings too?
my($version) = 0; # show version information
my($rootdir) = "/"; # root directory for files
my($whichhash) = 1; # which hash function to use
# Program needed variables
my($i,@domains,%networks,%maps,%serial,%mips,%hash,%netmap,@toskip);
my(%zonetoskip,$nameddir,%numordate,%files,$toskip);
my($pversion) = "2.1";
# Get commandline parameters
$i=&GetOptions("debug" => \$debug,
"help|h" => \$help,
"extension=s" => \$ext,
"quiet" => \$quiet,
"version" => \$version,
"rootdir=s" => \$rootdir,
"hash=i" => \$whichhash,
"<>" => sub{$bootfile = $_[0]}, # any "non-option" is
# config (boot) file
);
if ( $version || !$i || $help ) {
print "
mkrdns v$pversion (c) 1998-2001
By: Theo Van Dinter (felicity\@mkrdns.org, tvd\@colltech.com)
";
print "Usage: $0 [options] [configuration file]
Options:
-debug\t\tTurn on debugging (warning, this prints a *LOT* of info)
-extension\tAppend given extension to output files
-hash\t\tSpecify which hash function to use (1=MD5,0=32bit Csum)
-help\t\tShow this help screen
-quiet\t\tTurn off warning messages (multiple A records -> IP, etc.)
-rootdir\tSpecify the root directory that named will run in (chroot)
-version\tShow the mkrdns version information
Configuration file is the full path to either named.boot or named.conf.
" unless ( $version );
exit 0;
}
if ( $ext =~ /^\./ ) { # Remove the '.'s from the start of the extention ...
$ext =~ s/^\.+//;
warn "(warn) Extension started with '.' -- removed. Extention now '$ext'.\n";
}
# Check for invalid hash function
if ( $whichhash != 0 && $whichhash != 1 ) {
die qq{(fatal) Invalid Hash function specified! ($whichhash)\n};
}
# Use MD5 if requested
if ( $whichhash == 1 ) {
use Digest::MD5 qw(md5_hex);
}
if ( $debug ) {
print "Debugging turned on.\n",
"Version = $pversion\n",
'C. Revision = $Id: mkrdns,v 1.44 2001/07/12 15:13:44 felicity Stab $',"\n",
"Help = $help\n",
"Quiet Mode = $quiet\n",
"Root Dir = $rootdir\n";
print "Extension = $ext\n" if ( $ext );
print "Hash Func = $whichhash (",
(($whichhash == 1) ? "MD5" :
($whichhash == 0 ) ? "32-bit checksum" :
"Unknown"),
")\n";
print "\n";
}
$rootdir = &FixPath($rootdir);
if ( $rootdir !~ m#^/# || $rootdir =~ m#^/?\.\.(/|$)# ) {
die qq{(fatal) Root directory ("$rootdir") is invalid.\n};
}
# If bootfile wasn't specified, try to find one in standard locations ...
unless ( $bootfile ) {
my($stdloc);
my(@locs) = qw{ /etc/bind /etc /var/named /usr/named
/usr/local/etc /usr/freeware/etc /etc/named };
warn "(warn) No configuration file specified. Checking in standard locations ...\n";
foreach $stdloc ( @locs ) {
opendir(DIR,$stdloc) || next;
my(@files) = grep( /^named\.(boot|conf)$/, readdir(DIR) );
closedir(DIR);
print "(debug) Config files found in $stdloc: ",join(",",@files),"\n" if ( $debug );
if ( $#files == -1 ) { # named.boot and named.conf weren't found, exit.
print qq{(debug) Neither named.boot nor named.conf were found in "$stdloc".\n} if ( $debug );
}
elsif ( $#files == 0 ) { # one file was found, use it.
$bootfile = "$stdloc/$files[0]";
warn "(info) $bootfile was found.\n";
}
else { # more than one file was found, use the "best" one.
$bootfile = "$stdloc/named.conf";
warn "(info) Multiple configuration files were found, using $bootfile.\n";
}
last if ( $bootfile );
}
die "(die) Couldn't find either named.boot or named.conf in any standard location. Exiting.\n" unless ( $bootfile );
}
READCONF: {
my($type) = ($bootfile=~/\.(\w+)$/); # what kind of config file (boot, conf, etc.)?
# neither boot nor conf -- start crying and exit.
if ( $type !~ /^(boot|conf)$/ ) {
die "(fatal) $bootfile is neither a boot nor conf file.\n";
}
# Read configuration file into memory.
my($config);
open(CONF,"<$bootfile") || die "(fatal) Can't open $bootfile:$!";
while ( $_ = <CONF> ) { # deal with the includes!
if ( (/^directory/i && $type eq "boot") ||
(/\bdirectory\s+"[^"]+";/ && $type eq "conf") ) {
$nameddir = (m/\bdirectory\s+\"?([^\"\s]+)\"?/i)[0];
print "(debug) Named Directory = $nameddir\n" if ( $debug );
}
if ( (/^\s*include\s/i && $type eq "boot") ||
(/\binclude\s+\"/i && $type eq "conf") ) { # include statement!
my(@conf) = ($_);
# (boot) ^include <file>
# (conf) ^include "<file>";
for(my($i)=0; $i<=$#conf; $i++) {
next unless ( $conf[$i] =~ /\binclude\s/i ); # skip non includes ...
chomp $conf[$i];
print "(debug) Include statement ($conf[$i]) found.\n" if ( $debug );
my($file) = ( $conf[$i] =~ m/\binclude\s+\"?([^\"\s]+)\"?/i );
$file =~ s/\s+//; # files shouldn't have whitespace ...
unless ( $file =~ m!^/! ) { # relative
unless ( $nameddir ) { # include before directory? boo!
$nameddir = ".";
warn qq{(warn) Include found before named directory was specified! Using ".".\n};
}
$file = "$nameddir/$file";
}
$file = &Handle_Path($rootdir,$file);
print "(debug) Including file $file.\n" if ( $debug );
open(IN,"<$file") || die "(fatal) Can't open $file:$!";
splice @conf, $i--, 1, <IN>; # replace include with data then recheck index
close(IN);
}
$config .= join("",@conf); # tack in included stuff ...
next;
}
$config .= $_; # append single line!
}
close(CONF);
print "(debug) Read in $bootfile.\n" if ( $debug );
# no directory statement anywhere?
die "(fatal) No named directory specified!\n" unless ( $nameddir );
if ( $type eq "boot" ) { # parse named.boot
# deal with directives
foreach ( grep(/^;\s*mkrdns\s+/, split(/\n/,$config)) ) {
s/^;\s*mkrdns\s+//;
&Directives($_);
}
foreach $i ( split(/\n/,$config) ) {
$i=~s/;.*$//; # remove comments
$i=~s/^\s+//; # remove whitespace
$i=~s/\s+$//;
if ( $i=~/^(primary|secondary)/i ) { # primary/secondary domain ...
my($type,$domain,$tmp,$file) =
($i=~/^(\S+)\s+(\S+)\s+(\S+\s+)?(\S+)\s*$/);
# Skip IP domains we don't control.
next if ( $type=~/^secondary$/i && $domain=~/\.arpa$/i );
&Handle_Domain($i,$type,$domain,$file,\%files);
}
}
}
elsif ( $type eq "conf" ) { # parse named.conf
my($directives) = ($config=~m!^/\*\s*mkrdns(.+?)\*/!msi);
if ( $directives ) { # mkrdns directive
foreach $i ( split(/\n/, $directives) ) {
$i=~s/\#.+$//;
$i=~s/^\s+//;
$i=~s/\s+$//;
next unless $i=~/\S/;
&Directives($i);
}
}
# Remove comments from config!
$config =~ s!/\*.*?\*/!!gs;
$config =~ s!//.*?\n!\n!gs;
$config =~ s!#.*?\n!\n!gs;
# determine which domains and networks we are master for.
# this first regexp is *REALLY* a pain.
foreach $i ( $config =~ m/\b(zone\s*".+?".*?{\s*type.+?;\s*file.+?;)/isg ) {
my($domain,$file) = ( $i=~/\"(.+?)\"/g );
my($type) = ( $i=~/type\s+(\S+?);/i );
# Skip non-master/slave zones
next unless ( $type =~ /master|slave/i );
# Skip IP zones we don't control.
next if ( $type=~/^slave$/i && $domain=~/\.arpa$/i );
&Handle_Domain($i,$type,$domain,$file,\%files);
}
}
}
# Take the array of regexs to skip and put them in a single var
$toskip = @toskip ? join("|",@toskip) : undef;
# Read in current reverse maps, report errors. Remember non-PTR lines
# for creation later on.
REVERSE: {
while ( my($net,$file) = each %networks ) {
open(IN,"<$file") || die qq{(fatal) Can't open "$file" for reading:$!};
seek(IN,0,0);
{
local $/=undef; # slurp mode
$hash{$net} = Do_Hash($whichhash,<IN>); # get the hash value for the original file
}
print "(debug) Generated hash value for $file: $hash{$net}.\n" if ( $debug );
print "(debug) Scanning $file for non-PTR lines:\n" if ( $debug );
seek(IN,0,0);
# strip out PTR, $GENERATE, $ORIGIN, and $INCLUDE ...
$maps{$net} = join("", grep(!/(\s+PTR\s+|^\$(ORIGIN|INCLUDE|GENERATE))/i, <IN>));
close(IN);
# Pick out the serial number ( should be YYYYMMDDVV )
($i = $maps{$net}) =~ s/\s*;.+?\n//g; # remove comments
($serial{$file}) = ( $i =~ m!\(\s*(\d+)!s );
if ( $debug ) { # print out non-PTR records (long...?)
foreach $i ( split(/\n/, $maps{$net}),
"Parsed serial number: $serial{$file}" ) {
print "(debug) $i\n";
}
}
}
}
# Read in current forward maps, convert A records into PTR records,
# add to map. If there are multiple A records for a given IP, report
# duplicate, and keep first.
#
# This routine is the biggest time suck...
#
READIN: {
foreach ( @domains ) {
my($domain,$map) = split(/:/,$_); # $domain = domain, $map = map file
my($last) = "$domain."; # what to use in case of blank hostname
# hostname, $ORIGIN, domain in that order
my($end) = $last; # what to use in case of relative hostname
# $ORIGIN then domain, in that order
print "(debug) Reading in entries from $map for domain $domain.\n"
if ( $debug );
my(@data);
open(IN,"<$map") || die "(fatal) Can't open $map:$!";
chomp(@data=<IN>); # slurp in map file w/out ending \n's
close(IN);
# deal with $INCLUDE and $GENERATE statements ...
print "(debug) Scanning for \$INCLUDE and \$GENERATE statements...\n" if ( $debug );
for($i=0; $i<=$#data; $i++) {
next unless ( $data[$i] =~ /^\$(INCLUDE|GENERATE)/ ); # skip non-include/generate lines
$data[$i]=~s/;.*$//; # remove comments & whitespace
$data[$i]=~s/\s+$//;
if ( $data[$i] =~ /^\$GENERATE/ ) {
print qq{(debug) "$data[$i]" specified.\n} if ( $debug );
# Set ORIGIN to blank -- we'll handle it later.
splice @data, $i, 1, &Handle_GENERATE("",$data[$i]);
}
elsif ( $data[$i] =~ /^\$INCLUDE/ ) {
# $INCLUDE <file> <origin>
my($inc,$file,$origin) = split(/\s+/,$data[$i]);
print qq{(debug) "$data[$i]" specified.\n} if ( $debug );
$file = "$nameddir/$file" unless ( $file =~ m!^/! );
$file = &Handle_Path($rootdir,$file);
my(@inc);
open(IN,"<$file") || die qq{(fatal) Can't read \$INCLUDE file "$file":$!};
chomp(@inc=<IN>);
close(IN);
if ( $origin ) { # specified origin applies only to specified
# include file. put appropriate sections at end
# of zone file. see BIND 3rd ed. p.146
# put $ORIGIN and included file at the end of the config
push(@data,"\$ORIGIN $origin", @inc);
splice @data, $i, 1; # remove $INCLUDE line
}
else { # just replace the $INCLUDE line with the contents of file
splice @data, $i, 1, @inc;
}
$i--; # rescan the line where the $INCLUDE was.
}
}
# the file should be fully expanded in memory now.
# go through all 'host ? ? ?' and $ORIGIN lines ...
foreach $i ( grep(/^(\S*(\s+\d+)?(\s+\w+)?\s+\S+\s+|\$ORIGIN)/i,@data) ) {
$i =~ s/\s*;.*$//; # strip comments ...
next unless ( length $i ); # skip blanks
if ( $i =~ /^\$ORIGIN/i ) { # $ORIGIN!
$end = (split(/\s+/,$i))[1];
$end .= ".$domain." if ( $end !~ /\.$/ ); # not FQDN
$last = lc $end;
print qq{(debug) "$i" specified. Final = "$last".\n} if ( $debug );
next;
}
# parse the line
my($host,$type,$ip) = ($i=~m!^(\S*)(?:\s+\d+)?(?:\s+\w+)?\s+(\w+)\s+(\S+)!);
$host = lc $host; # lowercase the host
$type = uc $type; # make sure the type (A,MX,etc) is uppercase
next unless ( $type ); # in SOA " 30 ; comment" ...
$host = $end if ( $host eq "@" ); # @ = ORIGIN
# what to do with host? interact with last if necessary ...
if ( $host eq "" ) { # it's a blank, use the last entry ...
$host = $last;
}
elsif ( $host !~ /\.$/ ) { # relative hostname
$last = $host = "$host.$end";
}
else { # FQDN!
$last = $host;
}
# This needs to stay here for proper " A 10.0.0.0"
# behavior -- DON'T MOVE ME (again) BAD BAD THEO!
next unless ( $type eq "A" ); # skip non-A records
# should we skip?
if ( defined $toskip && ($host=~/$toskip/o || $ip=~/$toskip/o) ) {
print "(debug) Skipping $host/$ip, matched toskip regexp ($toskip).\n" if ($debug);
next;
}
# do network mapping
if ( keys %netmap ) {
my($ipm) = &GenMask($ip);
foreach $i ( keys %netmap ) {
my($newnet,$netm,$mask) = @{$netmap{$i}};
unless ( ($ipm^$netm) & $mask ) { # 0 if in match made
my($ptr) = ( $ip =~ /\.(\d+)$/ );
print "(debug) $ip mapping to $newnet.$ptr ...\n" if ( $debug );
$ip = "$newnet.$ptr";
last; # IPs should only match once ...
}
}
}
# figure out which network this IP is in ...
my($network) = &IPinNetwork($ip,\%networks);
if ( $network == 0 ) {
print "(debug) Not keeping $host = $ip, not in any network.\n"
if ($debug);
next;
}
print "(debug) Keeping $host = $ip, in network $network.\n"
if ( $debug );
# the original may or may not be all numeric (maps)
my($orig,$ptr) = ( $ip =~ /^(.+)\.(\d+)$/ );
if ( exists($mips{$network}->{$orig}->{$ptr}) ) { # IP already has mapping!
print "The entry in \"$map\" for \"$host\" duplicated \"",$mips{$network}->{$orig}->{$ptr},"\".\nKeeping the original entry.\n"
unless ( $quiet );
next;
}
# Network/origin/ptr = host
$mips{$network}->{$orig}->{$ptr} = $host;
}
}
}
# Check each output zone file to see if it needs changing
HASH: {
while ( my($net,$file) = each %networks ) {
my($orig,$ptr);
my($map) = $maps{$net};
%{$mips{$net}} = () unless ( defined $mips{$net} ); # no IPs in net!
# Stole this from http://www.sysarch.com/perl/sort_paper.html
foreach $orig ( sort { pack('C*' => split(/\./,$a)) cmp
pack('C*' => split(/\./,$b))
} keys %{$mips{$net}} ) {
$map.= "\$ORIGIN ".join(".",reverse(split(/\./,$orig))).".in-addr.arpa.\n"; # append $ORIGIN to map
my $ptrs = $mips{$net}->{$orig};
foreach $ptr ( sort { $a <=> $b } keys %{$ptrs} ) {
# Add PTR line to map
$map.= "$ptr\tPTR\t".$ptrs->{$ptr}."\n";
}
}
my($hv) = Do_Hash($whichhash,$map); # generate hash value for new map
print "(debug) Generated hash values for $file (old/new): $hash{$net}/$hv.\n" if ( $debug );
if ( $hv ne $hash{$net} ) { # maps are different!
print "(debug) File $file needs to be updated.\n" if ( $debug );
my($fserial);
my($use) = $numordate{$files{$file}} ||
$numordate{"default"} ||
"date";
print "(debug) File $file uses serial type $use.\n" if ( $debug );
if ( $use eq "date" ) {
$fserial = &strftime("%Y%m%d00",localtime(time));
# if fserial > serial, then use fserial directly ...
if ( $fserial <= $serial{$file} ) { # serial is >= fserial, add 1 to serial and use it if possible
if ( $serial{$file} =~ /99$/ ) { # version 99! can't roll.
die qq#(fatal) Serial number $serial{$file} (file "$file") ends in 99 -- can't add 1! Freaky!\n#;
}
$fserial = $serial{$file} + 1;
}
}
elsif ( $use eq "number" ) {
$fserial = $serial{$file} + 1;
}
else {
die qq{(fatal) Unknown serial type "$use".};
}
warn "(warn) Serial number for $file is at max.\n"
if ( $fserial > 4294967294 );
print "(debug) Changing serial number for $file from",
" $serial{$file} to $fserial\n" if ( $debug );
$map =~ s/(\(.+?)$serial{$file}/$1$fserial/s;
$file .= ".$ext" if ( $ext ); # file or file.ext?
print "Updating file \"$file\"\n" unless ( $quiet );
open(OUT,">$file") || die "(fatal) Can't open $file for writing:$!";
print OUT $map;
close(OUT);
}
else {
print "File $file needs no modification.\n" unless ( $quiet );
}
}
}
exit 0;
# Is the given IP address in any of the specified networks?
# note: this routine only checks on byte boundaries
# Return 0 if not, network number if yes.
#
{ my %cache = ();
sub IPinNetwork {
my($ip,$networks)=@_; # IP to check, hash of networks to check
my($orig) = ( $ip =~ /^(.+)\.\d+$/ );
return $cache{$orig} if exists $cache{$orig};
do { # matches most specific network first (10.0.49 before 10 ...)
$ip =~ s/\.[^\.]+$//; # remove last octet (host #)
if ( exists $networks->{$ip} ) {
$cache{$orig} = $ip;
return $ip;
}
} while ( $ip =~ /\./ ); # while there's a period in the IP
return 0;
}
}
# Generate a bitmask from an IP/Network/bit count.
# Returns array of bitmasks from array of input values.
#
sub GenMask {
if ( $_[0] =~ /^\d+$/ ) { # /27 ...
return ~(2**(32-$_[0])-1);
}
else { # 255.255.255.224 ...
return unpack("N",pack('C4'=>split(/\./,$_[0])));
}
}
# Parse the directive statements and plop the info in the right place.
#
sub Directives {
my($type,$vals) = split(/\s+/, $_[0], 2);
print qq{(debug) mkrdns directive, type "$type", vals "$vals"\n} if ( $debug );
$type = lc $type;
if ( $type eq "map" ) {
my($nm,$nn) = split(/\s+/, $vals);
@{$netmap{$nm}}= ($nn,map { &GenMask($_) } split(/\//,$nm));
}
elsif ( $type eq "skip" ) {
push(@toskip,$vals);
}
elsif ( $type eq "skipzone" ) {
map { $zonetoskip{lc $_}=1 } split(/\s+/,$vals);
}
elsif ( $type eq "serialt" ) {
# $vals = "default|zone number|date"
$vals = lc $vals;
my($zone,$nord) = split(/\s+/,$vals,2);
die qq{(fatal) mkrdns directive "$type $vals" invalid.}
if ( $nord !~ /^(number|date)$/ );
$numordate{$zone} = $nord;
}
else {
die qq{(fatal) mkrdns directive type "$type" is unknown.};
}
}
# Generate actual lines from $GENERATE statements
# This routine should actually handle all $GENERATE types, although we're
# only going to use it for A records in mkrdns ...
#
sub Handle_GENERATE {
my($ORIGIN,$GENERATE) = @_;
my(@toreturn) = ();
# $RANGE is 'start-stop[/step]', all must be positive
# $LHS/$RHS:
# $ is replaced by iterator value.
# \$ is a $ at the end.
# $\{ is replaced by the iterator value and the actual { char.
# Append $ORIGIN if $RHS!~/\.$/
# ${offset} where offset defaults to "0,1,d".
# offset (integer),min width (0 padded),radix (doxX)
# $TYPE is A|AAAA|PTR|CNAME|NS
my($RANGE,$LHS,$TYPE,$RHS) = (split(/\s+/,$GENERATE))[1..4];
die qq{(fatal) Invalid \$GENERATE line: "$GENERATE"\n}
unless ( defined($RANGE) && defined($LHS) && defined($TYPE) &&
defined($RHS) );
$TYPE = uc $TYPE;
die qq{(fatal) Invalid \$GENERATE line (bad type): "$GENERATE"\n}
unless ( $TYPE =~ /^(A|AAAA|PTR|CNAME|NS)$/ );
my($START,$STOP,$SKIP) = ($RANGE=~m{^(\d+)-(\d+)(?:/(\d+))?$});
if ( !defined($SKIP) || ( defined($SKIP) && $SKIP<1 ) ) {
warn qq{(warn) Invalid \$GENERATE line (bad skip): "$GENERATE" (set to 1)\n}
if ( defined $SKIP );
$SKIP=1; # skip defaults to 1 if not specified.
}
die qq{(fatal) Invalid \$GENERATE line (non-pos value): "$GENERATE"\n}
unless ( $START > 0 && $STOP > 0 );
# Convert trouble-some combinations out of the way.
foreach ( $LHS, $RHS ) {
s/\$\\\{/\$\377/g; # $\{ -> $\377
s/\\\$/\376/g; # \$ -> \376
# Replace $ or ${...} w/ valid ${offset,width,radix} sections.
s@\$(?:{([^}]+)})?@
my($o,$w,$r) = split(/,/,$1);
if ( !defined($o) || $o!~/^-?\d+$/ ) {
warn qq{(warn) Invalid \$GENERATE line (bad offset): "$GENERATE" (set to 0)\n}
if ( defined($o) );
$o = 0;
}
if ( !defined($w) || $w<1 ) {
warn qq{(warn) Invalid \$GENERATE line (bad width): "$GENERATE" (set to 1)\n}
if ( defined($w) );
$w = 1;
}
if ( !defined($r) || $r !~ /^[doxX]$/ ) {
warn qq{(warn) Invalid \$GENERATE line (bad radix): "$GENERATE" (set to d)\n}
if ( defined($r) );
$r = "d";
}
"\${$o,$w,$r}";
@ge;
}
for(my($IT) = $START; $IT<=$STOP; $IT+=$SKIP) {
$_ = "$LHS $RHS";
# The only $'s left in the string should be iterator values.
s@\${([^}]+)}@
my($o,$w,$r) = split(/,/,$1);
sprintf "%0$w$r", $IT+$o;
@ge;
tr/\377\376/{$/; # Put the chars back to normal.
my($l,$r) = split;
if ( $ORIGIN ne "" ) {
# The right side of an A or AAAA record is an address...
foreach ( ($TYPE=~/^A/)?$l:($l,$r) ) {
$_ .= ".$ORIGIN" unless ( /\.$/ );
}
}
push(@toreturn,"$l $TYPE $r");
}
return @toreturn;
}
# This section of code takes in a line from the named configuration file and
# puts the info in the appropriate spots. This used to be in both the
# named.conf and named.boot handlers in the main set of code, but the code
# was exactly the same, so I put it here for maintainability.
#
sub Handle_Domain {
my($i,$type,$domain,$file,$files) = @_;
$domain = lc $domain;
if ( $zonetoskip{$domain} ) {
print "(debug) Skipping zone $domain, matched skipzone.\n" if ($debug);
next;
}
unless ( $domain && $file ) {
warn qq{(warn) Error with line "$i" in "$bootfile".\n};
next;
}
$file = "$nameddir/$file" if ( $file !~ m!^/! );
$file = &Handle_Path($rootdir,$file);
# The file is already being used!
die qq#(fatal) The zone file "$file" is being used by two zones! Error in config file!\n($files->{$file} and $domain ...)\n# if ( $files->{$file} );
$files->{$file} = $domain;
if ( $domain =~ /\.arpa$/i ) { # network
$domain =~ s/\.in-addr\.arpa$//i; # just the net ...
if ( $domain =~ /127$/ ) { # silently skip 127.*
print "(debug) Skipping $file for the 127.* network.\n"
if ( $debug );
next;
}
$domain = join( ".", reverse(split(/\./,$domain)) );
$networks{$domain} = $file;
print qq{(debug) Network "$domain", File "$file", Type "$type".\n} if ( $debug );
}
else { # "normal" domain, read in domains in order presented.
push(@domains,"$domain:$file");
print qq{(debug) Domain "$domain", File "$file", Type "$type".\n} if ( $debug );
}
}
# Trim down a path to a standardized form.
# ie: /path/../foo -> /foo
#
sub FixPath {
$_ = $_[0];
tr#/#/#s; # Remove multiple /'s
s#/\./#/#g; # /./ -> /
s#/\.$##; # remove /.$
s#(^|/)[^/]*/\.\./#/#g; # /[^/]/../ -> /
s#(^|/)[^/]*/\.\.$##g; # remove /..$
s#^\./##; # remove ^./
return $_;
}
# Take a given path, handle a possibly different root directory, then return
# it.
#
sub Handle_Path {
my($rootdir,$orig) = @_;
my($new) = &FixPath($orig);
if ( $new=~m#^/?\.\.(/|$)# ) {
warn qq{(warn) Path "$_" tries to go beyond root directory ("$new"). Removing.\n} unless ( $quiet );
$new=~s#^/?\.\.(/|$)##;
}
$new = &FixPath("$rootdir/$new");
if ( $orig ne $new ) {
print qq{(debug) Path changed from "$orig" to "$new".\n} if ( $debug );
$orig = $new;
}
return $orig;
}
sub Do_Hash {
my($hashfunc) = @_;
if ( $hashfunc == 1 ) { # MD5
return md5_hex($_[1]); # generate MD5 for text
}
elsif ( $hashfunc == 0 ) { # Built-in (32bit checksum)
return unpack("%32C*",$_[1])%65535; # generate 32-bit checksum for text
}
else { # Who the heck are you anyway?
die qq{(fatal) Unknown hash function "$hashfunc".\n};
}
}
__END__
=head1 NAME
mkrdns - MaKe Reverse DNS (auto generate PTR maps)
=head1 SYNOPSIS
mkrdns [options] [configuration file]
=head1 DESCRIPTION
mkrdns is a program designed to auto-generate reverse DNS maps (IN PTR
records). Some programs already accompany the BIND source package
that will do this kind of thing on a single domain or network basis.
mkrdns will read either a named.boot or named.conf file, figure out
which domains and networks to deal with, and then generate the reverse
maps.
You are deemed "in charge" of a network/domain if you are the primary
DNS for a reverse zone, or if you are either the primary or secondary
for a forward zone. The exception to this rule is that the 127.*
network is not auto-generated due to the "1 IN PTR localhost." issue.
=head1 OPTIONS
-debug Print debugging information. (this will
print a B<LOT> of information, be warned.)
-extension <ext> Append the given extension to the output
files. This is useful if you want to
have the reverse maps generated, but want
to check their contents before use.
-hash <hash> Allows you to override the default hash
function. (used to determine if a map
has changed) mkrdns will try to use
MD5 (1) if the Digest::MD5 Perl module is
installed. Otherwise, it'll default to
32-bit checksums (0).
-help The help screen.
-quiet Turn off warning messages (multiple A
records -> IP, etc.) Good for scripts,
but you probably want to check on what
the warnings report.
-rootdir <path> Specify the path to the root directory
that named will be running in. This
will handle anyone using a chrooted
environment for named. Everything except
the configuration file is assumed to be
under the new root.
-version Show mkrdns version information.
=head1 CONFIGURATION FILE
mkrdns reads the standard BIND configuration files I<named.boot> and
I<named.conf>. If you don't specify the full path to the file on the
command line, mkrdns assumes that one (or both) will exist in /etc and
will search for them. If none are found, the program exits. If one
is found, it is used. If both are found, named.conf is used.
=head1 DIRECTIVES
Directives are new in mkrdns since version 1.2. Think of directives
as configuration options for mkrdns which are simply comments to BIND.
The current directives are B<map>, B<serialt>, B<skip>, and B<skipzone>.
B<Map> allows you to map hosts to another network. This was designed in
for the purpose of handling DNS for a subnet of a class C network which
you do not control. (See the DNS & BIND O'Reilly and Associates book,
3rd Ed., pg. 215-218) Assume that you have 10.4.4.32/27 (ie: you have
the 32 IPs from 10.4.4.32 to 10.4.4.63 ...) You want to do reverse
mappings for those IPs, but you don't control 4.4.10.in-addr.arpa.
How do you do it? The solution is to become the master for another
zone (such as 32.4.4.10.in-addr.arpa. or 32-63.4.4.10.in-addr.arpa.),
and CNAME the correct reverse pointers to the ones you're in charge of.
The format for the directive is:
map <network/mask> <new network>
Ex: map 10.4.4.32/27 10.4.4.32-63
This maps all hosts between 10.4.4.32 and 10.4.4.63 to 10.4.4.32-63.32
to 10.4.4.32-63.63.
B<Serialt> will change mkrdns's behavior with the serial number for
certain zones. By default (and in all pre-1.6 versions of mkrdns),
the serial number is assumed to be in I<date> format (YYYYMMDDVV,
year/month/day/version). As of v1.6 you can force mkrdns to treat it as
a regular number instead. This allows for more than 100 zone changes
a day, and has a bit more flexibility depending on the environment.
The format for the directive is:
serialt <zone> <format>
<zone> is either "default" or the actual zone (ie: 0.0.0.10.in-addr.arpa).
<format> is either "date" or "number".
Ex: serialt 1.168.192.in-addr.arpa number
B<Skip> forces mkrdns to ignore certain hosts/IPs via regular
expression. The concept is that there are some IN A records that
you would like to skip and not create a reverse entry. Skip allows
this. (for instance, "foo IN A 10.4.4.32" and "mail IN A 10.4.4.32" both
exist, but you want to force foo as the reverse lookup and ignore mail.
The following example can do this for you.) Format:
skip <regular expression>
Ex: skip ^mail
This will skip any host (or IP) that matches the "^mail" regular
expression. The host is the FQDN, and the IP is before mapping (see
above).
B<Skipzone> forces mkrdns to ignore certain zones while processing the
named configuration file. A possible use for this is where you have
"bar.com" and "bar.net", and both of them should have the same host info
(ie: foo.bar.com and foo.bar.net both have the same records.) You want
"bar.com" to be the reverse lookup for the IPs used. So set the zone file
setting to the same file (bar.zone), and then add "skipzone bar.net".
B<NOTE:> The skipzone argument must match EXACTLY with the zone name
in the config file. B<NOTE:> You can specify multiple zones in the same
"skipzone" statement. (ie: "skipzone foo.com bar.com")
The format of a directive differs (sorry) between named.conf and
named.boot. UNIX-style comments (the hash mark then the comment) are
allowed.
=head2 named.boot directives
Directives look like a comment, so the format is simply:
; mkrdns <directive type> <parameters>
=head2 named.conf directives
To make directives more efficient with BIND 8, the format is slightly
different:
/* mkrdns
<directive type> <parameters>
...
*/
=head1 EXAMPLES
B<mkrdns -e new /etc/named.boot>
This will run mkrdns over the file /etc/named.boot. Output files will
be generated as <name>.new (i.e.: if the PTR zone file is called
160.zone, the output will be 160.zone.new.)
=head1 NOTES
I tend to use this script like a lint check. i.e.: Edit the proper
zone files, then run mkrdns.
As with most documentation, there are probably things that aren't mentioned
in the docs that the script does/assumes/etc. I apologize for any
inaccuracies/omissions. Let me know if there are any parts that have an
"issue", and I'll see if I can't straighten it out.
=head1 ASSUMPTIONS
- the <network>.zone reverse map files must already be created, and
have the appropriate information (SOA/NS records, etc.) in there.
This script will strip out any PTR records, and then add them back in.
(This means anything like blank lines and comments will be moved to the
top of the file.) $ORIGIN and $INCLUDE are striped as of mkrdns 1.3.
- you must be at least a secondary for all domains which reference IP
networks for which you're responsible. There is no means (currently
at least) to specify a PTR record for a non-existent A record, so this
script must have access to all A records that need to be "reversed".
- if you have more than 1 A record pointing to a specific IP, you can't
have both be the PTR record. This script takes the first A record it
sees as the one used for the PTR record. A warning is printed for any
additional entries. (While the RFCs don't prohibit multiple PTR records
for the same IP, I have yet to find anyone who can give me a good reason
to do it.)
- map serial numbers default to be in YYYYMMDDVV format. (YYYY = year,
MM = month, DD = day, VV = version (00-99). This script will convert
your serial number to this format if it's not already. I don't have too
many daily DNS changes, so the action for not being able to update the
serial number (ie: VV is at 99 and can't be increased) is to simply exit.
If this is going to cause a problem for you, you can use the serialt
directive to specify a zone (or the default) should treat the serial
number as a number instead of using the date format. Either way,
a problem will come up when the serial number reaches 4294967295 (max
value), but that's another story. (mkrdns will print a warning if this
is about to happen)
=head1 AUTHOR
Theo Van Dinter <felicity@mkrdns.org> <tvd@colltech.com>
=cut
|