dns.monitor 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. #!/usr/bin/perl
  2. #
  3. # Copyright (C) 1998 David Eckelkamp
  4. # Copyright (C) 2002-2006 Carnegie Mellon University
  5. #
  6. # This program is free software; you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation; either version 2 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program; if not, write to the Free Software
  18. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  19. #
  20. # $Id: dns.monitor,v 1.3 2006/09/05 12:52:37 vitroth Exp $
  21. #
  22. =head1 NAME
  23. dns.monitor - Monitor DNS servers for the "mon" system
  24. =head1 SYNOPSIS
  25. B<dns.monitor>
  26. =over 12
  27. ( [ I<-zone zone [-zone zone ...]>
  28. =over 4
  29. I<-master server [-master server ...]>
  30. I<[-serial_threshold num]>
  31. I<[-failsingle]> ]
  32. =back
  33. | [ I<-caching_only>
  34. =over 4
  35. I<-query record[:type[:value]] [-query record[:type[:value]] ...]> ] )
  36. =back
  37. I<[-tcp]>
  38. I<[-retry num]>
  39. I<[-retransmit num]>
  40. I<[-timeout num]>
  41. I<[-debug num]>
  42. I<server [server ...]>
  43. =back
  44. =head1 DESCRIPTION
  45. B<dns.monitor> will make several DNS queries to verify that a server is
  46. operating correctly
  47. In normal mode, B<dns.monitor> will compare the zones between a master
  48. server and one or more slave servers. The I<zone> argument is the
  49. zone to check. There can be multiple I<zone> arguments. The I<master>
  50. argument is the master server for the I<zone>. There can be multiple
  51. I<master> arguments. The master server(s) will be queried for the
  52. base information. If the I<serial_threshold> argument is provided,
  53. the serials collected from the I<master> servers are checked to be
  54. within I<serial_threshold>. The greatest serial of all of the
  55. I<master> servers is chosen for comparison. Then each I<server> will
  56. be queried to verify that it has the correct answers. If the
  57. I<serial_threshold> argument is provided, the slave servers must
  58. return a zone whose serial number is no more than the threshold from
  59. the serial number of the zone on the master. (Zone serial numbers may
  60. not be identical during zone propagation, or on Dynamic DNS zones
  61. which may be updated hundreds or thousands of times an hour) It is
  62. assumed that each I<server> is supposed to be authoritative for the
  63. I<zone>. The I<-tcp> option will cause lookups to be done via TCP
  64. instead of the default UDP.
  65. In caching mode, specified via the I<-caching_only> switch,
  66. B<dns.monitor> will perform a set of DNS queries to one or more
  67. servers. The I<query> argument is the query to perform. The query
  68. may have an optional query type specified as I<:type> on the end of
  69. the query. I.e your.zone.com:MX will cause B<dns.monitor> to fetch
  70. the MX records for your.zone.com. There can be multiple I<query>
  71. arguments. The query type may also have an optional result specified
  72. as I<:value> on the end of the query (type must also be specified).
  73. Each I<server> will be contacted to verify that it returns a valid
  74. response to the query. If a query result is specified B<dns.monitor>
  75. will return an error is the DNS query returns an answer which differs
  76. from the supplied result. If you wish to use B<dns.monitor> to verify
  77. that a caching DNS server is actually fetching fresh data from other
  78. servers successfully, it is recommended that the DNS records you query
  79. should have very short TTLs.
  80. The exit code of B<dns.monitor> will be the highest number of servers
  81. which failed on a single zone/query, 0 if no problems occurred, or -1
  82. if an error with the script arguments was detected. If all of the
  83. I<master> servers fail, the return code will be 252. If using the
  84. I<failsingle> option and any I<master> server fails, the return code
  85. will be 251.
  86. =head1 AUTHOR
  87. The script was originally written by David Eckelkamp <davide@tradewave.com>
  88. The script was modified to support Caching DNS servers, configurable
  89. retry/timeout parameters, multiple DNS Master servers, and
  90. configurable Zone serials by David Nolan <vitroth@cmu.edu> and Jason
  91. Carr <jcarr@andrew.cmu.edu> from Carnegie Mellon University.
  92. =cut
  93. use strict;
  94. use Getopt::Long;
  95. use English;
  96. use File::Basename;
  97. use Net::DNS::Resolver;
  98. use Net::DNS::Packet;
  99. use Net::DNS::RR;
  100. use Data::Dumper;
  101. my($Program) = basename($0);
  102. my(@Zones) = ();
  103. my(@Queries) = ();
  104. my(@Master) = ();
  105. my($SerialThreshold) = (0);
  106. my($CachingServer) = (0);
  107. my($UseTCP) = (0);
  108. my ($retries, $retrans, $timeout) = ( 2, 5, undef );
  109. my $debug = 0;
  110. my $failsingle = 0;
  111. my(%OptVars) = (
  112. "master" => \@Master,
  113. "zone" => \@Zones,
  114. "serial_threshold" => \$SerialThreshold,
  115. "caching_only" => \$CachingServer,
  116. "query" => \@Queries,
  117. "retry" => \$retries,
  118. "retransmit" => \$retrans,
  119. "timeout" => \$timeout,
  120. "tcp" => \$UseTCP,
  121. "debug" => \$debug,
  122. "failsingle" => \$failsingle
  123. );
  124. if (!GetOptions(\%OptVars, "master=s@", "zone=s@", "serial_threshold=s", "caching_only", "tcp", "query=s@", "retry=i", "retransmit=i", "timeout=i", "debug", "failsingle")) {
  125. print STDERR "Problems with Options, sorry\n";
  126. exit -1;
  127. }
  128. if ( $#ARGV < 0 ) {
  129. print STDERR "$Program: at least one server must be specified\n";
  130. usage();
  131. exit -1;
  132. }
  133. if (!$CachingServer) {
  134. if (! @Master) {
  135. print STDERR "$Program: The zone master server must be specified\n";
  136. usage();
  137. exit -1;
  138. }
  139. if (! @Zones) {
  140. print STDERR "$Program: At least one zone must be specified\n";
  141. usage();
  142. exit -1;
  143. }
  144. } else {
  145. if (! @Queries) {
  146. print STDERR "$Program: At least one query must be specified\n";
  147. usage();
  148. exit -1;
  149. }
  150. }
  151. if (!$CachingServer) {
  152. my($err_cnt) = 0;
  153. my($bad_servers, $reason, $failcount, @FailedZones, @FailedServers, @Reasons);
  154. my($zone, $line, $i);
  155. foreach $zone (@Zones) {
  156. ($bad_servers, $reason, $failcount) = dns_verify($zone, \@Master, \@ARGV);
  157. if (defined($bad_servers)) {
  158. $err_cnt = $failcount if ($failcount > $err_cnt);
  159. push(@FailedZones, $zone);
  160. push(@FailedServers, $bad_servers);
  161. push(@Reasons, $reason);
  162. }
  163. }
  164. @FailedServers=split(' ',join(" ",@FailedServers));
  165. my (@UniqFailedServers, %saw);
  166. @saw{@FailedServers} = ();
  167. @UniqFailedServers = keys %saw;
  168. if ($err_cnt > 0) {
  169. print join(" ", @UniqFailedServers);
  170. print "\n";
  171. # Now print the detail lines
  172. for ($i=0; $i<=$#FailedZones; $i++) {
  173. print "Zone '$FailedZones[$i]': failed servers: $FailedServers[$i]\n";
  174. print "Diagnostics:\n";
  175. foreach $line (split("\n", $Reasons[$i])) {
  176. print " $line\n";
  177. }
  178. print "\n";
  179. }
  180. }
  181. exit $err_cnt;
  182. } else {
  183. my($err_cnt) = 0;
  184. my($bad_servers, $reason, $failcount, @FailedQuerys, @FailedServers, @Reasons);
  185. my($query, $type, $line, $i, $target);
  186. foreach (@Queries) {
  187. ($query, $type, $target) = split /:/;
  188. $type = 'A' if ($type eq "");
  189. ($bad_servers, $reason, $failcount) = dns_test($query, $type, $target, @ARGV);
  190. if (defined($bad_servers)) {
  191. $err_cnt = $failcount if ($failcount > $err_cnt);
  192. push(@FailedQuerys, "$query $type") if (!$target);
  193. push(@FailedQuerys, "$query $type == $target $type") if ($target);
  194. push(@FailedServers, $bad_servers);
  195. push(@Reasons, $reason);
  196. }
  197. }
  198. @FailedServers=split(' ',join(" ",@FailedServers));
  199. my (@UniqFailedServers, %saw);
  200. @saw{@FailedServers} = ();
  201. @UniqFailedServers = keys %saw;
  202. if ($err_cnt > 0) {
  203. print join(" ", @UniqFailedServers);
  204. print "\n";
  205. # Now print the detail lines
  206. for ($i=0; $i<=$#FailedQuerys; $i++) {
  207. print "Query '$FailedQuerys[$i]': failed servers: $FailedServers[$i]\n";
  208. print "Diagnostics:\n";
  209. foreach $line (split("\n", $Reasons[$i])) {
  210. print " $line\n";
  211. }
  212. print "\n";
  213. }
  214. }
  215. exit $err_cnt;
  216. }
  217. # dns_verify($zone, \@master, \@Servers)
  218. # This subroutine takes 3 or more arguments. The first argument is the name of
  219. # the DNS zone/domain to check. The second argument is the name of the DNS
  220. # server you consider to be the master of the given zone. The subroutine
  221. # will make a DNS query to the the master to get the SOA for the zone and
  222. # extract the serial number. The third and rest of the arguments are taken as
  223. # names of slave DNS servers. Each server will be queried for the SOA of the
  224. # given zone and the serial number will be checked against that found in the
  225. # SOA record on the master server. By default the zone serials must be
  226. # the same. This may be overridden by the serial_threshold command line
  227. # argument.
  228. # The return value is a 3 element list. The first element is a space delimited
  229. # string containing the names of the slave servers that did not match the
  230. # master zone. The second element is a string containing the diagnostic
  231. # output that should explain the problem encountered. The third element is a count
  232. # of how many servers failed, which will be used as the exit code.
  233. sub dns_verify {
  234. # First verify that we have enough arguments.
  235. my($Zone) = shift;
  236. my(@Master) = @{shift()};
  237. my(@Servers) = @{shift()};
  238. my($result) = undef;
  239. my(@failed, $res, $soa_req, $Serial, $error_cnt, $server);
  240. my(%serials) = ();
  241. my(%errors) = ();
  242. # Query the $Master for the SOA of $Zone and get the serial number.
  243. $res = new Net::DNS::Resolver;
  244. $res->usevc(1) if ($UseTCP);
  245. $res->defnames(0); # don't append default zone
  246. $res->recurse(0); # no recursion
  247. $res->retry($retries); # retries before failure
  248. $res->retrans($retrans); # retransmission interval
  249. $res->udp_timeout($timeout); # set udp timeout
  250. $res->tcp_timeout($timeout); # set tcp timeout
  251. $error_cnt=0;
  252. # Loop through each master server
  253. foreach my $qs (@Master) {
  254. $res->nameservers($qs);
  255. $soa_req = $res->query($Zone, "SOA");
  256. if (!defined($soa_req) || ($soa_req->header->ancount <= 0)) {
  257. $error_cnt++;
  258. $errors{$qs} = sprintf("SOA query for $Zone from $qs failed %s\n", $res->errorstring);
  259. if ($res->errorstring eq 'NOERROR') {
  260. $errors{$qs} .= sprintf(" Empty answer received. (No zone on server?)\n")
  261. }
  262. if ($failsingle) { return ($qs, $errors{$qs}, 251); }
  263. next;
  264. }
  265. unless ($soa_req->header->aa) {
  266. $error_cnt++;
  267. $errors{$qs} = sprintf("$qs is not authoritative for $Zone\n");
  268. if ($failsingle) { return ($qs, $errors{$qs}, 251); }
  269. next;
  270. }
  271. unless ($soa_req->header->ancount == 1) {
  272. $error_cnt++;
  273. $errors{$qs} = sprintf("Too many answers for SOA query to %s for %s\n", $qs, $Zone);
  274. if ($failsingle) { return ($qs, $errors{$qs}, 251); }
  275. next;
  276. }
  277. unless (($soa_req->answer)[0]->type eq "SOA") {
  278. $error_cnt++;
  279. $errors{$qs} = printf("Query for SOA for %s from %s failed: " . "return type = %s\n", $Zone, $qs, ($soa_req->answer)[0]->type);
  280. if ($failsingle) { return ($qs, $errors{$qs}, 251); }
  281. next;
  282. }
  283. $serials{$qs} = ($soa_req->answer)[0]->serial;
  284. }
  285. if ($debug >= 2) {
  286. print Data::Dumper->Dump([\%serials], ['serials']);
  287. }
  288. if ($error_cnt == scalar @Master) {
  289. # all masters errored
  290. return("", values %errors, 251);
  291. }
  292. my $maxvalue = undef;
  293. my $minvalue = undef;
  294. my $maxkey = undef;
  295. my $minkey = undef;
  296. foreach my $key (keys %serials) {
  297. if ($serials{$key} > $maxvalue) {
  298. $maxvalue = $serials{$key};
  299. $maxkey = $key;
  300. }
  301. if (($serials{$key} < $minvalue) || (!defined $minkey)) {
  302. $minvalue = $serials{$key};
  303. $minkey = $key;
  304. }
  305. }
  306. if (abs($maxvalue - $minvalue) > $SerialThreshold) {
  307. return ($minkey, "\nQuery to $minkey about $Zone failed\n" .
  308. "Serial number = $minvalue, should have been $maxvalue\n", 252)
  309. }
  310. $Serial = $maxvalue;
  311. return ("", "\nNo SOA Serial found for $Zone!?!?", 252) if (!$Serial);
  312. # Now, foreach server given on the command line, get the serial number from
  313. # the SOA and compare it to the master.
  314. $error_cnt = 0;
  315. foreach $server (@Servers) {
  316. $res = new Net::DNS::Resolver;
  317. $res->usevc(1) if ($UseTCP);
  318. $res->defnames(0); # don't append default zone
  319. $res->recurse(0); # no recursion
  320. $res->retry($retries);
  321. $res->retrans($retrans);
  322. $res->udp_timeout($timeout);
  323. $res->tcp_timeout($timeout);
  324. $res->nameservers($server);
  325. $soa_req = $res->query($Zone, "SOA");
  326. if (!defined($soa_req) || ($soa_req->header->ancount <= 0)) {
  327. $error_cnt++;
  328. push(@failed, $server);
  329. $result .= sprintf("\nSOA query for $Zone from $server failed %s\n",
  330. $res->errorstring);
  331. if ($res->errorstring eq 'NOERROR') {
  332. $result .= sprintf(" Empty answer received. (No zone on server?)\n");
  333. }
  334. next;
  335. }
  336. unless($soa_req->header->aa
  337. && $soa_req->header->ancount == 1
  338. && ($soa_req->answer)[0]->type eq "SOA"
  339. && ((abs(($soa_req->answer)[0]->serial - $Serial)) <= $SerialThreshold)) {
  340. $error_cnt++;
  341. push(@failed, $server);
  342. $result .= sprintf("\nQuery to $server about $Zone failed\n" .
  343. "Authoritative = %s\n" .
  344. "Answer count = %d\n" .
  345. "Answer Type = %s\n" .
  346. "Serial number = %s, should have been %s\n" ,
  347. $soa_req->header->aa ? "yes" : "no",
  348. $soa_req->header->ancount,
  349. ($soa_req->answer)[0]->type,
  350. ($soa_req->answer)[0]->serial,
  351. $Serial);
  352. next;
  353. }
  354. }
  355. if ($error_cnt == 0) {
  356. return(undef, undef, undef);
  357. } else {
  358. return("@failed", $result, $error_cnt);
  359. }
  360. }
  361. # dns_test($query, $type, $target, $server, ...)
  362. # This subroutine takes 4 or more arguments. The first argument is the name of
  363. # the DNS record to query. The second argument is the type of the DNS
  364. # query to perform. The third argument is the name of a second DNS record to query,
  365. # whose results should match the first query. The fourth and rest of the arguments are
  366. # taken as names of caching DNS servers. Each server will be queried for the
  367. # given record and type
  368. # The return value is a 3 element list. The first element is a space delimited
  369. # string containing the names of the servers that failed to respond to the
  370. # query. The second element is a string containing the diagnostic
  371. # output that should explain the problem encountered. The third element is the
  372. # count of how many servers failed, which will be used as the exit code.
  373. sub dns_test {
  374. # First verify that we have enough arguments.
  375. my($Query, $type, $target, @Servers) = @_;
  376. my($result) = undef;
  377. my(@failed, $res, $req, $treq, $Serial, $error_cnt, $server);
  378. # Now, foreach server given on the command line,
  379. # make the query
  380. $error_cnt = 0;
  381. foreach $server (@Servers) {
  382. $res = new Net::DNS::Resolver;
  383. $res->defnames(0); # don't append default zone
  384. $res->retry($retries); # 2 retries before failure
  385. $res->retrans($retrans);
  386. $res->udp_timeout($timeout);
  387. $res->tcp_timeout($timeout);
  388. $res->nameservers($server);
  389. $req = $res->query($Query, $type);
  390. if (!defined($req) || ($req->header->ancount <= 0)) {
  391. $error_cnt++;
  392. push(@failed, $server);
  393. $result .= sprintf("\n$type query for $Query from $server failed %s\n",
  394. $res->errorstring);
  395. next;
  396. } elsif ($target) {
  397. $treq = $res->query($target, $type);
  398. my $status = 0;
  399. foreach my $qans ($req->answer) {
  400. print STDERR $qans->string."\n" if ($debug);
  401. print STDERR $qans->rdatastr."\n" if ($debug);
  402. foreach my $tans ($treq->answer) {
  403. print STDERR "target\n" if ($debug);
  404. print STDERR $tans->string."\n" if ($debug);
  405. print STDERR $tans->rdatastr."\n" if ($debug);
  406. if ($tans->rdatastr eq $qans->rdatastr) {
  407. print STDERR "match found\n" if ($debug);
  408. $status = 1;
  409. last;
  410. }
  411. }
  412. last if ($status);
  413. }
  414. if (!$status) {
  415. $error_cnt++;
  416. push @failed, $server;
  417. $result .= "Query $Query:$type failed to match $target\n";
  418. }
  419. }
  420. }
  421. if ($error_cnt == 0) {
  422. return(undef, undef, undef);
  423. } else {
  424. return("@failed", $result, $error_cnt);
  425. }
  426. }
  427. sub usage {
  428. print STDERR <<END_USAGE;
  429. Usage: dns.monitor -zone zone [-zone zone ...]
  430. -master master
  431. [-serial_threshold num]
  432. server [server ...]
  433. or: dns.monitor -caching_only
  434. -query record[:type] [-query record[:type] ...]
  435. server [server ...]
  436. Optional Arguments for either mode:
  437. -retry num
  438. -retransmit num
  439. -timeout num
  440. -debug num
  441. END_USAGE
  442. }