Secondary request has now Reply-To set to the zone hostmaster
[sleuth.git] / sleuth
1 #!/usr/bin/perl -w
2 #
3 #       Sleuth -- A Simple DNS Checking Tool
4 #
5 #       (c) 1999--2001 Martin Mares <mj@ucw.cz>
6 #
7
8 # Load configuration file and all modules we need
9
10 BEGIN {
11         if (-f "/etc/sleuth.conf") {
12                 require "/etc/sleuth.conf";
13         } else {
14                 require __FILE__ . ".conf";
15         }
16 }
17
18 use Getopt::Std;
19 use Net::DNS::Resolver;
20
21 # Parse arguments
22
23 getopts('vmhp', \%opts) && (@ARGV >= 1 && @ARGV <= 3 || @ARGV == 5) || do {
24         print <<EOF
25 Usage: sleuth [-hmpv] <domain> [<server> [<server-IP> [<secondary> <secondary-ip>]]]
26
27 -h      Produce HTML output
28 -m      Produce machine-readable output
29 -p      Private network mode (avoid public accessibility checks)
30 -v      Be verbose
31 EOF
32 ;
33         exit 1;
34 };
35 $domain = norm_name($ARGV[0]);
36 $mode_submit = @ARGV == 5;
37 $check_ns = defined($ARGV[1]) ? norm_name($ARGV[1]) : "";
38 $check_ns_ip = defined($ARGV[2]) ? $ARGV[2] : "";
39 $our_name = defined($ARGV[3]) ? norm_name($ARGV[3]) : "";
40 $our_ip = defined($ARGV[4]) ? $ARGV[4] : "";
41
42 $verbose = $opts{"v"};
43 $private = $opts{"p"};
44 if ($opts{"m"}) { $output = \&plain_output; }
45 elsif ($opts{"h"}) { $output = \&html_output; }
46 else { $output = \&fancy_output; }
47
48 # Initialize reliable resolver using our local nameserver.
49
50 $rres = new Net::DNS::Resolver;
51 $rres->defnames(0);
52 $rres->dnsrch(0);
53 $rres->debug(0);
54 # FIXME: Net::DNS doesn't implement persistent vc's yet
55 #$rres->usevc(1);
56 #$rres->stayopen(1);
57
58 # And do the checks...
59
60 info("Starting zone checks for $domain");
61 $err_cnt = 0;
62 $warn_cnt = 0;
63 if ($mode_submit) {
64         check_zone_name();
65         check_submit();
66         check_ns_sanity();
67         check_zone() || msg("noserv", "No zone data available, giving up");
68 } else {
69         check_zone_name();
70         check_zone_basics();
71         $global_okay = 0;
72         foreach my $nsvr (@check_servers) {
73                 $nsvr =~ /(.*) = (.*)/;
74                 $check_ns = $1;
75                 $check_ns_ip = $2;
76                 info("Decided to use $check_ns ($check_ns_ip) for zone check");
77                 init_resolver($check_ns_ip);
78                 check_ns_sanity();
79                 if (check_zone()) {
80                         $global_okay = 1;
81                         last;
82                 }
83         }
84         $global_okay || msg("noserv", "No name server available for checking");
85 }
86 info("Summary: $err_cnt errors, $warn_cnt warnings");
87
88 exit ($err_cnt > 0);
89
90 # Output of messages
91
92 sub plain_output {
93         my $type = shift @_;
94         my $msg = shift @_;
95         my $ref = shift @_;
96         $ref = (defined $ref) ? " [RFC$ref]" : "";
97         print "$type $msg$ref\n";
98 }
99
100 sub fancy_output {
101         my $type = shift @_;
102         my $msg = shift @_;
103         my $ref = shift @_;
104         my $mmsg;
105         my %msg_types = %{{     'W' => '### Warning: ',
106                                 'E' => '### Error: ',
107                                 'F' => '### Fatal error: ',
108                                 '>' => '        ',
109                                 '*' => '        -> ',
110                                 '.' => ''
111                         }};
112         $mmsg = $msg_types{$type};
113         $ref = (defined $ref) ? " [RFC$ref]" : "";
114         print "$mmsg$msg$ref\n";
115 }
116
117 sub html_output {
118         my $type = shift @_;
119         my $msg = shift @_;
120         my $ref = shift @_;
121         if ($type =~ /[>*]/) {
122                 if (!$is_pre) { print "<PRE>"; $is_pre=1; }
123                 print "    ", ($type eq ">") ? "" : "-> ", $msg;
124         } else {
125                 if (!defined $is_pre) { print "<P>"; $is_pre=0; }
126                 elsif ($is_pre) { print "</PRE>"; $is_pre=0; }
127                 else { print "<BR>"; }
128                 if ($type =~ /[WEF]/) {
129                         my $map = {'W'=>'Warning', 'E'=>'Error', 'F'=>'Fatal error'};
130                         print "<em class=msg$type>### ", ${$map}{$type}, ": $msg", "</em>";
131                 } elsif ($type eq "." && $msg =~ /^Summary: /) {
132                         if ($msg !~ / 0 errors,/) { $msg =~ s/ (\d+) errors,/ <em class=msgE>$1 errors,<\/em>/; }
133                         if ($msg !~ / 0 warnings/) { $msg =~ s/ (\d+) warnings/ <em class=msgW>$1 warnings<\/em>/; }
134                         print $msg;
135                 } else { print $msg; }
136                 if (defined $ref) {
137                         my $comma = 0;
138                         print "&nbsp;&nbsp;[see";
139                         foreach my $z (split(/,\s*/, $ref)) {
140                                 my ($rfc, $url);
141                                 $comma++ && print ",";
142                                 if ($z =~ /(\d+)\/(.*)/) {
143                                         $rfc = "$1:$2";
144                                         $url = eval $rfc_sec_url;
145                                 } elsif ($z =~ /(\d+)/) {
146                                         $rfc = "$1";
147                                         $url = eval $rfc_url;
148                                 } else { die "Bad RFC reference"; }
149                                 print " <A HREF=\"$url\">RFC$rfc</A>";
150                         }
151                         print " for details]";
152                 }
153         }
154         print "\n";
155 }
156
157 sub msg {
158         my ($id, $msg, $ref) = @_;
159         defined $sev{$id} or die "Internal error: unknown message code <$id>";
160         my $type = $sev{$id};
161         return if $type eq "";
162         if (!$verbose) {
163                 if ($type =~ /[.>]/) { @msg_buffer = (); }
164                 elsif ($type =~ /[EWF]/ && @msg_buffer) {
165                         foreach my $m (@msg_buffer) { &{$output}('*', $m); }
166                         @msg_buffer = ();
167                 } elsif ($type eq '*') { push @msg_buffer, $msg; return; }
168         }
169         &{$output}($type, $msg, $ref);
170         if ($type eq "E") { $err_cnt++; }
171         elsif ($type eq "W") { $warn_cnt++; }
172         elsif ($type eq "F") { exit 1; }
173 }
174
175 sub info { msg('.', shift @_); }
176 sub rr_echo { my $rr=shift @_; msg('*', $rr->string); }
177
178 # Our interface to the resolver
179
180 sub try_resolve {
181         my $rver = shift @_;
182         my $name = shift @_;
183         my $type = shift @_;
184         my $need_aa = shift @_;
185         my $q = $rver->send($name, $type, "IN") or do {
186                 msg("reserr", $res->errorstring);
187                 return undef;
188         };
189         my $hdr = $q->header;
190         $hdr->tc && msg("dnserr", "Truncated response received");
191         my $rc = $hdr->rcode;
192         $rc eq "NXDOMAIN" and return undef;
193         $rc eq "NOERROR" or do { msg("reserr", "Unable to resolve $name: $rc"); return undef; };
194         $hdr->ancount || return undef;
195         !$need_aa || $hdr->aa || msg("needaa", "Answer is not authoritative");
196         return $q;
197 }
198
199 sub resolve {
200         my $name = shift @_;
201         my $type = shift @_;
202         my $allow_cnames = shift @_;
203         my $check_rev = shift @_;
204         my $need_aa = shift @_;
205         my @answer;
206         check_name($name) || return ();
207         if ($cache{$name}{$type}) {
208                 @answer = @{$cache{$name}{$type}};
209         } else {
210                 my $q = try_resolve($res, $name, $type, $need_aa);
211                 $q || return ();
212                 @answer = $q->answer;
213                 $cache{$name}{$type} = \@answer;
214         }
215         my @result = ();
216         my $cname_cnt = 0;
217         foreach my $r (@answer) {
218                 rr_echo($r);
219                 $r->class ne "IN" and next;
220                 if ($r->type eq "A") {
221                         # If it's an A record, automatically check it maps back.
222                         $check_rev && check_reverse($r->name, $r->address, "");
223                 }
224                 if ($r->type eq "CNAME") {
225                         if (!$allow_cnames) { msg("pcname", "DNS records must not point to CNAMEs", "1034/3.6, 1912/2.4, 2181/10.2-3"); }
226                         if ($cname_cnt) { msg("rcname", "CNAMEs must not point to CNAMEs", "1034/3.6, 1912/2.4, 2181/10.2-3"); }
227                         $cname_cnt++;
228                 }
229                 if ($r->type eq $type || $type eq "ANY") {
230                         # We shouldn't check minimum TTL here as we might have got a cached value
231                         ($r->ttl > 4*7*86400) && msg("suspttl", "Suspicious TTL value");
232                         push @result, $r;
233                 } elsif ($r->type ne "CNAME") {
234                         msg("unxtype", "Expected $type, got " . $r->type);
235                 }
236         }
237         return @result;
238 }
239
240 # Normalization and comparison of host names and IP addresses
241
242 sub same_ipa {
243         my $x = shift @_;
244         my $y = shift @_;
245         return $x eq $y;
246 }
247
248 sub norm_name {
249         my $n = shift @_;
250         $n =~ s/\.$//;
251         $n =~ tr[A-Z][a-z];
252         return $n;
253 }
254
255 sub same_name {
256         my $x = shift @_;
257         my $y = shift @_;
258         return norm_name($x) eq norm_name($y);
259 }
260
261 # Checks of reverse mapping
262
263 sub reverse_name {
264         my $addr = shift @_;
265         $addr =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/ or fatal("Unable to parse IP address $addr");
266         return "$4.$3.$2.$1.in-addr.arpa.";
267 }
268
269 sub check_reverse {
270         my $name = shift @_;
271         my $addr = shift @_;
272         my $allow_domain = shift @_;
273         my $rn = reverse_name($addr);
274         my $maps_back = "";
275         my $found_exact = 0;
276         my $warned = 0;
277         $did_reverse_check{$addr} && return;
278         $did_reverse_check{$addr} = 1;
279         ($addr =~ /^(192\.168|10|172\.(1[6-9]|2\d|3[01]))\./) && !$private &&
280                 msg("privadr", "Private addresses shouldn't occur in public zones", "1918");
281         foreach my $q (resolve("$rn", "PTR", 1, 0)) {
282                 my $dname = $q->ptrdname;
283                 if (same_name($dname, $name)) { $found_exact++; }
284                 else {
285                         my $matched = 0;
286                         foreach my $a (resolve("$dname", "A", 1, 0)) {
287                                 same_ipa($a->address, $addr) && ($matched = 1);
288                         }
289                         if (!$matched) {
290                                 $warned = 1;
291                                 msg("badrev", "$name maps to $dname which doesn't point back", "1912/2.1");
292                         }
293                         $maps_back = $dname;
294                 }
295         }
296         if (!$found_exact) {
297                 if ($maps_back eq "") { msg("norev", "$name ($addr) has no reverse record", "1912/2.1"); }
298                 elsif ($name ne $allow_domain && !$warned) {
299                         msg("inexrev", "$addr for $name points back to $maps_back", "1912/2.1");
300                 }
301         }
302 }
303
304 # Check of e-mail address
305
306 sub check_email {
307         my $e = shift @_;
308         $e =~ /@/ && do { msg("soamail", "'\@' in e-mail addresses should be encoded as '.'", "1912/2.2"); return; };
309         $e =~ /^(([^.\\]|\\.)+)\.(.*)$/ || do { msg("soamail", "Invalid e-mail address syntax"); return; };
310         my $user = $1;
311         my $host = norm_name($3);
312         $user =~ s/\\(.)/$1/g;
313         $e = "$user\@$host";
314         info("Hostmaster e-mail address is $e");
315         if (my @mx = resolve($host, "MX", 1, 0)) {
316                 foreach my $r (@mx) {
317                         resolve($r->exchange, "A", 0, 1) or msg("soammxa", "No A record for MX " . $r->exchange);
318                 }
319         } elsif (resolve($host, "A", 1, 0)) {
320                 msg("soaamx", "MX records should be used for mail routing");
321         } else {
322                 msg("soammx", "No MX record for $host");
323         }
324 }
325
326 # Check of name syntax
327
328 sub check_name {
329         my $n = shift @_;
330         $n =~ s/\.$//;
331         if ($n !~ /[^0-9.]/) {
332                 if ($n =~ /^(\d+\.){3}\d+$/) { msg("ipaname", "IP address found instead of name", "1912/2.1"); }
333                 else { msg("alldig", "All-digit names are not allowed", "1912/2.1"); }
334                 return 0;
335         }
336         if ($n =~ /^(.*)\.in-addr\.arpa$/i) {
337                 my $m = $1;
338                 if ($m !~ /^(\d+-\d+|\d+)(\/\d+)?(\.(\d+-\d+|\d+)(\/\d+)?)*$/) {
339                         msg("badrn", "Invalid name of reverse domain $n", "1035/3.5"); return 0;
340                 } elsif ($m =~ /(^|\.|-|\/)0[0-9]/) {
341                         msg("badrn", "Reverse names should not contain leading zeros", "1035/3.5"); return 0;
342                 }
343         }
344         $n =~ s/^\*\.//;
345         foreach my $q (split(/\./, $n)) {
346                 if ($q eq "") {
347                         msg("badname", "Name $n has empty components", "1912/2.1"); return 0;
348                 } elsif ($q !~ /^[0-9a-zA-Z_-]*$/) {
349                         msg("badname", "Name $n contains invalid characters", "1912/2.1"); return 0;
350                 }
351         }
352         return 1;
353 }
354
355 # Generic checks of nameserver configuration
356
357 sub check_ns_sanity {
358         # Check whether the nameserver is able to resolve its own address forth and back.
359
360         info("Checking whether $check_ns knows an A record for its own name");
361         my $ns_a = 0;
362         foreach $r (resolve($check_ns, "A", 0, 0)) {
363                 if (same_ipa($check_ns_ip, $r->address)) { $ns_a++; }
364         }
365         $ns_a || msg("selfa", "no matching A record found");
366
367         info("Checking whether $check_ns is able to reverse-map its own IP address");
368         check_reverse($check_ns, $check_ns_ip, "");
369
370         # General nameserver functionality checks
371
372         if (!$private) {
373                 info("Checking connectivity with other nameservers");
374                 foreach $name (@test_hosts) {
375                         resolve($name, "A", 1, 1) or
376                                 msg("recchk", "$check_ns is unable to resolve $name (maybe it's non-recursive)");
377                 }
378         }
379
380         info("Checking mapping of localhost");
381         $res->recurse(0);
382         if (@lh = resolve("localhost", "A", 1, 0, 1)) {
383                 (@lh != 1 || !same_ipa($lh[0]->address, "127.0.0.1")) &&
384                         msg("badloc", "Invalid resource records for localhost at $check_ns", "1912/4.1");
385         } else { msg("nolocal", "$check_ns is unable to resolve localhost", "1912/4.1"); }
386         resolve("1.0.0.127.in-addr.arpa", "PTR", 1, 0, 1) or msg("revloc", "Reverse mapping of 127.0.0.1 at $check_ns doesn't work", "1912/4.1");
387         $res->recurse(1);
388 }
389
390 # Zone name checks
391
392 sub check_zone_name {
393         info("Checking zone name");
394         check_name($domain);
395         if ($domain =~ /^(.*)\.in-addr\.arpa$/) {
396                 my $rev = $1;
397                 if ($rev =~ /(^|\.)(\d+(\.\d+){2})$/) {
398                         $rev_net = join('.', reverse split (/\./, $2)) . '.';
399                         info("Switched to reverse zone check mode for network $rev_net");
400                 } else {
401                         msg("unkrevz", "Switched to reverse mode, but unable to find network number in zone name", "1035/3.5");
402                 }
403                 $reverse = 1;
404         }
405 }
406
407 # Checks done for zone submission
408
409 sub check_submit {
410         # Test for bogus and forbidden names
411
412         ($domain =~ /(^|\.)([^.]+)\.([^.]+)$/) || msg("rtoplev", "Registration of top-level domains not supported");
413         $l2 = $2;
414         $l1 = $3;
415         try_resolve($rres, $l1, "SOA") || msg("utoplev", "Top level domain $l1 doesn't exist");
416         if (length($l2) <= 4 && ($q = try_resolve($rres, $l2, "SOA"))) {
417                 rr_echo($q->answer);
418                 msg("xtoplev", "Second-level domains must not use names of top-level domains");
419         }
420
421         # Test whether our NS is not already authoritative.
422
423         info("Checking for zone duplicity for $domain");
424         init_resolver($our_ip);
425         $res->recurse(0);
426         $q = try_resolve($res, $domain, "SOA");
427         ($q && $q->header->aa) && msg("alknown", "$domain already known at $our_name");
428
429         # Test whether the NS is authoritative for the zone.
430
431         init_resolver($check_ns_ip);
432         info("Checking for authoritative data for $domain");
433         $res->recurse(0);
434         $q = try_resolve($res, $domain, "SOA");
435         $q || msg("snauth", "SOA record for $domain not found");
436         $q->header->aa || msg("snauth", "$check_ns is not authoritative for $domain");
437         $res->recurse(1);
438
439         # Check number of name servers and whether we are one of them.
440
441         info("Checking list of nameservers");
442         @q = resolve($domain, "NS", 0, 1) or msg("missns", "No NS records for $domain found");
443         @q >= 2 || msg("twons", "Each domain should have at least 2 nameservers", "1912/2.8");
444         if (defined($our_name)) {
445                 $found_us = 0;
446                 foreach $r (@q) {
447                         same_name($r->nsdname, $our_name) && ($found_us = 1);
448                 }
449                 $found_us || msg("nosecns", "$our_name is not listed in NS records of $domain");
450         }
451 }
452
453 # Zone transfer and check
454
455 sub check_zone {
456
457 info("Fetching zone data for $domain");
458 if (!(@zone = $res->axfr($domain))) {
459         msg("axfer", "Zone transfer failed");
460         return 0;
461 }
462
463 info("Parsing zone data");
464 $rcnt=0;
465 foreach $r (@zone) {
466         $records{norm_name($r->name)}{$rcnt++} = $r;
467 }
468
469 info("Checking consistency of zone records");
470 $seen_localhost = 0;
471
472 foreach $name (sort { ($a eq $domain) ? -1 : ($b eq $domain) ? 1 : ($a cmp $b) } keys %records) {
473         $seen_cname = 0;
474         $seen_other = 0;
475         foreach $z (keys %{$records{$name}}) {
476                 $r = $records{$name}{$z};
477                 my $txt = $r->string;
478                 msg(">", $txt);
479                 defined $seen{$txt} && msg("duprec", "Duplicate record");
480                 $seen{$txt} = 1;
481                 check_name($name);
482                 ($r->ttl < 3600 || $r->ttl > 4*7*86400) && msg("suspttl", "Suspicious TTL value");
483                 $t = $r->type;
484                 $name =~ /(^|\.)$domain$/ || msg("outzone", "Out-of-zone record");
485                 if ($name =~ /\*/) {
486                         if ($t eq "SRV") {
487                                 # Wildcard SRV's are a useful thing
488                         } elsif ($t eq "A" || $t eq "CNAME") {
489                                 msg("wildac", "Wildcard A and CNAME records are likely to be very confusing", "1912/2.7");
490                         } else {
491                                 msg("wild", "Wildcard names are generally considered bad practice", "1912/2.7");
492                         }
493                 }
494                 if ($reverse) {
495                         ($name =~ /^(0|[1-9]\d*)\.$domain$/ && ($num = $1) < 256) ||
496                                 ($name eq $domain && $t ne "CNAME" && $t ne "PTR") ||
497                                 msg("badrevn", "Reverse zones should contain only numeric names");
498                         if ($t =~ /^(MX|WKS)$/) {
499                                 msg("badrevr", "Illegal record in reverse zone");
500                         } elsif ($t eq "A") {
501                                 msg("arev", "A records in reverse zones are valid, but considered bad practice", "1912/2.3");
502                         }
503                 } else {
504                         if ($t eq "PTR") {
505                                 msg("ptrfwd", "PTR records in forward zones are valid, but considered bad practice");
506                         }
507                 }
508                 if ($t eq "CNAME") {
509                         $seen_cname++;
510                         $d = norm_name($r->cname);
511                         # a.b.c -> a.b.c is wrong
512                         if (same_name($d, $name)) { msg("reccn", "Recursive CNAME", "1034/3.6"); }
513                         else {
514                                 # a.b.c -> x.a.b.c and a.b.c -> b.c are probably wrong as well, but not forbidden
515                                 if ($name =~ /(^|\.)$d/i || $d =~ /(^|\.)$name/) {
516                                         msg("suspcn", "Possibly incorrect overlapping CNAME");
517                                 }
518                                 if (!resolve($d, "ANY", 0, 1)) {
519                                         if ($reverse) {
520                                                 msg("dangcnr", "Unable to resolve CNAME destination (probably due to classless delegation)");
521                                         } else { msg("dangcn", "Unable to resolve CNAME destination"); }
522                                 }
523                         }
524                 } else { $seen_other++; }
525                 if (same_name($name, "localhost.$domain")) {
526                         if ($t eq "A" && same_ipa($r->address, "127.0.0.1")) { $seen_localhost++; next; }
527                         else { msg("badloc", "Invalid localhost record"); }
528                 }
529                 if ($t eq "A") {
530                         check_reverse($name, $r->address, $domain);
531                 } elsif ($t eq "NS") {
532                         $dest = $r->nsdname;
533                         resolve($dest, "A", 0, 1) || msg("missa", "Nameserver $dest doesn't have any valid A records");
534                 } elsif ($t =~ /^(MD|MF|MB|MG|MR)$/) {
535                         msg("obsrec", "MD/MF/MB/MG/MR records are obsolete and should not be used");
536                 } elsif ($t eq "SOA") {
537                         (same_name($name, $domain)) || do {
538                                 msg("supsoa", "Superfluous SOA record");
539                                 next;
540                         };
541                         resolve($r->mname, "A", 0, 1) || msg("soaorg", "No A record for zone origin");
542                         check_email($r->rname);
543                         ($r->expire < 2*7*86400 || $r->expire > 4*7*86400) &&
544                                 msg("suspexp", "Expire time should be between 2 and 4 weeks", "1912/2.2");
545                         ($r->minimum < 3600) && msg("suspmtl", "Suspicious minimum TTL", "2308/4");
546                 } elsif ($t eq "WKS") {
547                         msg("wks", "WKS record is obsolete and should not be used", "1912/2.6.1");
548                 } elsif ($t eq "PTR") {
549                         if (@dd = resolve($r->ptrdname, "A", 0, 0)) {
550                                 if (defined $rev_net) {
551                                         $found = 0;
552                                         foreach $rr (@dd) {
553                                                 (same_ipa($rr->address, $rev_net . $num)) && ($found=1);
554                                         }
555                                         $found || msg("ptrbada", "No corresponding A record found", "1912/2.4");
556                                 }
557                         } else { msg("ptrnoa", "PTR doesn't point to an A record", "1912/2.4"); }
558                 } elsif ($t eq "MX") {
559                         ($r->preference >= 0 && $r->preference < 65536) || msg("mxpref", "Invalid MX preference", "1035/3.3.9");
560                         $dest = $r->exchange;
561                         resolve($dest, "A", 0, 1) || msg("missa", "Mail exchanger $dest doesn't have any valid A records", "1035/3.3.9");
562                 } elsif ($t eq "SRV") {
563                         ($name =~ /^(\*|_[0-9a-zA-Z]+)\.(\*|_[a-zA-Z]+)\./) || msg("srvnam", "Invalid service name", "2782");
564                         ($r->priority >= 0 && $r->priority < 65536) || msg("srvpar", "Invalid SRV preference", "2782");
565                         ($r->weight >= 0 && $r->weight < 65536) || msg("srvpar", "Invalid SRV weight", "2872");
566                         ($r->port >= 0 && $r->port < 65536) || msg("srvpar", "Invalid SRV port number", "2872");
567                         $r->target eq "" || $r->target eq "." || resolve($r->target, "A", 0, 1) ||
568                                 msg("srvdest", "Service provider has no valid A record");
569                 }
570         }
571         if ($seen_cname > 1) {
572                 msg("cnclash", "Multiple CNAMEs for one name", "1912/2.4");
573         } elsif ($seen_cname && $seen_other) {
574                 msg("cnclash", "CNAME is not allowed to coexist with any other data", "1912/2.4");
575         }
576 }
577 return 1;
578 }
579
580 # Initialize resolver library, but point it to the nameserver given
581
582 sub init_resolver {
583         my $name = shift @_;
584         $res = new Net::DNS::Resolver;
585         $res->nameservers($name);
586         $res->recurse(1);
587         $res->defnames(0);
588         $res->dnsrch(0);
589         $res->debug(0);
590         # FIXME: Net::DNS doesn't implement persistent vc's yet
591         #$res->usevc(1);
592         #$res->stayopen(1);
593 }
594
595 # Basic zone checks -- existence, matching SOA versions and lame delegations
596 # returns @check_servers
597
598 sub check_zone_basics {
599         my $prefer_origin;
600
601         # In case check_ns is given, use it for initial checks, else use our local nameserver
602         if ($check_ns ne "") {
603                 if ($check_ns_ip eq "") {
604                         info("Resolving name-server address");
605                         $res = $rres;
606                         my @ips = resolve($check_ns, "A", 0, 0) or msg("nonsa", "$check_ns has no A record");
607                         $check_ns_ip = $ips[0]->address;
608                 }
609                 $prefer_origin = $check_ns;
610                 @check_servers = ( "$check_ns = $check_ns_ip" );
611                 init_resolver($check_ns_ip);
612                 $rres = $res;   # This one will be the reference
613         } else {
614                 $res = $rres;
615                 @check_servers = ();
616         }
617
618         info("Checking existence of zone");
619         resolve($domain, "CNAME", 1, 0) && msg("zcname", "$domain is a CNAME");
620         my @soa = resolve($domain, "SOA", 0, 0) or msg("znexist", "$domain doesn't exist");
621         my $real_origin = norm_name($soa[0]->mname);
622         defined $prefer_origin || ($prefer_origin = $real_origin);
623
624         info("Checking NS records");
625         my @ns = resolve($domain, "NS", 0, 0) or msg("missns", "$domain has no NS records");
626         (@ns >= 2) || msg("twons", "Each domain should have at least 2 nameservers", "1912/2.8");
627         @ns = map { norm_name($_->nsdname) } @ns;
628         my $nsnames = join(':', sort { $a cmp $b } @ns);
629         my %nshash;
630         foreach $r (@ns) { $nshash{$r} = 1; }
631         if (!defined $nshash{$real_origin}) { msg("ornotns", "Origin server $real_origin not listed in NS records"); }
632         delete $nshash{$prefer_origin};
633         @ns = keys %nshash;
634         unshift @ns, $prefer_origin;
635
636         info("Checking nameserver authority and synchronization");
637         my $psoa;
638         foreach $n (@ns) {
639                 my @nips;
640                 $res = $rres;
641                 if (!(@nips = resolve($n, "A", 0, 1))) {
642                         msg("missa", "Nameserver $n doesn't have any valid A records");
643                         next;
644                 }
645                 my $nip = $nips[0]->address;
646                 info("Probing name server $n ($nip)");
647                 init_resolver($nip);
648                 $res->recurse(0);
649                 my $q = try_resolve($res, $domain, "SOA");
650                 $res->recurse(1);
651                 $q && $q->header->aa || do { msg("lamer", "Lame delegation of $domain to $n", "1912/2.8"); next; };
652                 my @ss = resolve($domain, "SOA", 0, 0);
653                 if (!@ss) { msg("lamer", "Lame delegation of $domain to $n", "1912/2.8"); next; }
654                 my $ss = $ss[0];
655
656                 if ($check_ns eq "") { push @check_servers, "$n = $nip"; }
657                 if (defined $psoa) {
658                         my $delta = $psoa->serial - $ss->serial;
659                         ($delta >= 0x80000000) && ($delta -= 0x80000000);
660                         ($delta <= -0x80000000) && ($delta += 0x80000000);
661                         if ($delta > 0) { msg("oodsec", "$n has out of date data for $domain"); }
662                         elsif ($delta < 0) { msg("oodsec", "$n has newer data for $domain than zone origin"); }
663                         if ($psoa->mname ne $ss->mname ||
664                             $psoa->rname ne $ss->rname ||
665                             $psoa->refresh != $ss->refresh ||
666                             $psoa->retry != $ss->retry ||
667                             $psoa->expire != $ss->expire ||
668                             $psoa->minimum != $ss->minimum) {
669                                 msg("oodsoa", "$n lists different SOA parameters than zone origin");
670                         }
671                 } else { $psoa = $ss; }
672
673                 my $nsb = join(':', sort { $a cmp $b } map { $_->nsdname } resolve($domain, "NS", 0, 0));
674                 same_name($nsnames,$nsb) || msg("diffns", "Different set of NS records reported ($nsb)");
675         }
676         # info("Continuing zone checks on " . join("/", @check_servers));
677 }