File: traceroute.monitor

package info (click to toggle)
mon 1.2.0-6
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 1,832 kB
  • sloc: perl: 15,847; ansic: 774; sh: 330; makefile: 46
file content (634 lines) | stat: -rwxr-xr-x 17,923 bytes parent folder | download | duplicates (9)
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
#!/usr/bin/perl
#
# mon monitor to watch for route changes
#

# There is currently a hardcoded path to the traceroute binary, see $TRACEROUTE
# but it can be overriden in the config file.

#
# Jon Meek - 31-May-1999 (original code)
#

#
# Jon Meek
# Lawrenceville, NJ
# meekj at ieee.org
#
# $Id: traceroute.monitor,v 1.2.2.1 2007/06/03 13:08:59 trockij Exp $
#
#    Copyright (C) 2001-2005, Jon Meek
#
#    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
#

=head1 NAME

B<traceroute.monitor> - Route monitor for mon.

=head1 DESCRIPTION

Monitor routes from monitor machine to a remote system using traceroute. Alarm and log
when changes are detected.

=head1 SYNOPSIS

B<traceroute.monitor -d -t 20 -c -u /path/to/traceroute.cf -l /usr/local/mon/logs/routes_YYYYMM.log>

The logfile template is usually specified in the configuration file.

=head1 OPTIONS

=over 5

=item B<-d>

Debug/Test

=item B<-c config.cfg>

Configuration file for this monitor, see example below

=item B<-t timeout>

Timeout for traceroute to run in seconds default is 20s

=item B<-l log_file_template> /path/to/logs/internet_web_YYYYMM.log

Current year & month are substituted for YYYYMM, that is the only
possible template at this time.

=item B<-u>

Fail On Unexpected Hop Only - An alert will be triggered if any of the
IP addresses specified using the UnexpectedHop item in the
configuration file are observed. Any other route change will not
create an alert. This option is useful for alerting when a backup
circuit becomes part of a default route. This option causes
traceroute.monitor to act more like a traditional mon monitor because
an alert will be triggered on every monitor run if an UnexpectedHop
appears in the path. The use of mon's alertafter N directive can be
used to filter out short term glitches that might cause a route to
change for just one monitor cycle.

=back

=head1 MON CONFIGURATION EXAMPLE

 hostgroup route1 rt-tb-paris-26 rt-tb-london-18 rt-tta-pr01r00-4
                  rt-cam-cer001-5 rt-tta-pn01r00-4

 watch route1
	service traceroute
	interval 15m
        monitor traceroute.monitor -c /usr/local/mon/traceroute.cf
        period wd {Sun-Sat}
            alert mail.alert meekj
            alertevery 1h summary

=head1 CONFIGURATION FILE EXAMPLE

 # traceroute.monitor Config File
 RouteLogFile /usr/local/mon/logs/routes_YYYYMM.log
 RouterList /usr/local/mon/rt.list
 Traceroute /usr/sbin/traceroute
 TracerouteOptions -I
 StateDir /usr/local/mon/state.d
 EquivIP 10.22.4.254 10.22.5.254 10.22.6.254
 EquivIP 10.28.4.254 10.28.5.254 10.28.6.254
 StopAt 172.30.124.17 A firewall
 StopAt 172.31.124.17 Another firewall
 UnexpectedHop 10.22.249.2 S2S VPN Tunnel
 AlertMessage
 For more details see:
 http://$HOSTNAME/cgi-bin/network/traceroute.anal
 EndAlertMessage


Lines with '#' in the first column are ignored.

RouteLogFile - A new log file will be created each month in the above
example the files will be of the form routes_199810.log The YYYYMM
format is the only date string possible in the current version The logs contain
time stamped route changes.

RouterList - Optional IP address to router name translation in
/etc/hosts format (IP_address router_name). Supplying this list will
provide considerably more meaningful alarm messages, especially if the
router names contain geographical information. Without this list, or
DNS records, the extended alarm is just a list of interface IP
addresses. DNS results take precedence over this list.

Traceroute - Overrides the default of /usr/sbin/traceroute

TracerouteOptions - Supply additional options to traceroute. -I tells
traceroute to use ICMP rather than UDP on some systems. Note that -n
is always supplied so that no DNS lookups are performed.

StateDir - Overrides the default path of the mon environment variable
MON_STATEDIR.  Files named F<lastroute.router_name> contain the last
observed route.

EquivIP - A space separated list of IP addresses that should be
considered equivalent for the purposes of determining route
changes. Likely used where there are secondary addresses on router or
switch interfaces.

StopAt - A single IP address followed by an optional comment. The
traceroute will be terminated when this address is seen. This allows a
route check to a system on another network, such as the Internet,
without tracking the route on a network that you do not control. A
common use would be to put your firewall address in a StopAt
directive. There can be multiple StopAt lines.

UnexpectedHop - See the description of the -u option above. The
presence of an UnexpectedHop in a path will trigger an alarm
regardless of whether the -u option is set, or not.

AlertMessage - A message that is appended to the alert details starts
on the next line. $HOSTNAME, if present in the message, is converted
to the name of the machine on which the monitor is running.

EndAlertMessage - The AlertMessage can be terminated by this
directive, but it is not required if the message is at the end of the
configuration file.

=head1 BUGS

There probably are some.

=head1 AUTHOR

Jon Meek, meekj@ieee.org

=head1 SEE ALSO

F<traceroute.anal> - A CGI script to display route change information.

=cut

use Getopt::Long;
use Sys::Hostname;
use POSIX qw(:signal_h WNOHANG strftime);
use Socket;

#getopts ("vdt:l:c:");

GetOptions ('v' => \$opt_v,
	    'd' => \$opt_d,
	    'debug' => \$opt_d,
	    't=i' => \$opt_t,
	    'l=s' => \$opt_l,
	    'c=s' => \$opt_c,
	    'u' => \$FailOnUnexpectedHopOnly,
	    'unexpectedhoponly' => \$FailOnUnexpectedHopOnly,
	   );

# -l file  Log file name with optional YYYYMM part that will be transformed to current month

$TimeOut = $opt_t || 20;     # Set default timeout in seconds

# Usual Linux config
$TRACEROUTE = '/bin/traceroute';
#$STATE_DIR = '/usr/local/mon/state.d';

if (defined $ENV{MON_STATEDIR}) { # Are we running under mon?
  $STATE_DIR = $ENV{MON_STATEDIR};
  $RunningUnderMon = 1;
} else {
  $RunningUnderMon = 0;
}

if ($opt_c) { # Read configuration file

  $ConfigFile = $opt_c;

  if (open(C, $ConfigFile)) {
    while ($in = <C>) {
      last if ($in =~ /^Exit/i);
      next if ($in =~ /^\#/); 	 # Comments
      chomp $in;

      if ($in =~ /^RouteLogFile\s+/i) {
	($tag, $LogFile) = split(' ', $in, 2);
	next;
      }

      if ($in =~ /^Traceroute\s+/i) { # Need whitespace to distinguish this option
	($tag, $TRACEROUTE) = split(' ', $in, 2);
	next;
      }

      if ($in =~ /^TracerouteOptions\s+/i) {
	($tag, $TracerouteOptions) = split(' ', $in, 2);
	next;
      }

      if ($in =~ /^RouterList\s+/i) {
	($tag, $RouterListFile) = split(' ', $in, 2);
	next;
      }

      if ($in =~ /^StateDir\s+/i) { # If the mon environment variable needs to be overriden
	($tag, $STATE_DIR) = split(' ', $in, 2);
	next;
      }

      if ($in =~ /^EquivIP\s+/i) {
	($tag, $ips) = split(' ', $in, 2);
	(@ip_list) = split(' ', $ips);
#	$ip_string = " $ips "; # Each IP is surrounded by whitespace
	foreach $ip (@ip_list) {
	  $EquivIP{$ip} = [ @ip_list ];
	}
	next;
      }

      if ($in =~ /^StopAt\s+/i) {
	($tag, $stop_addr, $stop_comment) = split(' ', $in, 3);
	$StopAddress{$stop_addr}++;
	$StopComment{$stop_addr} = $stop_comment;
	next;
      }

      if ($in =~ /^UnexpectedHop\s+/i) {
	($tag, $ip, $name) = split(' ', $in, 3);
	print "UnexpectedHop $ip, $name<br>\n" if $opt_d;
	$UnexpectedHop{$ip}++;
	$UnexpectedHopName{$ip} = $name;
      }

      if ($in =~ /^AlertMessage/i) { # Extra text to add to an alert starts on next line
	while ($in = <C>) {
	  last if ($in =~ /^EndAlertMessage/i);
	  $AlertMessage .= $in;
	}
	$MonitorHostname = hostname;
	$AlertMessage =~ s/\$HOSTNAME/$MonitorHostname/;
      }
    }
  } else {
    print "traceroute.monitor: Couldn't open $ConfigFile configuration file\n";
    exit 1;

  }
}

if ($opt_l) { # Command line overrides config file
  $LogFile = $opt_l;
}

if ((defined $RouterListFile) && $opt_v) { # Read the router names now
  open(F, $RouterListFile);
  while ($in = <F>) {
    chomp $in;
    ($ip, $name) = split(' ', $in, 2);
    $RouterByIP{$ip} = $name;
  }
  close F;
}

@Failures = ();
@Hosts = @ARGV; # Host names are left on the command line after Getopt


if ($TestOnly) {
  foreach $h (@Hosts) {
    $name = &HopName($h);
    print "Host: $h   $name\n";

    if (defined $EquivIP{$h}) {
      print "  Has equivalent IP\n";
    }
  }

  $ip1 = $Hosts[0];
  $ip2 = $Hosts[1];

  $equiv_check = grep /^$ip2$/, @{ $EquivIP{$ip1} };
  print "$ip1  $ip2  $equiv_check\n";

  @equiv_arr = grep /^$ip2$/, @{ $EquivIP{$ip1} };
  print "$ip1  $ip2  @equiv_arr\n";
  foreach $ip (@equiv_arr) {
    print "  $ip\n";
  }

  exit;
}

#
# Reap children to avoid defunct processes / zombies
# See "Network Programming with Perl" by Lincoln Stein
#
sub Reaper {
  while ((my $child_pid = waitpid(-1, WNOHANG)) > 0) {
    print "Reaped child: $child_pid\n" if $opt_d;
  }
}

sub OtherSIGs {
  print "traceroute.monitor Exiting on Signal\n";
  exit 1;
}

$SIG{CHLD} = \&Reaper;

$SIG{HUP} = $SIG{INT} = $SIG{QUIT} = $SIG{TERM} = \&OtherSIGs;

#
# Run traceroute for each destination, collect route
#
foreach $TargetHost (@Hosts) {

  $TimeOfDay = time;
  $FmtTimeOfDay = strftime("%A %d-%b-%Y  %H:%M:%S %Z", localtime($TimeOfDay));

  @HopList = (); # Initialize hop list for this traceroute to $TargetHost

  $cmd = qq{$TRACEROUTE -n $TracerouteOptions $TargetHost 2>/dev/null |};
  print "Options: ->$TracerouteOptions<-\nCommand: $cmd\n" if $opt_d;

  eval {
    $SIG{ALRM} = sub {die "timeout" };
    print "Setting timeout to $TimeOut s\n" if $opt_d;
    alarm($TimeOut);

    eval {

      # discard STDERR data from traceroute
      $pid = open(TR, $cmd) || die "Couldn't run traceroute\n";
      print "$FmtTimeOfDay Traceroute to $TargetHost  pid: $pid\n" if $opt_d;
      while ($in = <TR>) {
	print $in if $opt_d;
	if ($in =~ /\*\s+\*\s+\*/) { # Get * * * then give up
	  push(@HopList, '*');       # Indicate that the traceroute did not complete
	  kill 13, $pid;             # 13 = PIPE, prevents Broken Pipe Error, at least on Solaris
	  last;
	}

	# We will only pick up the first IP address listed on a line for now
	# Get IP address into $1
	$in =~ /\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+/;
	$ThisHopIP = $1;
	push(@HopList, $ThisHopIP); # Build route hop list
	if ($UnexpectedHop{$ThisHopIP}) {
	  $UnexpectedHopSeen{$TargetHost}++;
	}

	if ($opt_v) {
	  chomp $in;
	  $name = &HopName($h);
	  print "$in  $name  $RouterByIP{$ThisHopIP}\n";
	}

	if (exists $StopAddress{$ThisHopIP}) {
	  print "Stopping at $ThisHopIP  $StopComment{$ThisHopIP}\n\n" if $opt_v;
	  kill 'TERM', $pid; # Terminate the traceroute
	  alarm(0);
	  return; # May be correct way to leave eval, instead of last
	}
      }
      alarm(0);
    };
    alarm(0);
  };

  if ($@) {                     # Check for SIG
    if ($@ =~ /timeout/) {      # It was a traceroute timeout
      print "Traceroute timeout\n" if $opt_d;
      push(@HopList, '*');      # Indicate that the traceroute did not complete
      kill 13, $pid;		# 13 = PIPE, prevents Broken Pipe Error, at least on Solaris
    } else {
      print "Exiting due to some other alarm\n" if $opt_d;
      die;			# Some other problem
    }
  }

  close TR;
  $route =~ s/\-$//;		# Remove trailing '-' from route string

  $previous_hop = '';
  $route = '';
  foreach $h (@HopList) {
    $route .= "$h-" unless ($h eq $previous_hop);
    $previous_hop = $h;
  }
  $route =~ s/\-$//;		# Remove trailing '-' from route string


  $ResultString{$TargetHost} = "$TimeOfDay $TargetHost $route";

  if ($opt_d) {
    print "$TargetHost: $ResultString{$TargetHost}\n";
    print " $route\n";
  }
}

$FmtTimeOfDay = strftime("%A %d-%b-%Y  %H:%M:%S %Z", localtime(time));
print "$FmtTimeOfDay finish $TargetHost  pid: $pid\n\n" if $opt_d;

#
# Compare just measured routes with previous route stored in state file
#  or just make the state file if this is the first time for a destination
#

# TODO: if new destination (no state file), then log route to log file
#       add IP to name translation for mail messages

foreach $k (sort keys %ResultString) {
  print "$ResultString{$k}\n" if $opt_d;
  $state_file = "$STATE_DIR/lastroute.$k";

  if (-e $state_file) { # We have checked this route before, compare current
    ($t2, $host2, $current_route) = split(' ', $ResultString{$k});
    open(S, $state_file) || warn "Can't open $state_file for reading\n";
    $in = <S>;
    chomp $in;
    ($t1, $host1, $prev_route) = split(' ', $in);
    close S;

    if ($opt_d) {
      print "Previous route for $host1 -$prev_route-\n";
      print "Current  route for $host2 -$current_route-\n";
    }

    $ThisTargetFailed = 0;
    $ThisTargetFailed++ if $UnexpectedHopSeen{$k};

    if (&RouteChanged($current_route, $prev_route)) { # Route changed, record, alarm if not using only unexpected hops
      $ThisTargetFailed++ unless $FailOnUnexpectedHopOnly;
      $LogString{$k} = $ResultString{$k}; # Use separate string for logging route changes so that we don't always log unexpected hops
      if ($RunningUnderMon) { # Write results
	open(S, ">$state_file") || warn "Can't open $state_file for writing\n";
	print S "$ResultString{$k}\n";
	close S;
      }
    }

    if ($ThisTargetFailed) {
      push (@Failures, $k);
      print "  Alarm\n" if $opt_d;
    }

  } else { # The state file does not yet exist, so make it

    if ($RunningUnderMon) { # Write results
      open(S, ">$state_file") || warn "Can't open $state_file for writing\n";
      print S "$ResultString{$k}\n";
      close S;
    }
#    $LogString{$k} = $ResultString{$k}; # Always log the first instance
    push (@Failures, $k); # Call it a failure so it will be logged and notification will be sent
    print "  New route added to check: $k\n" if $opt_d;
  }

}

#
# Write results to logfile
#
if ($LogFile) {

  ($sec,$min,$hour,$mday,$Month,$Year,$wday,$yday,$isdst) =
    localtime($TimeOfDay);
  $Month++; $Year += 1900;
  $YYYYMM = sprintf('%04d%02d', $Year, $Month);
  $LogFile =~ s/YYYYMM/$YYYYMM/; # Fill in current year and month

  if (-e $LogFile) { # Check for existing log file
    $NewLogFile = 0;
  } else {
    $NewLogFile = 1;
  }

  if ($NewLogFile || (@Failures > 0)) { # Only log if new log file, or if route changes
    open(LOG, ">>$LogFile") || warn "$0 Can't open logfile: $LogFile\n";

    if ($NewLogFile) { # New log file, record all routes being tested
      foreach $host (sort keys %ResultString) {
	print LOG "$ResultString{$host}\n";
      }
    }

    if (($NewLogFile == 0) && (@Failures > 0)) { # Just record changes, not repeated unexpected hops
      foreach $host (sort keys %LogString) {
	print LOG "$LogString{$host}\n";
      }

    }

    close LOG;
  }
}

if (@Failures == 0) { # Exit if there were no failures
    exit 0;
}

# Note that we might have already read this file if --v was specified
#
if (defined $RouterListFile) { # Read the router names if we have a failure
  open(F, $RouterListFile);
  while ($in = <F>) {
    chomp $in;
    ($ip, $name) = split(' ', $in, 2);
    $RouterByIP{$ip} = $name;
  }
  close F;
}

@SortedFailures = sort @Failures; # To make summary mode in mon happy

print "@SortedFailures\n";

foreach $host (@SortedFailures) {
  print "$host:\n";
  ($t, $target, $rest) = split(' ', $ResultString{$host});
  (@hop_ips) = split(/\-/, $rest);
  foreach $hop_ip (@hop_ips) {
    $name = &HopName($hop_ip);
    printf " %-15s %s", $hop_ip, $name;
    print "  Unexpected Hop: $UnexpectedHopName{$hop_ip}" if ($UnexpectedHop{$hop_ip});
    print "\n";
  }
  print "\n";
}

if (defined $AlertMessage) {
  print "\n$AlertMessage\n";
}

exit 1;


sub RouteChanged {
  my ($current_route, $prev_route) = @_;
  my(@current_ips, @prev_ips);

  if ($current_route eq $prev_route) { # Simple case, same string, no change
    return 0;
  }

  (@current_ips) = split(/\-/, $current_route);
  (@prev_ips) = split(/\-/, $prev_route);

  if ($#current_ips != $#prev_ips) { # Another simple case, different number of hops
    return 1; # Fail
  }

  for ($i = 0; $i <= $#current_ips; $i++) {
    $ip1 = $current_ips[$i];
    $ip2 = $prev_ips[$i];
    next if ($ip1 eq $ip2);
    $equiv_check = grep /^$ip2$/, @{ $EquivIP{$ip1} };
    if ($equiv_check == 0) { # Not same, or equivalent, route different, fail
      return 1;
    }
    print "$i $ip1  $ip2  $equiv_check\n" if $opt_d;
  }
  return 0; # Good, no route change
}

sub HopName {
  my ($h_ip) = @_;
  my ($lookupname, $ha);
#  print "HopName: $h_ip<br>\n"  if $opt_d;
  if ($h_ip =~ /^\*/) {
    $name = 'Not reached';
    return $name;
  }

  if (exists $HopNameCache{$h_ip}) { # Already have the name
    $name = $HopNameCache{$h_ip};
    return $name;
  }
  $name = '';
  $ha = inet_aton($h_ip);
  $lookupname = gethostbyaddr($ha, &AF_INET);

  if (length($lookupname) > 0) { # Attempt lookup of address via "normal" system methods (DNS, hosts, etc)
    $name = $lookupname;
  } elsif ($UseRouterList) {
    $name = $RouterByIP{$h_ip} if (exists $RouterByIP{$h_ip});
  }

  # Have an auxilliary name?   such as "London Internet Router", prepend it
#  $name = qq{$RouteHopName{$h_ip}  $name} if (exists $RouteHopName{$h_ip});

  $HopNameCache{$h_ip} = $name;
#  print "$h_ip -- $name<br>\n" if $opt_d;
  return $name;
}