File: ndiff

package info (click to toggle)
ndiff 0.05beta4-2
  • links: PTS
  • area: main
  • in suites: woody
  • size: 300 kB
  • ctags: 254
  • sloc: perl: 1,806; makefile: 56
file content (527 lines) | stat: -rw-r--r-- 13,474 bytes parent folder | download | duplicates (2)
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
#!/usr/bin/perl
#
# $Id: ndiff,v 1.22 2001/11/24 22:28:15 levine Exp $
#
# Copyright (c) 2000  James D. Levine (jdl@vinecorp.com)
#
#
#   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 Getopt::Long;

use strict;
use PortScan::ScannedHost;
use PortScan::ScanComparison;
use PortScan::DataStore;
use Carp;

my @ARGS = ( @ARGV );		# save for later

my $dashed = "- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n";
my $solid  = "-----------------------------------------------------------\n";

my $baseline_tag;
my $observation_tag;

my $format = "verbose";
my $port_flags = "oxkcf";
my $host_flags = "nmc";
my $outfile = "";
my $help = 0;

GetOptions(
          "b=s"  => \$baseline_tag,
           "o=s"  => \$observation_tag,
           "op|output-ports=s" => \$port_flags,
           "oh|output-hosts=s" => \$host_flags,
           "fmt|format=s" => \$format,
	   "of|output-file=s" => \$outfile,
	   "h|help!" => \$help,
	   );

$outfile = PortScan::DataStore::prepare_tag( $outfile ) if length( $outfile ); # do % substitutions


sub usage
{
    print <<DONE;

 ndiff    [-b|-baseline  <file-or-:tag>]   [-o|-observed  <file-or-:tag>]
          [-op|-output-ports <ocufx>]      [-oh|-output-hosts <nmc>]
          [-fmt|-format <terse | minimal | verbose | machine | html | htmle>]

DONE
    ;
    exit 1;
}

&usage if $help ||  !length($baseline_tag) || !length($observation_tag);


my $out = \*STDOUT;

if ( $format =~ /html/ )
{

    my $cmd = ( $format eq "html" ) ? "ndiff2html" : "ndiff2html -e";

    $format = "machine";	# ndiff2html expects "machine" format, so reset it

    if ( length( $outfile ) )
    {
	open FOO, "| $cmd > $outfile";
	$out = \*FOO;
    }
    else
    {
	open FOO, "| $cmd ";
	$out = \*FOO;
    }
}
else
{
    if ( length( $outfile ) )
    {
	open FOO, ">$outfile" || croak "can't open $outfile for writing";
	$out = \*FOO;
    }
}

$baseline_tag = PortScan::DataStore::prepare_tag($baseline_tag);
$observation_tag = PortScan::DataStore::prepare_tag($observation_tag);

my ($processed_baseline_tag, $bds) = PortScan::DataStore::data_store_for($baseline_tag);
my ($processed_obsevation_tag, $ods) = PortScan::DataStore::data_store_for($observation_tag);

my $bss = $bds->retrieve_scanset($processed_baseline_tag);
my $oss = $ods->retrieve_scanset($processed_obsevation_tag);

my $all_ports = PortScan::SetOps::hash_union($bss->all_scanned_ports(), $oss->all_scanned_ports());
my $all_ports_list = [ keys %$all_ports ];

croak "can't get baseline scanset" if !defined $bss;
croak "can't get observation scanset" if !defined $oss;

my $baseline_set = $bss->hosts();
my $observed_set = $oss->hosts();

if ($format eq "verbose")
{
    print $out $solid;
    print $out "ndiff run " . `date` . "\n";
    print "command line: @ARGS \n";
    print $out "baseline: $baseline_tag\n";
    print $out "observed: $observation_tag\n";
}


($host_flags =~ /n/) && do 
{
    my $new_hosts     = PortScan::SetOps::unified_hash_complement($observed_set, $baseline_set);

    printf $out $dashed if $format eq "verbose";

    printf $out "new hosts:\n" if $format ne "machine";

    print $out "\n" if $format eq "verbose";

    foreach my $host (PortScan::ScannedHost::sorted_list values %$new_hosts)
    {
	print $out "new: " if $format eq "machine";
	printf $out ( host_as_text($host, $format) . "\n" );
    }

    printf $out "\n" if $format ne "machine";
};


($host_flags =~ /m/) && do
{
    my $missing_hosts = PortScan::SetOps::unified_hash_complement($baseline_set, $observed_set);

    printf $out $dashed if $format eq "verbose";

    printf $out "missing hosts:\n" if $format ne "machine";

    print $out "\n" if $format eq "verbose";

    foreach my $host (PortScan::ScannedHost::sorted_list values %$missing_hosts)
    {
	print $out "missing: " if $format eq "machine";
	printf $out (  host_as_text($host, $format) . "\n" );
    }

    printf $out "\n" if $format ne "machine";
};


($host_flags =~ /c/) && do
{
    printf $out $dashed if $format eq "verbose";

    printf $out "changed hosts:\n" if $format ne "machine";

    print $out "\n" if $format eq "verbose";

    # check the hosts that were present in both baseline and observed
    # just use the keys from this one...
    my $check_hosts   = PortScan::SetOps::hash_intersection($baseline_set, $observed_set);

    my %changed_hosts;

    foreach my $host (keys %$check_hosts)
    {

	my $baseline_scan = $baseline_set->{$host};
	my $observed_scan = $observed_set->{$host};
#    print $out "checking common host $host \n";
	my $comparison = new PortScan::ScanComparison($baseline_scan, $observed_scan, 
						      $all_ports_list);
#    print $out "created  comparison for  $host \n";

	$changed_hosts{$host} = $comparison if $comparison->differs();
#    print $out "done checking common host $host \n";
    }

    foreach my $host (PortScan::ScannedHost::addrs_sorted_list keys %changed_hosts)
    {
	my $comparison = $changed_hosts{$host};

	print $out "changed: " if $format eq "machine";
	printf $out "$host";

 	printf $out ": " if $format =~ /terse|machine/;

	printf $out "\n" if $format =~ /verbose|minimal/;

	print $out ( diffs_as_text($comparison, $port_flags, $format)   )
	    if ($comparison->differs()) ;

	print $out "\n" if $format =~ /verbose/;
    }
};

print $out $solid if $format eq "verbose";

exit 0;


sub diffs_as_text
{
    my ($compare, $flags, $fmt) = @_;
    my $text;

    ($flags =~ /o/) && $compare->to && do # output ports that changed to open
    {
	my $h = $compare->to_open();
	foreach my $pair (sort compare_port_pair values %$h)
	{
	    $text .= pair_as_text($pair, $fmt) . ( ($fmt =~ /terse|machine/) ? " " : "\n");
	}
    };

    ($flags =~ /c/) && $compare->tc && do # output ports that changed to closed
    {
	my $h = $compare->to_closed();
	foreach my $pair (sort compare_port_pair values %$h)
	{
	    $text .= pair_as_text($pair, $fmt) . ( ($fmt =~ /terse|machine/) ? " " : "\n");
	}
    };

    ($flags =~ /f/) && $compare->tf && do # output ports that changed to filtered
    {

	my $h = $compare->to_filtered();
	foreach my $pair (sort compare_port_pair values %$h)
	{
	    $text .= pair_as_text($pair, $fmt) . ( ($fmt =~ /terse|machine/) ? " " : "\n");
	}
    };

    ($flags =~ /x/) && $compare->tu && do # output ports that changed to unfiltered
    {
	my $h = $compare->to_unfiltered();
	foreach my $pair (sort compare_port_pair values %$h)
	{
	    $text .= pair_as_text($pair, $fmt) . ( ($fmt =~ /terse|machine/ ) ? " " : "\n");
	}
    };

    ($flags =~ /k/) && $compare->tunk && do # output ports that changed to unknown
    {
	my $h = $compare->to_unknown();
	foreach my $pair (sort compare_port_pair values %$h)
	{
	    $text .= pair_as_text($pair, $fmt) . ( ($fmt =~ /terse|machine/) ? " " : "\n");
	}
    };

    $text .= "\n" if $fmt =~ /terse|machine/;

    $text;
}

sub pair_as_text 
{
    my ($p, $fmt) = @_;	
    my ($b, $o) = @$p;

    ($fmt eq "terse") 
	&& return sprintf "%s/%s (%s > %s)", $o->number, $o->proto, $b->state_sm, $o->state_sm;

    ($fmt eq "minimal") 
	&& return sprintf "%s/%s/%s (%s -> %s)", $o->number, $o->proto, 
                                                 $o->service, $b->state, $o->state;

    ($fmt eq "machine")
	&& return sprintf "%s/%s/%s/%s/%s",  $o->number, $o->proto, 
                                             $o->service, $b->state, $o->state;

    return sprintf "%11s%11s -> %-11s %-11s", $o->number . "/" . $o->proto,
                                              $b->state, $o->state, $o->service;
}




sub host_as_text
{
    my ($h, $fmt)  = @_;

    my $text = $h->addr();

    $text .= ($fmt =~ /verbose|minimal/) ?  "\n" : ": ";

    my $p = $h->port_specs();

    foreach my $port ( $h->port_specs_sorted_list() )
    {
	$text .= port_as_text($port, $fmt);
	
	$text .= ($fmt =~ /verbose|minimal/) ? "\n" : " ";
    }

    $text;
}


sub port_as_text 
{
    my ($o, $fmt) = @_;	

    ($fmt =~ /terse|minimal/) 
	&& return sprintf "%s/%s/%s/%s", $o->number, $o->proto, $o->service, $o->state_sm;

    ($fmt =~ /machine/) 
	&& return sprintf "%s/%s/%s/%s", $o->number, $o->proto, $o->service, $o->state;


    return sprintf ("%11s%12s    %-20s",
		    $o->number()."/".$o->proto(), $o->state(), $o->service());
}






sub compare_port_pair
{

    if ( $a->[0]->proto() eq $b->[0]->proto() )
    {
	return $a->[0]->number() <=> $b->[0]->number();
    }

    return -1 if $a->[0]->proto() eq "tcp";
    return 1;

}





=head1 NAME

ndiff - find differences between two nmap network scans

=head1 SYNOPSIS

 ndiff    [-b|-baseline  <file-or-:tag>]   [-o|-observed  <file-or-:tag>]
          [-op|-output-ports <ocufx>]      [-of|-output-hosts <nmc>]
          [-fmt|-format <terse | minimal | verbose | machine | html | htmle>]

=head1 DESCRIPTION

ndiff allows a network administrator or other interested party to
easily monitor one or more networks for changes in port states
and running services.  It achieves this by comparing the results of
two nmap scans, one designated the "baseline", the other "observation".

Both baseline and observation are stored in files generated via nmap's
-m switch.

=head1 OPTIONS

=over 4

=item -b <filename-or-:tag>

=item -baseline <filename-or-:tag>

Specifies the nmap results to use as the baseline for the comparison.  Normally
this is the name of an nmap machine-parseable file, but if the parameter
starts with a colon (:), it is treated as a key into a data store.  See L<"DATA STORES">
below for more information.

See L<"SUBSTITUTIONS"> below for information about using %-style expansions within
filenames and :tags.

=item -o <filename-or-:tag>

=item -observed <filename-or-:tag>

Specifies the nmap results to use as the "observed results" for the comparison.  Normally
this is the name of an nmap machine-parseable file, but if the parameter
starts with a colon (:), it is treated as a key into a data store. See L<"DATA STORES">
below for more information.

See L<"SUBSTITUTIONS"> below for information about using %-style expansions within
filenames and :tags.



=item -fmt  <terse | minimal | verbose | machine | html | htmle>

=item -format  <terse | minimal | verbose | machine | html | htmle>

Specifies the level of detail in the output.  "html" causes ndiff to 
generate an html page, while "htmle" causes ndiff to generate an embeddable
html fragment (See L<ndiff2html>).


=item -op [ocufx]

=item -output-ports [ocufk]

Specifies which ports to display when outputting changed hosts. 
Any combination of the characters [ocufx] may be specified to enable
printing of ports that changed to states (in the "observed" scan) 
as follows:

 o = open
 c = closed
 f = filtered
 x = unfiltered
 k = unknown (wasn't scanned or host wasn't up)


=item -oh [nmc]

=item -output-hosts [nmc]

Specifies which types hosts to display.  Any combination of [nmc] may be
specified, as follows:

 n = new hosts (in the "observed" scan)
 m = missing hosts ( " " " )
 c = changed hosts ( " " " )

=item -of <file>

=item -output-file <file>

Send the output to the specified file.  % substitutions are supported in the
filename, see L<"SUBSTITUTIONS"> below.

=back


=head1 DATA STORES

Nrun and its related tools can manipulate results in regular nmap-format
files, in any user-specified location, or they can handle storing and organizing
the data on behalf of the user, through a user-configurable "data store".  

Whenever you precede a results tag with a colon (:), the tag will be treated
as a unique key into a data store, identifying the results set.  

Currently the only supported data store is  nmap format files placed
in a preconfigured directory.  Other types may be added at a later date.  

A legal tag may contain any alphanumeric string, plus dash, underscore, and dot.
%-style substitutions in the ilk of the "date" command are also supported,
allowing a tag to contain date, time, or the local hostname.  See L<"SUBSTITUTIONS">
below for more information.

=head1 SUBSTITUTIONS


%-style substitutions supported in tags as follows:

=over 4

=item %H = hour

=item %M = minute

=item %S = second 

=item %D = day of month

=item %m = month of year (01-12)

=item %Y = year, four digits

=item %j = day of year, three digits

=item %w = day of week (0-6) one digit

=back

Except where noted, the above items are two digits, and local time.  All are zero-padded
as appropriate.

In addtion-

=over 4

=item %F = output of "hostname" on the local machine

=back



=head1 BUGS

It's too slow -- approx 3 scanned hosts per second on a Pentium II-300.  
No support for human-readable hostnames and portnames.
Port/protocol output formatting is inconsistent in certain places.

=head1 AUTHOR

James Levine <jdl@vinecorp.com>


=cut