head	1.1;
branch	1.1.1;
access;
symbols
	RELENG_8_4:1.1.1.4.0.56
	RELENG_9_1_0_RELEASE:1.1.1.4
	RELENG_9_1:1.1.1.4.0.54
	RELENG_9_1_BP:1.1.1.4
	RELENG_8_3_0_RELEASE:1.1.1.4
	RELENG_8_3:1.1.1.4.0.52
	RELENG_8_3_BP:1.1.1.4
	RELENG_9_0_0_RELEASE:1.1.1.4
	RELENG_9_0:1.1.1.4.0.50
	RELENG_9_0_BP:1.1.1.4
	RELENG_9:1.1.1.4.0.48
	RELENG_9_BP:1.1.1.4
	RELENG_7_4_0_RELEASE:1.1.1.4
	RELENG_8_2_0_RELEASE:1.1.1.4
	RELENG_7_4:1.1.1.4.0.46
	RELENG_7_4_BP:1.1.1.4
	RELENG_8_2:1.1.1.4.0.44
	RELENG_8_2_BP:1.1.1.4
	RELENG_8_1_0_RELEASE:1.1.1.4
	RELENG_8_1:1.1.1.4.0.42
	RELENG_8_1_BP:1.1.1.4
	RELENG_7_3_0_RELEASE:1.1.1.4
	RELENG_7_3:1.1.1.4.0.40
	RELENG_7_3_BP:1.1.1.4
	RELENG_8_0_0_RELEASE:1.1.1.4
	RELENG_8_0:1.1.1.4.0.38
	RELENG_8_0_BP:1.1.1.4
	RELENG_8:1.1.1.4.0.36
	RELENG_8_BP:1.1.1.4
	RELENG_7_2_0_RELEASE:1.1.1.4
	RELENG_7_2:1.1.1.4.0.34
	RELENG_7_2_BP:1.1.1.4
	RELENG_7_1_0_RELEASE:1.1.1.4
	RELENG_6_4_0_RELEASE:1.1.1.4
	RELENG_7_1:1.1.1.4.0.32
	RELENG_7_1_BP:1.1.1.4
	RELENG_6_4:1.1.1.4.0.30
	RELENG_6_4_BP:1.1.1.4
	RELENG_7_0_0_RELEASE:1.1.1.4
	RELENG_6_3_0_RELEASE:1.1.1.4
	RELENG_7_0:1.1.1.4.0.28
	RELENG_7_0_BP:1.1.1.4
	RELENG_6_3:1.1.1.4.0.26
	RELENG_6_3_BP:1.1.1.4
	v4-1-28:1.1.1.4
	RELENG_7:1.1.1.4.0.24
	RELENG_7_BP:1.1.1.4
	v4-1-23:1.1.1.4
	RELENG_6_2_0_RELEASE:1.1.1.4
	RELENG_6_2:1.1.1.4.0.22
	RELENG_6_2_BP:1.1.1.4
	v4-1-13:1.1.1.4
	RELENG_5_5_0_RELEASE:1.1.1.4
	RELENG_5_5:1.1.1.4.0.20
	RELENG_5_5_BP:1.1.1.4
	RELENG_6_1_0_RELEASE:1.1.1.4
	RELENG_6_1:1.1.1.4.0.18
	RELENG_6_1_BP:1.1.1.4
	v4-1-10:1.1.1.4
	RELENG_6_0_0_RELEASE:1.1.1.4
	RELENG_6_0:1.1.1.4.0.16
	RELENG_6_0_BP:1.1.1.4
	RELENG_6:1.1.1.4.0.14
	RELENG_6_BP:1.1.1.4
	RELENG_5_4_0_RELEASE:1.1.1.4
	v4-1-8:1.1.1.4
	RELENG_5_4:1.1.1.4.0.12
	RELENG_5_4_BP:1.1.1.4
	RELENG_4_11_0_RELEASE:1.1.1.1.2.2
	RELENG_4_11:1.1.1.1.2.2.0.18
	RELENG_4_11_BP:1.1.1.1.2.2
	RELENG_5_3_0_RELEASE:1.1.1.4
	RELENG_5_3:1.1.1.4.0.10
	RELENG_5_3_BP:1.1.1.4
	RELENG_5:1.1.1.4.0.8
	RELENG_5_BP:1.1.1.4
	v3-4-35:1.1.1.4
	RELENG_4_10_0_RELEASE:1.1.1.1.2.2
	RELENG_4_10:1.1.1.1.2.2.0.16
	RELENG_4_10_BP:1.1.1.1.2.2
	RELENG_5_2_1_RELEASE:1.1.1.4
	RELENG_5_2_0_RELEASE:1.1.1.4
	RELENG_5_2:1.1.1.4.0.6
	RELENG_5_2_BP:1.1.1.4
	RELENG_4_9_0_RELEASE:1.1.1.1.2.2
	RELENG_4_9:1.1.1.1.2.2.0.14
	RELENG_4_9_BP:1.1.1.1.2.2
	RELENG_5_1_0_RELEASE:1.1.1.4
	RELENG_5_1:1.1.1.4.0.4
	RELENG_5_1_BP:1.1.1.4
	RELENG_4_8_0_RELEASE:1.1.1.1.2.2
	RELENG_4_8:1.1.1.1.2.2.0.12
	RELENG_4_8_BP:1.1.1.1.2.2
	v3-4-31:1.1.1.4
	RELENG_5_0_0_RELEASE:1.1.1.4
	RELENG_5_0:1.1.1.4.0.2
	RELENG_5_0_BP:1.1.1.4
	RELENG_4_7_0_RELEASE:1.1.1.1.2.2
	RELENG_4_7:1.1.1.1.2.2.0.10
	RELENG_4_7_BP:1.1.1.1.2.2
	v3-4-29:1.1.1.4
	RELENG_4_6_2_RELEASE:1.1.1.1.2.2
	RELENG_4_6_1_RELEASE:1.1.1.1.2.2
	RELENG_4_6_0_RELEASE:1.1.1.1.2.2
	v3-4-28:1.1.1.4
	RELENG_4_6:1.1.1.1.2.2.0.8
	RELENG_4_6_BP:1.1.1.1.2.2
	v3-4-27:1.1.1.4
	v3-4-26:1.1.1.4
	v3-4-25:1.1.1.4
	RELENG_4_5_0_RELEASE:1.1.1.1.2.2
	RELENG_4_5:1.1.1.1.2.2.0.6
	RELENG_4_5_BP:1.1.1.1.2.2
	RELENG_4_4_0_RELEASE:1.1.1.1.2.2
	RELENG_4_4:1.1.1.1.2.2.0.4
	RELENG_4_4_BP:1.1.1.1.2.2
	v3-4-20:1.1.1.4
	RELENG_4_3_0_RELEASE:1.1.1.1.2.2
	RELENG_4_3:1.1.1.1.2.2.0.2
	RELENG_4_3_BP:1.1.1.1.2.2
	v3-4-16:1.1.1.4
	rev:1.1.1.4
	RELENG_4_2_0_RELEASE:1.1.1.1.2.1
	v3-4-13:1.1.1.4
	v3-4-12:1.1.1.4
	RELENG_4_1_1_RELEASE:1.1.1.1.2.1
	PRE_SMPNG:1.1.1.3
	v3-4-9:1.1.1.3
	RELENG_4_1_0_RELEASE:1.1.1.1.2.1
	v3-4-8:1.1.1.2
	v3_4_4:1.1.1.2
	RELENG_4_0_0_RELEASE:1.1.1.1
	RELENG_4:1.1.1.1.0.2
	RELENG_4_BP:1.1.1.1
	v3_3_8:1.1.1.1
	v3_3_6:1.1.1.1
	v3_3_3:1.1.1.1
	DARRENR:1.1.1;
locks; strict;
comment	@# @;


1.1
date	99.11.08.20.51.07;	author guido;	state Exp;
branches
	1.1.1.1;
next	;

1.1.1.1
date	99.11.08.20.51.07;	author guido;	state Exp;
branches
	1.1.1.1.2.1;
next	1.1.1.2;

1.1.1.2
date	2000.05.24.02.14.20;	author darrenr;	state Exp;
branches;
next	1.1.1.3;

1.1.1.3
date	2000.08.13.04.58.02;	author darrenr;	state Exp;
branches;
next	1.1.1.4;

1.1.1.4
date	2000.10.26.12.45.53;	author darrenr;	state Exp;
branches
	1.1.1.4.56.1;
next	;

1.1.1.1.2.1
date	2000.07.19.23.00.51;	author darrenr;	state Exp;
branches;
next	1.1.1.1.2.2;

1.1.1.1.2.2
date	2001.02.17.20.36.28;	author darrenr;	state Exp;
branches;
next	;

1.1.1.4.56.1
date	2000.10.26.12.45.53;	author svnexp;	state dead;
branches;
next	1.1.1.4.56.2;

1.1.1.4.56.2
date	2013.03.28.13.01.21;	author svnexp;	state Exp;
branches;
next	;


desc
@@


1.1
log
@Initial revision
@
text
@#!/usr/bin/perl -wT
#
# Author: Jefferson Ogata <jogata@@nodc.noaa.gov>
# Date: 1998/11/01
# Version: 0.4
#
# Please feel free to use or redistribute this program if you find it useful.
# If you have suggestions, or even better, bits of new code, send them to me
# and I will add them when I have time. The current version of this script
# can always be found at the URL:
#
#    http://pobox.com/~ogata/webtools/plog.txt
#
# Parse ipmon output into a coherent form. This program only handles the
# lines regarding filter actions. It does not parse nat and state lines.
#
# Present lines from ipmon to this program on standard input. One way I
# often use is:
#     grep ' b ' logfile | plog
# since a ' b ' sequence indicates a blocked packet.
#
# TODO:
# - Handle output from ipmon -v.
# - Handle timestamps from other locales. Anyone with a timestamp problem
#   please email me the format of your timestamps.
#
# CHANGES:
# 1999/05/03:
# - Now accepts hostnames in the source and destination address fields, as
#   well as port names in the port fields. This allows the people who are
#   using ipmon -n to still use plog. Note that if you are logging
#   hostnames, you are vulnerable to forgery of DNS information, modified
#   DNS information, and your log files will be larger also. If you are
#   using this program you can have it look up the names for you (still
#   vulnerable to forgery) and keep your addresses all in numeric format,
#   so that packets from the same source will always show the same source
#   address regardless of what's up with DNS. Nevertheless, some people
#   wanted this, so here it is.
# - Added S and n flags to %acts hash. Thanks to Stephen J. Roznowski
#   <sjr@@home.net>.
# - Stopped reporting host IPs twice when numeric output was requested.
#   Thanks, yet again, to Stephen J. Roznowski <sjr@@home.net>.
# - Number of minor tweaks that might speed it up a bit, and some comments.
# - Put the script back up on the web site. I moved the site and forgot to
#   move the tool.
# 1999/02/04:
# - Changed log line parser to accept fully-qualified name in the logging
#   host field. Thanks to Stephen J. Roznowski <sjr@@home.net>.
# 1999/01/22:
# - Changed high port strategy to use 65536 for unknown high ports so that
#   they are sorted last.
# 1999/01/21:
# - Moved icmp parsing to output loop.
# - Added parsing of icmp codes, and more types.
# - Changed packet sort routine to sort by port number rather than service
#   name.
# 1999/01/20:
# - Fixed problem matching ipmon log lines. Sometimes they have "/ipmon" in
#   them, sometimes just "ipmon".
# - Added numeric parse option to turn off hostname lookups.
# - Moved summary to usage() sub.

use strict;
use Socket;

select STDOUT ; $| = 1 ;

my %hosts;

my $me = $0;
$me =~ s/^([^\/]*\/)*//;

my $numeric = 0;

# Under IPv4 port numbers are unsigned shorts. The value below is higher
# than the maximum value of an unsigned port, and is used in place of
# high port numbers that don't correspond to known services. This makes
# high ports get sorted behind all others.
my $highPort = 0x10000;

# Map of log codes for various actions. Not all of these can occur, but
# I've included everything in print_ipflog() from ipmon.c.
my %acts = (
    'p'	=> 'pass',
    'P'	=> 'pass',
    'b'	=> 'block',
    'B'	=> 'block',
    'L'	=> 'log',
    'S' => 'short',
    'n' => 'nomatch',
);

while (defined ($_ = shift))
{
    if (s/^-//)
    {
	$numeric += s/n//g;
	&usage (0) if (s/[h\?]//g);
	&usage (1) if (length ($_));
	next;
    }
    &usage (1);
}

while (<STDIN>)
{
    chomp;

    # For ipmon output that came through syslog, we'll have an asctime
    # timestamp, hostname, "ipmon"[process id]: prefixed to the line. For
    # output that was written directly to a file by ipmon, we'll have a date
    # prefix as dd/mm/yyyy (no y2k problem here!). Both formats then have a
    # packet timestamp and the log info.
    my ($time, $log);
    if (/^(\w+\s+\d+\s+\d+:\d+:\d+)\s+([\w\.]+)\s+\S*ipmon\[\d+\]:\s+(\d+:\d+:\d+\.\d+)\s+(.+)/)
    {
	my ($logtime, $loghost);
	($logtime, $loghost, $time, $log) = ($1, $2, $3, $4);
    }
    elsif (/^(\d+\/\d+\/\d+)\s+(\d+:\d+:\d+\.\d+)\s+(.+)$/)
    {
	my $logdate;
	($logdate, $time, $log) = ($1, $2, $3);
    }
    else
    {
	# It don't look like no ipmon output to me, baby.
	next;
    }
    next unless (defined ($log));

    # Parse the log line. We're expecting interface name, rule group and
    # number, an action code, a source host name or IP with possible port
    # name or number, a destination host name or IP with possible port
    # number, "PR", a protocol name or number, "len", a header length, a
    # packet length, and maybe some additional info.
    $log =~ /^(\w+)\s+@@(\d+):(\d+)\s+(\w)\s+([a-zA-Z0-9\-\.,]+)\s+->\s+([a-zA-Z0-9\-\.,]+)\s+PR\s+(\w+)\s+len\s+(\d+)\s+(\d+)\s*(.*)$/;
    my ($if, $group, $rule, $act, $src, $dest, $proto, $hlen, $len, $more)
	= ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10);
    unless (defined ($len))
    {
	warn ("Bad input line at $.: \"$_\"");
	next;
    }

    my ($sport, $dport);

    if ($proto eq 'icmp')
    {
	if ($more =~ s/^icmp (\d+)\/(\d+)\s*//)
	{
	    # We save icmp type and code in both sport and dport.
	    $dport = $sport = "$1.$2";
	}
	else
	{
	    $sport = '';
	    $dport = '';
	}
    }
    else
    {
	$sport = (($src =~ s/,(\w+)$//) ? &portSimplify ($1, $proto) : '');
	$dport = (($dest =~ s/,(\w+)$//) ? &portSimplify ($1, $proto) : '');
    }

    # Make sure addresses are numeric at this point. We want to sort by
    # IP address later. This has got to do some weird things, but if you
    # want to use ipmon -n, be ready for weirdness.
    $src = &hostNumber ($src);
    $dest = &hostNumber ($dest);

    # Convert proto to proto number.
    $proto = &protoNumber ($proto);

    sub countPacket
    {
	my ($host, $dir, $peer, $proto, $packet) = @@_;

	# Make sure host is in the hosts hash.
	$hosts{$host} =
	    +{
		'out'	=> +{ },
		'in'	=> +{ },
	    } unless (exists ($hosts{$host}));

	# Get the incoming/outgoing traffic hash for the host in question.
	my $trafficHash = $hosts{$host}->{$dir};

	# Make sure there's a hash for the peer.
	$trafficHash->{$peer} = +{ } unless (exists ($trafficHash->{$peer}));

	# Make sure the peer hash has a hash for the protocol number.
	my $peerHash = $trafficHash->{$peer};
	$peerHash->{$proto} = +{ } unless (exists ($peerHash->{$proto}));

	# Make sure there's a counter for this packet type in the proto hash.
	my $protoHash = $peerHash->{$proto};
	$protoHash->{$packet} = 0 unless (exists ($protoHash->{$packet}));

	# Increment the counter.
	++$protoHash->{$packet};
    }

    # Count the packet as outgoing traffic from the source address.
    &countPacket ($src, 'out', $dest, $proto, "$sport:$dport:$if:$act");

    # Count the packet as incoming traffic to the destination address.
    &countPacket ($dest, 'in', $src, $proto, "$dport:$sport:$if:$act");
}

my $dir;
foreach $dir (qw(out in))
{
    my $order = ($dir eq 'out' ? 'source' : 'destination');
    my $arrow = ($dir eq 'out' ? '->' : '<-');

    print "### Traffic by $order address:\n";

    sub ipSort
    {
	my @@a = split (/\./, $a);
	my @@b = split (/\./, $b);
	$a[0] != $b[0] ? $a[0] <=> $b[0]
	    : $a[1] != $b[1] ? $a[1] <=> $b[1]
	    : $a[2] != $b[2] ? $a[2] <=> $b[2]
	    : $a[3] != $b[3] ? $a[3] <=> $b[3]
	    : 0;
    }

    my $host;
    foreach $host (sort ipSort (keys %hosts))
    {
	my $traffic = $hosts{$host}->{$dir};

	# Skip hosts with no traffic.
	next unless (scalar (keys (%{$traffic})));

	if ($numeric)
	{
	    print "    $host\n";
	}
	else
	{
	    print "    ", &hostName ($host), " \[$host\]\n";
	}

	my $peer;
	foreach $peer (sort ipSort (keys %{$traffic}))
	{
	    my $peerHash = $traffic->{$peer};
	    my $peerName = &hostName ($peer);
	    my $proto;
	    foreach $proto (sort (keys (%{$peerHash})))
	    {
		my $protoHash = $peerHash->{$proto};
		my $protoName = &protoName ($proto);

		sub packetSort
		{
		    my ($asport, $adport, $aif, $aact) = split (/:/, $a);
		    my ($bsport, $bdport, $bif, $bact) = split (/:/, $b);
		    return $bact cmp $aact if ($aact ne $bact);
		    return $aif cmp $bif if ($aif ne $bif);
		    return $asport <=> $bsport if ($asport != $bsport);
		    return $adport <=> $bdport if ($adport != $bdport);
		}

		my $packet;
		foreach $packet (sort packetSort (keys %{$protoHash}))
		{
		    my ($sport, $dport, $if, $act) = split (/:/, $packet);
		    my $count = $protoHash->{$packet};
		    $act = '?' unless (defined ($act = $acts{$act}));
		    if (($protoName eq 'tcp') || ($protoName eq 'udp'))
		    {
			printf ("        %-6s %7s %5d %6s %14s %2s %s.%s\n", $if, $act, $count, $protoName, &portName ($sport, $protoName), $arrow, $peerName, &portName ($dport, $protoName));
		    }
		    elsif ($protoName eq 'icmp')
		    {
			printf ("        %-6s %7s %5d %6s %14s %2s %s\n", $if, $act, $count, $protoName, &icmpType ($sport), $arrow, $peerName);
		    }
		    else
		    {
			printf ("        %-6s %7s %5d %6s %14s %2s %s\n", $if, $act, $count, $protoName, '', $arrow, $peerName);
		    }
		}
	    }
	}
    }

    print "\n\n";
}

exit (0);

# We use this hash to cache port name -> number and number -> name mappings.
# Isn't is cool that we can use the same hash for both?
my %pn;

# Translates a numeric port/named protocol to a port name. Reserved ports
# that do # not have an entry in the services database are left numeric.
# High ports that do not have an entry in the services database are mapped
# to '<high>'.
sub portName
{
    my $port = shift;
    my $proto = shift;
    my $pname = "$port/$proto";
    unless (exists ($pn{$pname}))
    {
	my $name = getservbyport ($port, $proto);
	$pn{$pname} = (defined ($name) ? $name : ($port <= 1023 ? $port : '<high>'));
    }
    return $pn{$pname};
}

# Translates a named port/protocol to a port number.
sub portNumber
{
    my $port = shift;
    my $proto = shift;
    my $pname = "$port/$proto";
    unless (exists ($pn{$pname}))
    {
	my $number = getservbyname ($port, $proto);
	unless (defined ($number))
	{
	    # I don't think we need to recover from this. How did the port
	    # name get into the log file if we can't find it? Log file from
	    # a different machine? Fix /etc/services on this one if that's
	    # your problem.
	    die ("Unrecognized port name \"$port\" at $.");
	}
	$pn{$pname} = $number;
    }
    return $pn{$pname};
}

# Convert all unrecognized high ports to the same value so they are treated
# identically. The protocol should be by name.
sub portSimplify
{
    my $port = shift;
    my $proto = shift;

    # Make sure port is numeric.
    $port = &portNumber ($port, $proto)
	unless ($port =~ /^\d+$/);

    # Look up port name.
    my $portName = &portName ($port, $proto);

    # Port is an unknown high port. Return a value that is too high for a
    # port number, so that high ports get sorted last.
    return $highPort if ($portName eq '<high>');

    # Return original port number.
    return $port;
}

# Again, we can use the same hash for both host name -> IP mappings and
# IP -> name mappings.
my %ip;

# Translates a dotted quad into a hostname. Don't pass names to this
# function.
sub hostName
{
    my $ip = shift;
    return $ip if ($numeric);
    unless (exists ($ip{$ip}))
    {
	my $addr = inet_aton ($ip);
	my $name = gethostbyaddr ($addr, AF_INET);
	if (defined ($name))
	{
	    $ip{$ip} = $name;

	    # While we're at it, cache the forward lookup.
	    $ip{$name} = $ip;
	}
	else
	{
	    # Just map the IP address to itself. There's no reverse.
	    $ip{$ip} = $ip;
	}
    }
    return $ip{$ip};
}

# Translates a hostname or dotted quad into a dotted quad.
sub hostNumber
{
    my $name = shift;
    if ($name =~ /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/)
    {
	# Return original value for dotted quads.
	my $or = int ($1) | int ($2) | int ($3) | int ($4);
	return $name if ($or == ($or & 0xff));
    }
    unless (exists ($ip{$name}))
    {
	my $addr = inet_aton ($name);
	unless (defined ($addr))
	{
	    # Again, I don't think we need to recover from this. If we can't
	    # resolve a hostname that ended up in the log file, punt. We
	    # want to be able to sort hosts by IP address later, and letting
	    # hostnames through will snarl up that code. Users of ipmon -n
	    # will have to grin and bear it for now.
	    die ("Unable to resolve host \"$name\" at $.");
	}
	my $ip = inet_ntoa ($addr);
	$ip{$name} = $ip;

	# While we're at it, cache the reverse lookup.
	$ip{$ip} = $name;
    }
    return $ip{$name};
}

# Hash for protocol number <--> name mappings.
my %pr;

# Translates a protocol number into a protocol name, or a number if no name
# is found in the protocol database.
sub protoName
{
    my $code = shift;
    return $code if ($code !~ /^\d+$/);
    unless (exists ($pr{$code}))
    {
	my $name = scalar (getprotobynumber ($code));
	if (defined ($name))
	{
	    $pr{$code} = $name;
	}
	else
	{
	    $pr{$code} = $code;
	}
    }
    return $pr{$code};
}

# Translates a protocol name or number into a protocol number.
sub protoNumber
{
    my $name = shift;
    return $name if ($name =~ /^\d+$/);
    unless (exists ($pr{$name}))
    {
	my $code = scalar (getprotobyname ($name));
	if (defined ($code))
	{
	    $pr{$name} = $code;
	}
	else
	{
	    $pr{$name} = $name;
	}
    }
    return $pr{$name};
}

sub icmpType
{
    my %icmp = (
	0	=> +{
	    name	=> 'echo-reply',
	    codes	=> +{0	=> undef},
	},
	3	=> +{
	    name	=> 'dest-unr',
	    codes	=> +{
		0	=> 'net',
		1	=> 'host',
		2	=> 'proto',
		3	=> 'port',
		4	=> 'need-frag',
		5	=> 'no-sroute',
		6	=> 'net-unk',
		7	=> 'host-unk',
		8	=> 'shost-isol',
		9	=> 'net-proh',
		10	=> 'host-proh',
		11	=> 'net-tos',
		12	=> 'host-tos',
	    },
	},
	4	=> +{
	    name	=> 'src-quench',
	    codes	=> +{0	=> undef},
	},
	5	=> +{
	    name	=> 'redirect',
	    codes	=> +{
		0	=> 'net',
		1	=> 'host',
		2	=> 'tos',
		3	=> 'tos-host',
	    },
	},
	6	=> +{
	    name	=> 'alt-host-addr',
	    codes	=> +{0	=> undef},
	},
	8	=> +{
	    name	=> 'echo',
	    codes	=> +{0	=> undef},
	},
	9	=> +{
	    name	=> 'rtr-advert',
	    codes	=> +{0	=> undef},
	},
	10	=> +{
	    name	=> 'rtr-select',
	    codes	=> +{0	=> undef},
	},
	11	=> +{
	    name	=> 'time-excd',
	    codes	=> +{
		0	=> 'in-transit',
		1	=> 'frag-assy',
	    },
	},
	12	=> +{
	    name	=> 'param-prob',
	    codes	=> +{
		0	=> 'ptr-err',
		1	=> 'miss-opt',
		2	=> 'bad-len',
	    },
	},
	13	=> +{
	    name	=> 'time',
	    codes	=> +{0	=> undef},
	},
	14	=> +{
	    name	=> 'time-reply',
	    codes	=> +{0	=> undef},
	},
	15	=> +{
	    name	=> 'info',
	    codes	=> +{0	=> undef},
	},
	16	=> +{
	    name	=> 'info-req',
	    codes	=> +{0	=> undef},
	},
	17	=> +{
	    name	=> 'mask-req',
	    codes	=> +{0	=> undef},
	},
	18	=> +{
	    name	=> 'mask-reply',
	    codes	=> +{0	=> undef},
	},
	31	=> +{
	    name	=> 'dgram-conv-err',
	    codes	=> +{ },
	},
	32	=> +{
	    name	=> 'mbl-host-redir',
	    codes	=> +{ },
	},
	33	=> +{
	    name	=> 'ipv6-whereru?',
	    codes	=> +{ },
	},
	34	=> +{
	    name	=> 'ipv6-iamhere',
	    codes	=> +{ },
	},
	35	=> +{
	    name	=> 'mbl-reg-req',
	    codes	=> +{ },
	},
	36	=> +{
	    name	=> 'mbl-reg-rep',
	    codes	=> +{ },
	},
    );

    my $typeCode = shift;
    my ($type, $code) = split ('\.', $typeCode);

    return "?" unless (defined ($code));

    my $info = $icmp{$type};

    return "\(type=$type/$code?\)" unless (defined ($info));

    my $typeName = $info->{name};
    my $codeName;
    if (exists ($info->{codes}->{$code}))
    {
	$codeName = $info->{codes}->{$code};
	$codeName = (defined ($codeName) ? "/$codeName" : '');
    }
    else
    {
	$codeName = "/$code";
    }
    return "$typeName$codeName";
}

sub usage
{
    my $ec = shift;

    print STDERR <<EOT;
usage: $me [-n]

Parses logging from ipmon and presents it in a comprehensible format.
This program generates two tables: one organized by source address and
another organized by destination address. For the first table, source
addresses are sorted by IP address. For each address, all packets
originating at the address are presented in a tabular form, where all
packets with the same source and destination address and port are counted
as a single entry. The packet count for each entry is shown as the third
field. In addition, any port number greater than 1024 that doesn't match
an entry in the services table is treated as a "high" port, and high ports
are coalesced into the same entry. The entry fields for the source address
table are:

    iface action packet-count proto src-port dest-ip dest-port

The entry fields for the destination table are:

    iface action packet-count proto dest-port src-ip src-port

If the -n option is given, reverse hostname lookups are disabled and all
hosts are displayed as numeric addresses.

Note: if you are logging traffic with ipmon -n, ipmon will already have
looked up and logged addresses as hostnames where possible. This has an
important side effect: this program will translate the hostnames back into
IP addresses which may not match the original addresses of the logged
packets because of numerous DNS issues. If you care about where packets
are really coming from, you simply cannot rely on ipmon -n. An attacker
with control of his reverse DNS can map the reverse lookup to anything he
likes. If you haven't logged the numeric IP address, there's no way to
discover the source of an attack reliably. For this reason, I strongly
recommend that you run ipmon without the -n option, and use this or a
similar script to do reverse lookups during analysis, rather than during
logging.
EOT

    exit ($ec);
}

@


1.1.1.1
log
@Import of ipfilter 3.3.3  in anticipation of its revival.
More to come in the next days.
@
text
@@


1.1.1.1.2.1
log
@actually commit merged diffs to the trunk
@
text
@d3 3
a5 3
# Author: Jefferson Ogata (JO317) <jogata@@pobox.com>
# Date: 2000/04/10
# Version: 0.8
d17 4
a20 21
# Present lines from ipmon to this program on standard input.
#
# EXAMPLES
#
# plog -A block,log < /var/log/ipf
#
#    Generate source and destination reports of all packets logged with
#    block or log actions.
#
# plog -S -s ./services www.example.com < /var/log/ipf
#
#    Generate a source report of traffic to or from www.example.com using
#    the additional services defined in ./services.
#
# plog -nSA block < /var/log/ipf
#
#    Generate a source report of all blocked packets with no hostname
#    lookups. This is handy for an initial pass to identify portscans or
#    other aggressive traffic.
#
# TODO
d22 1
a25 47
# - It looks as though short TCP or UDP packets will break things, but I
#   haven't seen any yet.
#
# CHANGES
#
# 2000/04/12 (0.9):
# - Wasn't handling underscore in hostname,servicename fields; these may be
#   logged using ipmon -n. Observation by <ark@@eltex.ru>.
# - Hadn't properly attributed observation and fix for repetition counter in
#   0.8 change log. Added John Ladwig to attribution. Thanks, John.
#
# 2000/04/10 (0.8):
# - Service names can also have hyphens, dummy. I wasn't allowing these
#   either. Observation and fix thanks to Taso N. Devetzis
#   <devetzis@@snet.net>.
# - IP Filter now logs a repetition counter. Observation and fixes (changed
#   slightly) from Andy Kreiling <Andy@@ntcs-inc.com> and John Ladwig
#   <jladwig@@nts.umn.edu>.
# - Added fix to handle new Solaris log format, e.g.:
#     Nov 30 04:49:37 raoul ipmon[121]: [ID 702911 local0.warning] 04:49:36.420
541 hme0 @@0:34 b 205.152.16.6,58596 -> 204.60.220.24,113 PR tcp len 20 44
#   Fix thanks to Taso N. Devetzis <devetzis@@SNET.Net>.
# - Added services map option.
# - Added options for generating only source/destination tables.
# - Added verbosity option.
# - Added option for reporting traffic for specific hosts.
# - Added some more ICMP unreachable codes, and made code and type names
#   match the ones in IP Filter parse.c.
# - Condensed output format somewhat.
# - Various minor improvements, perhaps slight speed improvements.
# - Documented new options in usage() and tried to improve wording.
#
# 1999/08/02 (0.7):
# - Hostnames can have hyphens, dummy. I wasn't allowing them in the syslog
#   line. Fix from Antoine Verheijen <antoine.verheijen@@ualberta.ca>.
#
# 1999/05/05 (0.6):
# - IRIX syslog prefixes the hostname with a severity code. Handle it. Fix
#   from John Ladwig <jladwig@@nts.umn.edu>.
#
# 1999/05/05 (0.5):
# - Protocols other than TCP, UDP, or ICMP have packet lengths reported in
#   parentheses for some reason. The script now handles this. Thanks to
#   Dispatcher <dispatch@@blackhelicopters.org>.
# - I had mixed up info-request and info-reply ICMP codes, and omitted the
#   traceroute code. Sorted this out. I had also missed code 0 for type 6
#   (alternate address for host). Thanks to John Ladwig <jladwig@@nts.umn.edu>.
d27 1
d35 4
a38 5
#   vulnerable to forgery) and keep your logged addresses all in numeric
#   format, so that packets from the same source will always show the same
#   source address regardless of what's up with DNS. Obviously, I don't
#   favor using ipmon -n. Nevertheless, some people wanted this, so here it
#   is.
d44 2
a45 3
# - Put the script back up on the web site. I had moved the site and
#   forgotten to move the tool.
#
a48 1
#
a51 1
#
a56 1
#
a64 1
use IO::File;
d66 1
a66 1
select STDOUT; $| = 1;
d71 9
a79 1
$me =~ s/^.*\///;
d84 5
a88 5
    'p' => 'pass',
    'P' => 'pass',
    'b' => 'block',
    'B' => 'block',
    'L' => 'log',
a92 137
# Map of ICMP types and their relevant codes.
my %icmpTypeMap = (
    0   => +{
        name    => 'echorep',
        codes   => +{0  => undef},
    },
    3   => +{
        name    => 'unreach',
        codes   => +{
            0   => 'net-unr',
            1   => 'host-unr',
            2   => 'proto-unr',
            3   => 'port-unr',
            4   => 'needfrag',
            5   => 'srcfail',
            6   => 'net-unk',
            7   => 'host-unk',
            8   => 'isolate',
            9   => 'net-prohib',
            10  => 'host-prohib',
            11  => 'net-tos',
            12  => 'host-tos',
            13  => 'filter-prohib',
            14  => 'host-preced',
            15  => 'preced-cutoff',
        },
    },
    4   => +{
        name    => 'squench',
        codes   => +{0  => undef},
    },
    5   => +{
        name    => 'redir',
        codes   => +{
            0   => 'net',
            1   => 'host',
            2   => 'tos',
            3   => 'tos-host',
        },
    },
    6   => +{
        name    => 'alt-host-addr',
        codes   => +{
            0   => 'alt-addr'
        },
    },
    8   => +{
        name    => 'echo',
        codes   => +{0  => undef},
    },
    9   => +{
        name    => 'routerad',
        codes   => +{0  => undef},
    },
    10  => +{
        name    => 'routersol',
        codes   => +{0  => undef},
    },
    11  => +{
        name    => 'timex',
        codes   => +{
            0   => 'in-transit',
            1   => 'frag-assy',
        },
    },
    12  => +{
        name    => 'paramprob',
        codes   => +{
            0   => 'ptr-err',
            1   => 'miss-opt',
            2   => 'bad-len',
        },
    },
    13  => +{
        name    => 'timest',
        codes   => +{0  => undef},
    },
    14  => +{
        name    => 'timestrep',
        codes   => +{0  => undef},
    },
    15  => +{
        name    => 'inforeq',
        codes   => +{0  => undef},
    },
    16  => +{
        name    => 'inforep',
        codes   => +{0  => undef},
    },
    17  => +{
        name    => 'maskreq',
        codes   => +{0  => undef},
    },
    18  => +{
        name    => 'maskrep',
        codes   => +{0  => undef},
    },
    30  => +{
        name    => 'tracert',
        codes   => +{ },
    },
    31  => +{
        name    => 'dgram-conv-err',
        codes   => +{ },
    },
    32  => +{
        name    => 'mbl-host-redir',
        codes   => +{ },
    },
    33  => +{
        name    => 'ipv6-whereru?',
        codes   => +{ },
    },
    34  => +{
        name    => 'ipv6-iamhere',
        codes   => +{ },
    },
    35  => +{
        name    => 'mbl-reg-req',
        codes   => +{ },
    },
    36  => +{
        name    => 'mbl-reg-rep',
        codes   => +{ },
    },
);

# Arguments we will parse from argument list.
my $numeric = 0;        # Don't lookup hostnames.
my $verbosity = 0;      # Bla' bla' bla'.
my $sTable = 0;         # Generate source table.
my $dTable = 0;         # Generate destination table.
my $services = undef;   # Preload services table.
my %selectHosts;        # Limit report to these hosts.
my %selectActs;         # Limit report to these actions.

# Parse argument list.
d97 4
a100 113
        while (s/^([nSD\?hsA])//)
        {
            my $flag = $1;
            if ($flag eq 'v')
            {
                ++$verbosity;
            }
            elsif ($flag eq 'n')
            {
                $numeric = 1;
            }
            elsif ($flag eq 'S')
            {
                $sTable = 1;
            }
            elsif ($flag eq 'D')
            {
                $dTable = 1;
            }
            elsif (($flag eq '?') || ($flag eq 'h'))
            {
                &usage (0);
            }
            else
            {
                my $arg = shift;
                defined ($arg) || &usage (1, qq{-$flag requires an argument});
                if ($flag eq 's')
                {
                    defined ($services) && &usage (1, qq{too many service maps}
);
                    $services = $arg;
                }
                elsif ($flag eq 'A')
                {
                    my @@acts = split (/,/, $arg);
                    my $a;
                    foreach $a (@@acts)
                    {
                        my $aa;
                        my $match = 0;
                        foreach $aa (keys (%acts))
                        {
                            if ($acts{$aa} eq $a)
                            {
                                ++$match;
                                $selectActs{$aa} = $a;
                            }
                        }
                        $match || &usage (1, qq{unknown action $a});
                    }
                }
            }
        }

        &usage (1, qq{unknown option: -$_}) if (length);

        next;
    }

    # Add host to hash of hosts we're interested in.
    my $addr = &hostNumber ($_);
    defined ($addr) || &usage (1, qq{cannot resolve hostname $_});
    $selectHosts{$addr} = undef;
}

# Which tables will we generate?
$dTable = $sTable = 1 unless ($dTable || $sTable);
my @@dirs;
push (@@dirs, 'd') if ($dTable);
push (@@dirs, 's') if ($sTable);

# Are we interested in specific hosts?
my $selectHosts = scalar (keys (%selectHosts));

# Are we interested in specific actions?
if (scalar (keys (%selectActs)) == 0)
{
    %selectActs = %acts;
}

# We use this hash to cache port name -> number and number -> name mappings.
# Isn't it cool that we can use the same hash for both?
my %pn;

# Preload any services map.
if (defined ($services))
{
    my $sf = new IO::File ($services, "r");
    defined ($sf) || &quit (1, qq{cannot open services file $services});

    while (defined ($_ = $sf->getline ()))
    {
        my $text = $_;
        chomp;
        s/#.*$//;
        s/\s+$//;
        next unless (length);
        my ($name, $spec, @@aliases) = split (/\s+/);
        ($spec =~ /^([\w\-]+)\/([\w\-]+)$/)
            || &quit (1, qq{$services:$.: invalid definition: $text});
        my ($pnum, $proto) = ($1, $2);

        # Enter service definition in pn hash both forwards and backwards.
        my $port;
        my $pname;
        foreach $port ($name, @@aliases)
        {
            $pname = "$pnum/$proto";
            $pn{$pname} = $port;
        }
        $pname = "$name/$proto";
        $pn{$pname} = $pnum;
d102 1
a102 2

    $sf->close ();
a104 13
# Again, we can use the same hash for both host name -> IP mappings and
# IP -> name mappings.
my %ip;

# Hash for protocol number <--> name mappings.
my %pr;

# Under IPv4 port numbers are unsigned shorts. The value below is higher
# than the maximum value of an unsigned short, and is used in place of
# high port numbers that don't correspond to known services. This makes
# high ports get sorted behind all others.
my $highPort = 0x10000;

d110 6
a115 8
    # timestamp, an optional severity code (IRIX), the hostname,
    # "ipmon"[process id]: prefixed to the line. For output that was
    # written directly to a file by ipmon, we'll have a date prefix as
    # dd/mm/yyyy (no y2k problem here!). Both formats then have a packet
    # timestamp and the log info.
    my ($log);
    if (s/^\w+\s+\d+\s+\d+:\d+:\d+\s+(?:\d\w:)?[\w\.\-]+\s+\S*ipmon\[\d+\]:\s+(
?:\[ID\s+\d+\s+[\w\.]+\]\s+)?\d+:\d+:\d+\.\d+\s+//)
d117 2
a118 1
        $log = $_;
d120 1
a120 1
    elsif (s/^(?:\d+\/\d+\/\d+)\s+(?:\d+:\d+:\d+\.\d+)\s+//)
d122 2
a123 1
        $log = $_;
d127 2
a128 2
        # It don't look like no ipmon output to me, baby.
        next;
a131 2
    print STDERR "$log\n" if ($verbosity);

d136 8
a143 8
    # packet length (which will be in parentheses for protocols other than
    # TCP, UDP, or ICMP), and maybe some additional info.
    my @@fields = ($log =~ /^(?:(\d+)x)?\s*(\w+)\s+@@(\d+):(\d+)\s+(\w)\s+([\w\-\
..,]+)\s+->\s+([\w\-\.,]+)\s+PR\s+(\w+)\s+len\s+(\d+)\s+\(?(\d+)\)?\s*(.*)$/ox);
    unless (scalar (@@fields))
    {
        print STDERR "$me:$.: cannot parse: $_\n";
        next;
a144 8
    my ($count, $if, $group, $rule, $act, $src, $dest, $proto, $hlen, $len, $mo
re) = @@fields;

    # Skip actions we're not interested in.
    next unless (exists ($selectActs{$act}));

    # Packet count defaults to 1.
    $count = 1 unless (defined ($count));
d150 10
a159 12
        if ($more =~ s/^icmp (\d+)\/(\d+)\s*//)
        {
            # We save icmp type and code in both sport and dport. This
            # allows us to sort icmp packets using the normal port-sorting
            # code.
            $dport = $sport = "$1.$2";
        }
        else
        {
            $sport = '';
            $dport = '';
        }
d163 2
a164 16
        if ($src =~ s/,([\-\w]+)$//)
        {
            $sport = &portSimplify ($1, $proto);
        }
        else
        {
            $sport = '';
        }
        if ($dest =~ s/,([\-\w]+)$//)
        {
            $dport = &portSimplify ($1, $proto);
        }
        else
        {
            $dport = '';
        }
d170 2
a171 19
    my $x;
    $x = &hostNumber ($src);
    unless (defined ($x))
    {
        print STDERR "$me:$.: cannot resolve hostname $src\n";
        next;
    }
    $src = $x;
    $x = &hostNumber ($dest);
    unless (defined ($x))
    {
        print STDERR "$me:$.: cannot resolve hostname $dest\n";
        next;
    }
    $dest = $x;

    # Skip hosts we're not interested in.
    next if ($selectHosts && !(exists ($selectHosts{$src}) || exists ($selectHo
sts{$dest})));
d178 1
a178 1
        my ($host, $dir, $peer, $proto, $count, $packet) = @@_;
d180 20
a199 20
        # Make sure host is in the hosts hash.
        $hosts{$host} =
            +{
                'd'     => +{ },
                's'     => +{ },
            } unless (exists ($hosts{$host}));

        # Get the source/destination traffic hash for the host in question.
        my $trafficHash = $hosts{$host}->{$dir};

        # Make sure there's a hash for the peer.
        $trafficHash->{$peer} = +{ } unless (exists ($trafficHash->{$peer}));

        # Make sure the peer hash has a hash for the protocol number.
        my $peerHash = $trafficHash->{$peer};
        $peerHash->{$proto} = +{ } unless (exists ($peerHash->{$proto}));

        # Make sure there's a counter for this packet type in the proto hash.
        my $protoHash = $peerHash->{$proto};
        $protoHash->{$packet} = 0 unless (exists ($protoHash->{$packet}));
d201 2
a202 2
        # Increment the counter.
        $protoHash->{$packet} += $count;
d206 1
a206 2
    &countPacket ($src, 's', $dest, $proto, $count, "$sport:$dport:$if:$act") i
f ($sTable);
d209 1
a209 2
    &countPacket ($dest, 'd', $src, $proto, $count, "$dport:$sport:$if:$act") i
f ($dTable);
d213 1
a213 1
foreach $dir (@@dirs)
d215 2
a216 2
    my $order = ($dir eq 's' ? 'source' : 'destination');
    my $arrow = ($dir eq 's' ? '->' : '<-');
a217 1
    print "###\n";
a218 1
    print "###\n";
d222 7
a228 12
        my @@a = split (/\./, $a);
        my @@b = split (/\./, $b);
        $a[0] <=> $b[0] || $a[1] <=> $b[1] || $a[2] <=> $b[2] || $a[3] <=> $b[3
];
    }

    sub packetSort
    {
        my ($asport, $adport, $aif, $aact) = split (/:/, $a);
        my ($bsport, $bdport, $bif, $bact) = split (/:/, $b);
        $bact cmp $aact || $aif cmp $bif || $asport <=> $bsport || $adport <=> 
$bdport;
d234 1
a234 1
        my $traffic = $hosts{$host}->{$dir};
d236 2
a237 2
        # Skip hosts with no traffic.
        next unless (scalar (keys (%{$traffic})));
d239 51
a289 45
        if ($numeric)
        {
            print "$host\n";
        }
        else
        {
            print &hostName ($host), " \[$host\]\n";
        }

        my $peer;
        foreach $peer (sort ipSort (keys %{$traffic}))
        {
            my $peerHash = $traffic->{$peer};
            my $peerName = &hostName ($peer);
            my $proto;
            foreach $proto (sort (keys (%{$peerHash})))
            {
                my $protoHash = $peerHash->{$proto};
                my $protoName = &protoName ($proto);

                my $packet;
                foreach $packet (sort packetSort (keys %{$protoHash}))
                {
                    my ($sport, $dport, $if, $act) = split (/:/, $packet);
                    my $count = $protoHash->{$packet};
                    $act = '?' unless (defined ($act = $acts{$act}));
                    if (($protoName eq 'tcp') || ($protoName eq 'udp'))
                    {
                        printf ("    %-6s %7s %4d %4s %16s %2s %s.%s\n", $if, $
act, $count, $protoName, &portName ($sport, $protoName), $arrow, $peerName, &po
rtName ($dport, $protoName));
                    }
                    elsif ($protoName eq 'icmp')
                    {
                        printf ("    %-6s %7s %4d %4s %16s %2s %s\n", $if, $act
, $count, $protoName, &icmpType ($sport), $arrow, $peerName);
                    }
                    else
                    {
                        printf ("    %-6s %7s %4d %4s %16s %2s %s\n", $if, $act
, $count, $protoName, '', $arrow, $peerName);
                    }
                }
            }
        }
d292 1
a292 1
    print "\n";
d297 4
d302 2
a303 2
# that do not have an entry in the services database are left numeric. High
# ports that do not have an entry in the services database are mapped
d312 2
a313 3
        my $name = getservbyport ($port, $proto);
        $pn{$pname} = (defined ($name) ? $name : ($port <= 1023 ? $port : '<hig
h>'));
d326 10
a335 10
        my $number = getservbyname ($port, $proto);
        unless (defined ($number))
        {
            # I don't think we need to recover from this. How did the port
            # name get into the log file if we can't find it? Log file from
            # a different machine? Fix /etc/services on this one if that's
            # your problem.
            die ("Unrecognized port name \"$port\" at $.");
        }
        $pn{$pname} = $number;
d349 1
a349 1
        unless ($port =~ /^\d+$/);
d362 4
d374 14
a387 14
        my $addr = inet_aton ($ip);
        my $name = gethostbyaddr ($addr, AF_INET);
        if (defined ($name))
        {
            $ip{$ip} = $name;

            # While we're at it, cache the forward lookup.
            $ip{$name} = $ip;
        }
        else
        {
            # Just map the IP address to itself. There's no reverse.
            $ip{$ip} = $ip;
        }
d398 3
a400 3
        # Return original value for dotted quads.
        my $or = int ($1) | int ($2) | int ($3) | int ($4);
        return $name if ($or == ($or & 0xff));
d404 12
a415 12
        my $addr = inet_aton ($name);
        unless (defined ($addr))
        {
            # Again, I don't think we need to recover from this. If we can't
            # resolve a hostname that ended up in the log file, punt. We
            # want to be able to sort hosts by IP address later, and letting
            # hostnames through will snarl up that code. Users of ipmon -n
            # will have to grin and bear it for now.
            return undef;
        }
        my $ip = inet_ntoa ($addr);
        $ip{$name} = $ip;
d417 2
a418 2
        # While we're at it, cache the reverse lookup.
        $ip{$ip} = $name;
d423 3
d434 9
a442 9
        my $name = scalar (getprotobynumber ($code));
        if (defined ($name))
        {
            $pr{$code} = $name;
        }
        else
        {
            $pr{$code} = $code;
        }
d454 9
a462 9
        my $code = scalar (getprotobyname ($name));
        if (defined ($code))
        {
            $pr{$name} = $code;
        }
        else
        {
            $pr{$name} = $name;
        }
d469 117
d591 1
a591 1
    my $info = $icmpTypeMap{$type};
d599 2
a600 2
        $codeName = $info->{codes}->{$code};
        $codeName = (defined ($codeName) ? "/$codeName" : '');
d604 1
a604 1
        $codeName = "/$code";
d609 1
a609 1
sub quit
a611 1
    my $msg = shift;
d613 2
a614 3
    print STDERR "$me: $msg\n";
    exit ($ec);
}
d616 11
a626 4
sub usage
{
    my $ec = shift;
    my @@msg = @@_;
d628 1
a628 4
    if (scalar (@@msg))
    {
        print STDERR "$me: ", join ("\n", @@msg), "\n\n";
    }
d630 1
a630 2
    print STDERR <<EOT;
usage: $me [-n] [-S] [-D] [-s servicemap] [-A act1,...] host...
a631 11
Parses logging from ipmon and presents it in a comprehensible format. This
program generates two reports: one organized by source address and another
organized by destination address. For the first report, source addresses are
sorted by IP address. For each address, all packets originating at the address
are presented in a tabular form, where all packets with the same source and
destination address and port are counted as a single entry. Any port number
greater than 1023 that does not match an entry in the services table is treated
as a "high" port; all high ports are coalesced into the same entry. The fields
for the source address report are:
    iface action packet-count proto src-port dest-ip dest-port
The fields for the destination address report are:
d634 15
a648 28
Options are:
-n           Disable hostname lookups, and report only IP addresses.
-S           Generate a source address report.
-D           Generate a destination address report.
-s map       Supply an alternate services map to be preloaded. The map should
             be in the same format as /etc/services. Any service name not found
             in the map will be looked for in the system services file.
-A act1,...  Limit the report to the specified actions. The possible actions ar
e
             pass, block, log, short, and nomatch.

If any hostnames are supplied on the command line, the report is limited to
these hosts. If a host has multiple addresses, only the first address will be
considered.

If neither -S nor -D is given, both reports are generated.

Note: if you are logging traffic with ipmon -n, ipmon will already have looked
up and logged addresses as hostnames where possible. This has an important side
effect: this program will translate the hostnames back into IP addresses which
may not match the original addresses of the logged packets because of numerous
DNS issues. If you care about where packets are really coming from, you simply
cannot rely on ipmon -n. An attacker with control of his reverse DNS can map
the reverse lookup to anything he likes. If you haven't logged the numeric IP
address, there's no way to discover the source of an attack reliably. For this
reason, I strongly recommend that you run ipmon without the -n option, and use
this or a similar script to do reverse lookups during analysis, rather than
during logging.
a652 2


@


1.1.1.1.2.2
log
@Merge changes from 3.4.8 to 3.4.16
@
text
@d4 2
a5 2
# Date: 2000/04/22
# Version: 0.10
a11 1
#    http://www.antibozo.net/ogata/webtools/plog.pl
d21 1
a21 1
# plog -AF block,log < /var/log/ipf
d24 1
a24 1
#    block or log actions, and report TCP flags and keep state actions.
a36 8
# plog -SFp 192.168.0.0/24 www.example.com/24 < /var/log/ipf
#
#    Generate a source report of all packets whose source or destination
#    address is either in 192.168.0.0/24 or an address associated with
#    the host www.example.com, report packet flags and perform paranoid
#    hostname lookups. This is a handy usage for examining traffic more
#    closely after identifying a potential attack.
#
a46 8
# 2000/04/22 (0.10):
# - Restructured host name and address caches. Hosts are now cached using
#   packed addresses as keys. Conversion to IPv6 should be simple now.
# - Added paranoid hostname lookups.
# - Added netmask qualifications for address arguments.
# - Tweaked usage info.
# 2000/04/20:
# - Added parsing and tracking of TCP and state flags.
d61 2
a62 1
#     Nov 30 04:49:37 raoul ipmon[121]: [ID 702911 local0.warning] 04:49:36.420541 hme0 @@0:34 b 205.152.16.6,58596 -> 204.60.220.24,113 PR tcp len 20 44
d144 5
a148 5
    'p'	=> 'pass',
    'P'	=> 'pass',
    'b'	=> 'block',
    'B'	=> 'block',
    'L'	=> 'log',
d155 122
a276 122
    0	=> +{
	name	=> 'echorep',
	codes	=> +{0	=> undef},
    },
    3	=> +{
	name	=> 'unreach',
	codes	=> +{
	    0	=> 'net-unr',
	    1	=> 'host-unr',
	    2	=> 'proto-unr',
	    3	=> 'port-unr',
	    4	=> 'needfrag',
	    5	=> 'srcfail',
	    6	=> 'net-unk',
	    7	=> 'host-unk',
	    8	=> 'isolate',
	    9	=> 'net-prohib',
	    10	=> 'host-prohib',
	    11	=> 'net-tos',
	    12	=> 'host-tos',
	    13	=> 'filter-prohib',
	    14	=> 'host-preced',
	    15	=> 'preced-cutoff',
	},
    },
    4	=> +{
	name	=> 'squench',
	codes	=> +{0	=> undef},
    },
    5	=> +{
	name	=> 'redir',
	codes	=> +{
	    0	=> 'net',
	    1	=> 'host',
	    2	=> 'tos',
	    3	=> 'tos-host',
	},
    },
    6	=> +{
	name	=> 'alt-host-addr',
	codes	=> +{
	    0	=> 'alt-addr'
	},
    },
    8	=> +{
	name	=> 'echo',
	codes	=> +{0	=> undef},
    },
    9	=> +{
	name	=> 'routerad',
	codes	=> +{0	=> undef},
    },
    10	=> +{
	name	=> 'routersol',
	codes	=> +{0	=> undef},
    },
    11	=> +{
	name	=> 'timex',
	codes	=> +{
	    0	=> 'in-transit',
	    1	=> 'frag-assy',
	},
    },
    12	=> +{
	name	=> 'paramprob',
	codes	=> +{
	    0	=> 'ptr-err',
	    1	=> 'miss-opt',
	    2	=> 'bad-len',
	},
    },
    13	=> +{
	name	=> 'timest',
	codes	=> +{0	=> undef},
    },
    14	=> +{
	name	=> 'timestrep',
	codes	=> +{0	=> undef},
    },
    15	=> +{
	name	=> 'inforeq',
	codes	=> +{0	=> undef},
    },
    16	=> +{
	name	=> 'inforep',
	codes	=> +{0	=> undef},
    },
    17	=> +{
	name	=> 'maskreq',
	codes	=> +{0	=> undef},
    },
    18	=> +{
	name	=> 'maskrep',
	codes	=> +{0	=> undef},
    },
    30	=> +{
	name	=> 'tracert',
	codes	=> +{ },
    },
    31	=> +{
	name	=> 'dgram-conv-err',
	codes	=> +{ },
    },
    32	=> +{
	name	=> 'mbl-host-redir',
	codes	=> +{ },
    },
    33	=> +{
	name	=> 'ipv6-whereru?',
	codes	=> +{ },
    },
    34	=> +{
	name	=> 'ipv6-iamhere',
	codes	=> +{ },
    },
    35	=> +{
	name	=> 'mbl-reg-req',
	codes	=> +{ },
    },
    36	=> +{
	name	=> 'mbl-reg-rep',
	codes	=> +{ },
d281 7
a287 9
my $numeric = 0;	# Don't lookup hostnames.
my $paranoid = 0;	# Do paranoid hostname lookups.
my $verbosity = 0;	# Bla' bla' bla'.
my $sTable = 0;		# Generate source table.
my $dTable = 0;		# Generate destination table.
my @@services = ();	# Preload services tables.
my $showFlags = 0;	# Show TCP flag combinations.
my %selectAddrs;	# Limit report to these hosts.
my %selectActs;		# Limit report to these actions.
d294 54
a347 60
	while (s/^([vnpSD\?hsAF])//)
	{
	    my $flag = $1;
	    if ($flag eq 'v')
	    {
		++$verbosity;
	    }
	    elsif ($flag eq 'n')
	    {
		$numeric = 1;
	    }
	    elsif ($flag eq 'p')
	    {
		$paranoid = 1;
	    }
	    elsif ($flag eq 'S')
	    {
		$sTable = 1;
	    }
	    elsif ($flag eq 'D')
	    {
		$dTable = 1;
	    }
	    elsif ($flag eq 'F')
	    {
		$showFlags = 1;
	    }
	    elsif (($flag eq '?') || ($flag eq 'h'))
	    {
		&usage (0);
	    }
	    else
	    {
		my $arg = shift;
		defined ($arg) || &usage (1, qq{-$flag requires an argument});
		if ($flag eq 's')
		{
		    push (@@services, $arg);
		}
		elsif ($flag eq 'A')
		{
		    my @@acts = split (/,/, $arg);
		    my $a;
		    foreach $a (@@acts)
		    {
			my $aa;
			my $match = 0;
			foreach $aa (keys (%acts))
			{
			    if ($acts{$aa} eq $a)
			    {
				++$match;
				$selectActs{$aa} = $a;
			    }
			}
			$match || &usage (1, qq{unknown action $a});
		    }
		}
	    }
	}
d349 1
a349 1
	&usage (1, qq{unknown option: -$_}) if (length);
d351 1
a351 1
	next;
d355 3
a357 26
    (/^(.+)\/([\d+\.]+)$/) || (/^(.+)$/) || &usage (1, qq{invalid CIDR address $_});
    my ($addr, $mask) = ($1, $2);
    my @@addr = &hostAddrs ($addr);
    (scalar (@@addr)) || &usage (1, qq{cannot resolve hostname $_});
    if (!defined ($mask))
    {
	$mask = (2 ** 32) - 1;
    }
    elsif (($mask =~ /^\d+$/) && ($mask <= 32))
    {
	$mask = (2 ** 32) - 1 - ((2 ** (32 - $mask)) - 1);
    }
    elsif (defined ($mask = &isDottedAddr ($mask)))
    {
	$mask = &integerAddr ($mask);
    }
    else
    {
	&usage (1, qq{invalid CIDR address $_});
    }
    foreach $addr (@@addr)
    {
	# Save mask unless we already have a less specific one for this address.
	my $a = &integerAddr ($addr) & $mask;
	$selectAddrs{$a} = $mask unless (exists ($selectAddrs{$a}) && ($selectAddrs{$a} < $mask));
    }
d367 1
a367 1
my $selectAddrs = scalar (keys (%selectAddrs));
d379 2
a380 3
# Preload any services maps.
my $sm;
foreach $sm (@@services)
d382 2
a383 2
    my $sf = new IO::File ($sm, "r");
    defined ($sf) || &quit (1, qq{cannot open services file $sm});
d387 20
a406 20
	my $text = $_;
	chomp;
	s/#.*$//;
	s/\s+$//;
	next unless (length);
	my ($name, $spec, @@aliases) = split (/\s+/);
	($spec =~ /^([\w\-]+)\/([\w\-]+)$/)
	    || &quit (1, qq{$sm:$.: invalid definition: $text});
	my ($pnum, $proto) = ($1, $2);

	# Enter service definition in pn hash both forwards and backwards.
	my $port;
	my $pname;
	foreach $port ($name, @@aliases)
	{
	    $pname = "$pnum/$proto";
	    $pn{$pname} = $port;
	}
	$pname = "$name/$proto";
	$pn{$pname} = $pnum;
d412 3
a414 5
# Cache for host name -> addr mappings.
my %ipAddr;

# Cache for host addr -> name mappings.
my %ipName;
d436 2
a437 1
    if (s/^\w+\s+\d+\s+\d+:\d+:\d+\s+(?:\d\w:)?[\w\.\-]+\s+\S*ipmon\[\d+\]:\s+(?:\[ID\s+\d+\s+[\w\.]+\]\s+)?\d+:\d+:\d+\.\d+\s+//)
d439 1
a439 1
	$log = $_;
d443 1
a443 1
	$log = $_;
d447 2
a448 2
	# It don't look like no ipmon output to me, baby.
	next;
d460 2
a461 1
    my @@fields = ($log =~ /^(?:(\d+)x)?\s*(\w+)\s+@@(\d+):(\d+)\s+(\w)\s+([\w\-\.,]+)\s+->\s+([\w\-\.,]+)\s+PR\s+(\w+)\s+len\s+(\d+)\s+\(?(\d+)\)?\s*(.*)$/ox);
d464 2
a465 2
	print STDERR "$me:$.: cannot parse: $_\n";
	next;
d467 2
a468 1
    my ($count, $if, $group, $rule, $act, $src, $dest, $proto, $hlen, $len, $more) = @@fields;
d476 1
a476 1
    my ($sport, $dport, @@flags);
d480 12
a491 12
	if ($more =~ s/^icmp (\d+)\/(\d+)\s*//)
	{
	    # We save icmp type and code in both sport and dport. This
	    # allows us to sort icmp packets using the normal port-sorting
	    # code.
	    $dport = $sport = "$1.$2";
	}
	else
	{
	    $sport = '';
	    $dport = '';
	}
d495 16
a510 27
	if ($showFlags)
	{
	    if (($proto eq 'tcp') && ($more =~ s/^\-([A-Z]+)\s*//))
	    {
		push (@@flags, $1);
	    }
	    if ($more =~ s/^K\-S\s*//)
	    {
		push (@@flags, 'state');
	    }
	}
	if ($src =~ s/,([\-\w]+)$//)
	{
	    $sport = &portSimplify ($1, $proto);
	}
	else
	{
	    $sport = '';
	}
	if ($dest =~ s/,([\-\w]+)$//)
	{
	    $dport = &portSimplify ($1, $proto);
	}
	else
	{
	    $dport = '';
	}
d514 2
a515 3
    # IP address later. If the hostname doesn't resolve, punt. If you
    # must use ipmon -n, be ready for weirdness. Use only the first
    # address returned.
d517 1
a517 1
    $x = (&hostAddrs ($src))[0];
d520 2
a521 2
	print STDERR "$me:$.: cannot resolve hostname $src\n";
	next;
d524 1
a524 1
    $x = (&hostAddrs ($dest))[0];
d527 2
a528 2
	print STDERR "$me:$.: cannot resolve hostname $dest\n";
	next;
d533 2
a534 16
    if ($selectAddrs)
    {
	my ($a, $m);
	my $s = &integerAddr ($src);
	my $d = &integerAddr ($dest);
	my $cute = 0;
	while (($a, $m) = each (%selectAddrs))
	{
	    if ((($s & $m) == $a) || (($d & $m) == $a))
	    {
		$cute = 1;
		last;
	    }
	}
	next unless ($cute);
    }
d541 1
a541 1
	my ($host, $dir, $peer, $proto, $count, $packet, @@flags) = @@_;
d543 23
a565 25
	# Make sure host is in the hosts hash.
	$hosts{$host} =
	    +{
		'd'	=> +{ },
		's'	=> +{ },
	    } unless (exists ($hosts{$host}));

	# Get the source/destination traffic hash for the host in question.
	my $trafficHash = $hosts{$host}->{$dir};

	# Make sure there's a hash for the peer.
	$trafficHash->{$peer} = +{ } unless (exists ($trafficHash->{$peer}));

	# Make sure the peer hash has a hash for the protocol number.
	my $peerHash = $trafficHash->{$peer};
	$peerHash->{$proto} = +{ } unless (exists ($peerHash->{$proto}));

	# Make sure there's a counter for this packet type in the proto hash.
	my $protoHash = $peerHash->{$proto};
	$protoHash->{$packet} = +{ '' => 0 } unless (exists ($protoHash->{$packet}));

	# Increment the counter and mark flags.
	my $packetHash = $protoHash->{$packet};
	$packetHash->{''} += $count;
	map { $packetHash->{$_} = undef; } (@@flags);
d569 2
a570 1
    &countPacket ($src, 's', $dest, $proto, $count, "$sport:$dport:$if:$act", @@flags) if ($sTable);
d573 2
a574 1
    &countPacket ($dest, 'd', $src, $proto, $count, "$dport:$sport:$if:$act", @@flags) if ($dTable);
d589 4
a592 1
	&integerAddr ($a) <=> &integerAddr ($b);
d597 4
a600 3
	my ($asport, $adport, $aif, $aact) = split (/:/, $a);
	my ($bsport, $bdport, $bif, $bact) = split (/:/, $b);
	$bact cmp $aact || $aif cmp $bif || $asport <=> $bsport || $adport <=> $bdport;
d606 1
a606 1
	my $traffic = $hosts{$host}->{$dir};
d608 2
a609 2
	# Skip hosts with no traffic.
	next unless (scalar (keys (%{$traffic})));
d611 45
a655 52
	if ($numeric)
	{
	    print &dottedAddr ($host), "\n";
	}
	else
	{
	    print &hostName ($host), " \[", &dottedAddr ($host), "\]\n";
	}

	my $peer;
	foreach $peer (sort ipSort (keys %{$traffic}))
	{
	    my $peerHash = $traffic->{$peer};
	    my $peerName = ($numeric ? &dottedAddr ($peer) : &hostName ($peer));
	    my $proto;
	    foreach $proto (sort (keys (%{$peerHash})))
	    {
		my $protoHash = $peerHash->{$proto};
		my $protoName = &protoName ($proto);

		my $packet;
		foreach $packet (sort packetSort (keys %{$protoHash}))
		{
		    my ($sport, $dport, $if, $act) = split (/:/, $packet);
		    my $packetHash = $protoHash->{$packet};
		    my $count = $packetHash->{''};
		    $act = '?' unless (defined ($act = $acts{$act}));
		    if (($protoName eq 'tcp') || ($protoName eq 'udp'))
		    {
			printf ("    %-6s %7s %4d %4s %16s %2s %s.%s", $if, $act, $count, $protoName, &portName ($sport, $protoName), $arrow, $peerName, &portName ($dport, $protoName));
		    }
		    elsif ($protoName eq 'icmp')
		    {
			printf ("    %-6s %7s %4d %4s %16s %2s %s", $if, $act, $count, $protoName, &icmpType ($sport), $arrow, $peerName);
		    }
		    else
		    {
			printf ("    %-6s %7s %4d %4s %16s %2s %s", $if, $act, $count, $protoName, '', $arrow, $peerName);
		    }
		    if ($showFlags)
		    {
			my @@flags = sort (keys (%{$packetHash}));
			if (scalar (@@flags))
			{
			    shift (@@flags);
			    print ' (', join (',', @@flags), ')' if (scalar (@@flags));
			}
		    }
		    print "\n";
		}
	    }
	}
d674 3
a676 2
	my $name = getservbyport ($port, $proto);
	$pn{$pname} = (defined ($name) ? $name : ($port <= 1023 ? $port : '<high>'));
d689 10
a698 10
	my $number = getservbyname ($port, $proto);
	unless (defined ($number))
	{
	    # I don't think we need to recover from this. How did the port
	    # name get into the log file if we can't find it? Log file from
	    # a different machine? Fix /etc/services on this one if that's
	    # your problem.
	    die ("Unrecognized port name \"$port\" at $.");
	}
	$pn{$pname} = $number;
d712 1
a712 1
	unless ($port =~ /^\d+$/);
d725 2
a726 2
# Translates a numeric address into a hostname. Pass only packed numeric
# addresses to this routine.
d730 2
a731 37
    return $ipName{$ip} if (exists ($ipName{$ip}));

    # Do an inverse lookup on the address.
    my $name = gethostbyaddr ($ip, AF_INET);
    unless (defined ($name))
    {
	# Inverse lookup failed, so map the IP address to its dotted
	# representation and cache that.
	$ipName{$ip} = &dottedAddr ($ip);
	return $ipName{$ip};
    }

    # For paranoid hostname lookups.
    if ($paranoid)
    {
	# If this address already matches, we're happy.
	unless (exists ($ipName{$ip}) && (lc ($ipName{$ip}) eq lc ($name)))
	{
	    # Do a forward lookup on the resulting name.
	    my @@addr = &hostAddrs ($name);
	    my $match = 0;

	    # Cache the forward lookup results for future inverse lookups,
	    # but don't stomp on inverses we've already cached, even if they
	    # are questionable. We want to generate consistent output, and
	    # the cache is growing incrementally.
	    foreach (@@addr)
	    {
		$ipName{$_} = $name unless (exists ($ipName{$_}));
		$match = 1 if ($_ eq $ip);
	    }

	    # Was this one of the addresses? If not, tack on a ?.
	    $name .= '?' unless ($match);
	}
    }
    else
d733 14
a746 2
	# Just believe it and cache it.
	$ipName{$ip} = $name;
d748 1
a748 2

    return $name;
d751 2
a752 3
# Translates a hostname or dotted address into a list of packed numeric
# addresses.
sub hostAddrs
d755 1
a755 14
    my $ip;

    # Check if it's a dotted representation.
    return ($ip) if (defined ($ip = &isDottedAddr ($name)));

    # Return result from cache.
    $name = lc ($name);
    return @@{$ipAddr{$name}} if (exists ($ipAddr{$name}));

    # Look up the addresses.
    my @@addr = gethostbyname ($name);
    splice (@@addr, 0, 4);

    unless (scalar (@@addr))
d757 18
a774 9
	# Again, I don't think we need to recover from this gracefully.
	# If we can't resolve a hostname that ended up in the log file,
	# punt. We want to be able to sort hosts by IP address later,
	# and letting hostnames through will snarl up that code. Users
	# of ipmon -n will have to grin and bear it for now. The
	# functions that get undef back should treat it as an error or
	# as some default address, e.g. 0 just to make things work.
	return ();
    }
d776 2
a777 17
    $ipAddr{$name} = [ @@addr ];
    return @@{$ipAddr{$name}};
}

# If the argument is a valid dotted address, returns the corresponding
# packed numeric address, otherwise returns undef.
sub isDottedAddr
{
    my $addr = shift;
    if ($addr =~ /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/)
    {
	my @@a = (int ($1), int ($2), int ($3), int ($4));
	foreach (@@a)
	{
	    return undef if ($_ >= 256);
	}
	return pack ('C*', @@a);
d779 1
a779 26
    return undef;
}

# Unpacks a packed numeric address and returns an integer representation.
sub integerAddr
{
    my $addr = shift;
    return unpack ('N', $addr);

    # The following is for generalized IPv4/IPv6 stuff. For now, it's a
    # lot faster to assume IPv4.
    my @@a = unpack ('C*', $addr);
    my $a = 0;
    while (scalar (@@a))
    {
	$a = ($a << 8) | shift (@@a);
    }
    return $a;
}

# Unpacks a packed numeric address into a dotted representation.
sub dottedAddr
{
    my $addr = shift;
    my @@a = unpack ('C*', $addr);
    return join ('.', @@a);
d790 9
a798 9
	my $name = scalar (getprotobynumber ($code));
	if (defined ($name))
	{
	    $pr{$code} = $name;
	}
	else
	{
	    $pr{$code} = $code;
	}
d810 9
a818 9
	my $code = scalar (getprotobyname ($name));
	if (defined ($code))
	{
	    $pr{$name} = $code;
	}
	else
	{
	    $pr{$name} = $name;
	}
d838 2
a839 2
	$codeName = $info->{codes}->{$code};
	$codeName = (defined ($codeName) ? "/$codeName" : '');
d843 1
a843 1
	$codeName = "/$code";
d864 1
a864 1
	print STDERR "$me: ", join ("\n", @@msg), "\n\n";
d867 2
a868 2
    print <<EOT;
usage: $me [-nSDF] [-s servicemap] [-A act1,...] [address...]
d879 1
a879 1
    iface action packet-count proto src-port dest-host.dest-port \[\(flags\)\]
d881 1
a881 1
    iface action packet-count proto dest-port src-host.src-port \[\(flags\)\]
a884 1
-p           Perform paranoid hostname lookups.
a886 1
-F           Show all flag combinations associated with packets.
d888 1
a888 1
	     be in the same format as /etc/services. Any service name not found
d890 7
a896 7
-A act1,...  Limit the report to the specified actions. The possible actions
	     are pass, block, log, short, and nomatch.

If any addresses are supplied on the command line, the report is limited to
these hosts. Addresses may be given as dotted IP addresses or hostnames, and
may be qualified with netmasks in CIDR \(/24\) or dotted \(/255.255.255.0\) format.
If a hostname resolves to multiple addresses, all addresses are used.
d915 2
@


1.1.1.2
log
@Import IP Filter 3.4.4 into FreeBSD-current
@
text
@d3 3
a5 3
# Author: Jefferson Ogata (JO317) <jogata@@pobox.com>
# Date: 2000/04/10
# Version: 0.8
d17 4
a20 21
# Present lines from ipmon to this program on standard input.
#
# EXAMPLES
#
# plog -A block,log < /var/log/ipf
#
#    Generate source and destination reports of all packets logged with
#    block or log actions.
#
# plog -S -s ./services www.example.com < /var/log/ipf
#
#    Generate a source report of traffic to or from www.example.com using
#    the additional services defined in ./services.
#
# plog -nSA block < /var/log/ipf
#
#    Generate a source report of all blocked packets with no hostname
#    lookups. This is handy for an initial pass to identify portscans or
#    other aggressive traffic.
#
# TODO
d22 1
a25 47
# - It looks as though short TCP or UDP packets will break things, but I
#   haven't seen any yet.
#
# CHANGES
#
# 2000/04/12 (0.9):
# - Wasn't handling underscore in hostname,servicename fields; these may be
#   logged using ipmon -n. Observation by <ark@@eltex.ru>.
# - Hadn't properly attributed observation and fix for repetition counter in
#   0.8 change log. Added John Ladwig to attribution. Thanks, John.
#
# 2000/04/10 (0.8):
# - Service names can also have hyphens, dummy. I wasn't allowing these
#   either. Observation and fix thanks to Taso N. Devetzis
#   <devetzis@@snet.net>.
# - IP Filter now logs a repetition counter. Observation and fixes (changed
#   slightly) from Andy Kreiling <Andy@@ntcs-inc.com> and John Ladwig
#   <jladwig@@nts.umn.edu>.
# - Added fix to handle new Solaris log format, e.g.:
#     Nov 30 04:49:37 raoul ipmon[121]: [ID 702911 local0.warning] 04:49:36.420
541 hme0 @@0:34 b 205.152.16.6,58596 -> 204.60.220.24,113 PR tcp len 20 44
#   Fix thanks to Taso N. Devetzis <devetzis@@SNET.Net>.
# - Added services map option.
# - Added options for generating only source/destination tables.
# - Added verbosity option.
# - Added option for reporting traffic for specific hosts.
# - Added some more ICMP unreachable codes, and made code and type names
#   match the ones in IP Filter parse.c.
# - Condensed output format somewhat.
# - Various minor improvements, perhaps slight speed improvements.
# - Documented new options in usage() and tried to improve wording.
#
# 1999/08/02 (0.7):
# - Hostnames can have hyphens, dummy. I wasn't allowing them in the syslog
#   line. Fix from Antoine Verheijen <antoine.verheijen@@ualberta.ca>.
#
# 1999/05/05 (0.6):
# - IRIX syslog prefixes the hostname with a severity code. Handle it. Fix
#   from John Ladwig <jladwig@@nts.umn.edu>.
#
# 1999/05/05 (0.5):
# - Protocols other than TCP, UDP, or ICMP have packet lengths reported in
#   parentheses for some reason. The script now handles this. Thanks to
#   Dispatcher <dispatch@@blackhelicopters.org>.
# - I had mixed up info-request and info-reply ICMP codes, and omitted the
#   traceroute code. Sorted this out. I had also missed code 0 for type 6
#   (alternate address for host). Thanks to John Ladwig <jladwig@@nts.umn.edu>.
d27 1
d35 4
a38 5
#   vulnerable to forgery) and keep your logged addresses all in numeric
#   format, so that packets from the same source will always show the same
#   source address regardless of what's up with DNS. Obviously, I don't
#   favor using ipmon -n. Nevertheless, some people wanted this, so here it
#   is.
d44 2
a45 3
# - Put the script back up on the web site. I had moved the site and
#   forgotten to move the tool.
#
a48 1
#
a51 1
#
a56 1
#
a64 1
use IO::File;
d66 1
a66 1
select STDOUT; $| = 1;
d71 9
a79 1
$me =~ s/^.*\///;
d84 5
a88 5
    'p' => 'pass',
    'P' => 'pass',
    'b' => 'block',
    'B' => 'block',
    'L' => 'log',
a92 137
# Map of ICMP types and their relevant codes.
my %icmpTypeMap = (
    0   => +{
        name    => 'echorep',
        codes   => +{0  => undef},
    },
    3   => +{
        name    => 'unreach',
        codes   => +{
            0   => 'net-unr',
            1   => 'host-unr',
            2   => 'proto-unr',
            3   => 'port-unr',
            4   => 'needfrag',
            5   => 'srcfail',
            6   => 'net-unk',
            7   => 'host-unk',
            8   => 'isolate',
            9   => 'net-prohib',
            10  => 'host-prohib',
            11  => 'net-tos',
            12  => 'host-tos',
            13  => 'filter-prohib',
            14  => 'host-preced',
            15  => 'preced-cutoff',
        },
    },
    4   => +{
        name    => 'squench',
        codes   => +{0  => undef},
    },
    5   => +{
        name    => 'redir',
        codes   => +{
            0   => 'net',
            1   => 'host',
            2   => 'tos',
            3   => 'tos-host',
        },
    },
    6   => +{
        name    => 'alt-host-addr',
        codes   => +{
            0   => 'alt-addr'
        },
    },
    8   => +{
        name    => 'echo',
        codes   => +{0  => undef},
    },
    9   => +{
        name    => 'routerad',
        codes   => +{0  => undef},
    },
    10  => +{
        name    => 'routersol',
        codes   => +{0  => undef},
    },
    11  => +{
        name    => 'timex',
        codes   => +{
            0   => 'in-transit',
            1   => 'frag-assy',
        },
    },
    12  => +{
        name    => 'paramprob',
        codes   => +{
            0   => 'ptr-err',
            1   => 'miss-opt',
            2   => 'bad-len',
        },
    },
    13  => +{
        name    => 'timest',
        codes   => +{0  => undef},
    },
    14  => +{
        name    => 'timestrep',
        codes   => +{0  => undef},
    },
    15  => +{
        name    => 'inforeq',
        codes   => +{0  => undef},
    },
    16  => +{
        name    => 'inforep',
        codes   => +{0  => undef},
    },
    17  => +{
        name    => 'maskreq',
        codes   => +{0  => undef},
    },
    18  => +{
        name    => 'maskrep',
        codes   => +{0  => undef},
    },
    30  => +{
        name    => 'tracert',
        codes   => +{ },
    },
    31  => +{
        name    => 'dgram-conv-err',
        codes   => +{ },
    },
    32  => +{
        name    => 'mbl-host-redir',
        codes   => +{ },
    },
    33  => +{
        name    => 'ipv6-whereru?',
        codes   => +{ },
    },
    34  => +{
        name    => 'ipv6-iamhere',
        codes   => +{ },
    },
    35  => +{
        name    => 'mbl-reg-req',
        codes   => +{ },
    },
    36  => +{
        name    => 'mbl-reg-rep',
        codes   => +{ },
    },
);

# Arguments we will parse from argument list.
my $numeric = 0;        # Don't lookup hostnames.
my $verbosity = 0;      # Bla' bla' bla'.
my $sTable = 0;         # Generate source table.
my $dTable = 0;         # Generate destination table.
my $services = undef;   # Preload services table.
my %selectHosts;        # Limit report to these hosts.
my %selectActs;         # Limit report to these actions.

# Parse argument list.
d97 4
a100 113
        while (s/^([nSD\?hsA])//)
        {
            my $flag = $1;
            if ($flag eq 'v')
            {
                ++$verbosity;
            }
            elsif ($flag eq 'n')
            {
                $numeric = 1;
            }
            elsif ($flag eq 'S')
            {
                $sTable = 1;
            }
            elsif ($flag eq 'D')
            {
                $dTable = 1;
            }
            elsif (($flag eq '?') || ($flag eq 'h'))
            {
                &usage (0);
            }
            else
            {
                my $arg = shift;
                defined ($arg) || &usage (1, qq{-$flag requires an argument});
                if ($flag eq 's')
                {
                    defined ($services) && &usage (1, qq{too many service maps}
);
                    $services = $arg;
                }
                elsif ($flag eq 'A')
                {
                    my @@acts = split (/,/, $arg);
                    my $a;
                    foreach $a (@@acts)
                    {
                        my $aa;
                        my $match = 0;
                        foreach $aa (keys (%acts))
                        {
                            if ($acts{$aa} eq $a)
                            {
                                ++$match;
                                $selectActs{$aa} = $a;
                            }
                        }
                        $match || &usage (1, qq{unknown action $a});
                    }
                }
            }
        }

        &usage (1, qq{unknown option: -$_}) if (length);

        next;
    }

    # Add host to hash of hosts we're interested in.
    my $addr = &hostNumber ($_);
    defined ($addr) || &usage (1, qq{cannot resolve hostname $_});
    $selectHosts{$addr} = undef;
}

# Which tables will we generate?
$dTable = $sTable = 1 unless ($dTable || $sTable);
my @@dirs;
push (@@dirs, 'd') if ($dTable);
push (@@dirs, 's') if ($sTable);

# Are we interested in specific hosts?
my $selectHosts = scalar (keys (%selectHosts));

# Are we interested in specific actions?
if (scalar (keys (%selectActs)) == 0)
{
    %selectActs = %acts;
}

# We use this hash to cache port name -> number and number -> name mappings.
# Isn't it cool that we can use the same hash for both?
my %pn;

# Preload any services map.
if (defined ($services))
{
    my $sf = new IO::File ($services, "r");
    defined ($sf) || &quit (1, qq{cannot open services file $services});

    while (defined ($_ = $sf->getline ()))
    {
        my $text = $_;
        chomp;
        s/#.*$//;
        s/\s+$//;
        next unless (length);
        my ($name, $spec, @@aliases) = split (/\s+/);
        ($spec =~ /^([\w\-]+)\/([\w\-]+)$/)
            || &quit (1, qq{$services:$.: invalid definition: $text});
        my ($pnum, $proto) = ($1, $2);

        # Enter service definition in pn hash both forwards and backwards.
        my $port;
        my $pname;
        foreach $port ($name, @@aliases)
        {
            $pname = "$pnum/$proto";
            $pn{$pname} = $port;
        }
        $pname = "$name/$proto";
        $pn{$pname} = $pnum;
d102 1
a102 2

    $sf->close ();
a104 13
# Again, we can use the same hash for both host name -> IP mappings and
# IP -> name mappings.
my %ip;

# Hash for protocol number <--> name mappings.
my %pr;

# Under IPv4 port numbers are unsigned shorts. The value below is higher
# than the maximum value of an unsigned short, and is used in place of
# high port numbers that don't correspond to known services. This makes
# high ports get sorted behind all others.
my $highPort = 0x10000;

d110 6
a115 8
    # timestamp, an optional severity code (IRIX), the hostname,
    # "ipmon"[process id]: prefixed to the line. For output that was
    # written directly to a file by ipmon, we'll have a date prefix as
    # dd/mm/yyyy (no y2k problem here!). Both formats then have a packet
    # timestamp and the log info.
    my ($log);
    if (s/^\w+\s+\d+\s+\d+:\d+:\d+\s+(?:\d\w:)?[\w\.\-]+\s+\S*ipmon\[\d+\]:\s+(
?:\[ID\s+\d+\s+[\w\.]+\]\s+)?\d+:\d+:\d+\.\d+\s+//)
d117 2
a118 1
        $log = $_;
d120 1
a120 1
    elsif (s/^(?:\d+\/\d+\/\d+)\s+(?:\d+:\d+:\d+\.\d+)\s+//)
d122 2
a123 1
        $log = $_;
d127 2
a128 2
        # It don't look like no ipmon output to me, baby.
        next;
a131 2
    print STDERR "$log\n" if ($verbosity);

d136 8
a143 8
    # packet length (which will be in parentheses for protocols other than
    # TCP, UDP, or ICMP), and maybe some additional info.
    my @@fields = ($log =~ /^(?:(\d+)x)?\s*(\w+)\s+@@(\d+):(\d+)\s+(\w)\s+([\w\-\
..,]+)\s+->\s+([\w\-\.,]+)\s+PR\s+(\w+)\s+len\s+(\d+)\s+\(?(\d+)\)?\s*(.*)$/ox);
    unless (scalar (@@fields))
    {
        print STDERR "$me:$.: cannot parse: $_\n";
        next;
a144 8
    my ($count, $if, $group, $rule, $act, $src, $dest, $proto, $hlen, $len, $mo
re) = @@fields;

    # Skip actions we're not interested in.
    next unless (exists ($selectActs{$act}));

    # Packet count defaults to 1.
    $count = 1 unless (defined ($count));
d150 10
a159 12
        if ($more =~ s/^icmp (\d+)\/(\d+)\s*//)
        {
            # We save icmp type and code in both sport and dport. This
            # allows us to sort icmp packets using the normal port-sorting
            # code.
            $dport = $sport = "$1.$2";
        }
        else
        {
            $sport = '';
            $dport = '';
        }
d163 2
a164 16
        if ($src =~ s/,([\-\w]+)$//)
        {
            $sport = &portSimplify ($1, $proto);
        }
        else
        {
            $sport = '';
        }
        if ($dest =~ s/,([\-\w]+)$//)
        {
            $dport = &portSimplify ($1, $proto);
        }
        else
        {
            $dport = '';
        }
d170 2
a171 19
    my $x;
    $x = &hostNumber ($src);
    unless (defined ($x))
    {
        print STDERR "$me:$.: cannot resolve hostname $src\n";
        next;
    }
    $src = $x;
    $x = &hostNumber ($dest);
    unless (defined ($x))
    {
        print STDERR "$me:$.: cannot resolve hostname $dest\n";
        next;
    }
    $dest = $x;

    # Skip hosts we're not interested in.
    next if ($selectHosts && !(exists ($selectHosts{$src}) || exists ($selectHo
sts{$dest})));
d178 1
a178 1
        my ($host, $dir, $peer, $proto, $count, $packet) = @@_;
d180 20
a199 20
        # Make sure host is in the hosts hash.
        $hosts{$host} =
            +{
                'd'     => +{ },
                's'     => +{ },
            } unless (exists ($hosts{$host}));

        # Get the source/destination traffic hash for the host in question.
        my $trafficHash = $hosts{$host}->{$dir};

        # Make sure there's a hash for the peer.
        $trafficHash->{$peer} = +{ } unless (exists ($trafficHash->{$peer}));

        # Make sure the peer hash has a hash for the protocol number.
        my $peerHash = $trafficHash->{$peer};
        $peerHash->{$proto} = +{ } unless (exists ($peerHash->{$proto}));

        # Make sure there's a counter for this packet type in the proto hash.
        my $protoHash = $peerHash->{$proto};
        $protoHash->{$packet} = 0 unless (exists ($protoHash->{$packet}));
d201 2
a202 2
        # Increment the counter.
        $protoHash->{$packet} += $count;
d206 1
a206 2
    &countPacket ($src, 's', $dest, $proto, $count, "$sport:$dport:$if:$act") i
f ($sTable);
d209 1
a209 2
    &countPacket ($dest, 'd', $src, $proto, $count, "$dport:$sport:$if:$act") i
f ($dTable);
d213 1
a213 1
foreach $dir (@@dirs)
d215 2
a216 2
    my $order = ($dir eq 's' ? 'source' : 'destination');
    my $arrow = ($dir eq 's' ? '->' : '<-');
a217 1
    print "###\n";
a218 1
    print "###\n";
d222 7
a228 12
        my @@a = split (/\./, $a);
        my @@b = split (/\./, $b);
        $a[0] <=> $b[0] || $a[1] <=> $b[1] || $a[2] <=> $b[2] || $a[3] <=> $b[3
];
    }

    sub packetSort
    {
        my ($asport, $adport, $aif, $aact) = split (/:/, $a);
        my ($bsport, $bdport, $bif, $bact) = split (/:/, $b);
        $bact cmp $aact || $aif cmp $bif || $asport <=> $bsport || $adport <=> 
$bdport;
d234 1
a234 1
        my $traffic = $hosts{$host}->{$dir};
d236 2
a237 2
        # Skip hosts with no traffic.
        next unless (scalar (keys (%{$traffic})));
d239 51
a289 45
        if ($numeric)
        {
            print "$host\n";
        }
        else
        {
            print &hostName ($host), " \[$host\]\n";
        }

        my $peer;
        foreach $peer (sort ipSort (keys %{$traffic}))
        {
            my $peerHash = $traffic->{$peer};
            my $peerName = &hostName ($peer);
            my $proto;
            foreach $proto (sort (keys (%{$peerHash})))
            {
                my $protoHash = $peerHash->{$proto};
                my $protoName = &protoName ($proto);

                my $packet;
                foreach $packet (sort packetSort (keys %{$protoHash}))
                {
                    my ($sport, $dport, $if, $act) = split (/:/, $packet);
                    my $count = $protoHash->{$packet};
                    $act = '?' unless (defined ($act = $acts{$act}));
                    if (($protoName eq 'tcp') || ($protoName eq 'udp'))
                    {
                        printf ("    %-6s %7s %4d %4s %16s %2s %s.%s\n", $if, $
act, $count, $protoName, &portName ($sport, $protoName), $arrow, $peerName, &po
rtName ($dport, $protoName));
                    }
                    elsif ($protoName eq 'icmp')
                    {
                        printf ("    %-6s %7s %4d %4s %16s %2s %s\n", $if, $act
, $count, $protoName, &icmpType ($sport), $arrow, $peerName);
                    }
                    else
                    {
                        printf ("    %-6s %7s %4d %4s %16s %2s %s\n", $if, $act
, $count, $protoName, '', $arrow, $peerName);
                    }
                }
            }
        }
d292 1
a292 1
    print "\n";
d297 4
d302 2
a303 2
# that do not have an entry in the services database are left numeric. High
# ports that do not have an entry in the services database are mapped
d312 2
a313 3
        my $name = getservbyport ($port, $proto);
        $pn{$pname} = (defined ($name) ? $name : ($port <= 1023 ? $port : '<hig
h>'));
d326 10
a335 10
        my $number = getservbyname ($port, $proto);
        unless (defined ($number))
        {
            # I don't think we need to recover from this. How did the port
            # name get into the log file if we can't find it? Log file from
            # a different machine? Fix /etc/services on this one if that's
            # your problem.
            die ("Unrecognized port name \"$port\" at $.");
        }
        $pn{$pname} = $number;
d349 1
a349 1
        unless ($port =~ /^\d+$/);
d362 4
d374 14
a387 14
        my $addr = inet_aton ($ip);
        my $name = gethostbyaddr ($addr, AF_INET);
        if (defined ($name))
        {
            $ip{$ip} = $name;

            # While we're at it, cache the forward lookup.
            $ip{$name} = $ip;
        }
        else
        {
            # Just map the IP address to itself. There's no reverse.
            $ip{$ip} = $ip;
        }
d398 3
a400 3
        # Return original value for dotted quads.
        my $or = int ($1) | int ($2) | int ($3) | int ($4);
        return $name if ($or == ($or & 0xff));
d404 12
a415 12
        my $addr = inet_aton ($name);
        unless (defined ($addr))
        {
            # Again, I don't think we need to recover from this. If we can't
            # resolve a hostname that ended up in the log file, punt. We
            # want to be able to sort hosts by IP address later, and letting
            # hostnames through will snarl up that code. Users of ipmon -n
            # will have to grin and bear it for now.
            return undef;
        }
        my $ip = inet_ntoa ($addr);
        $ip{$name} = $ip;
d417 2
a418 2
        # While we're at it, cache the reverse lookup.
        $ip{$ip} = $name;
d423 3
d434 9
a442 9
        my $name = scalar (getprotobynumber ($code));
        if (defined ($name))
        {
            $pr{$code} = $name;
        }
        else
        {
            $pr{$code} = $code;
        }
d454 9
a462 9
        my $code = scalar (getprotobyname ($name));
        if (defined ($code))
        {
            $pr{$name} = $code;
        }
        else
        {
            $pr{$name} = $name;
        }
d469 117
d591 1
a591 1
    my $info = $icmpTypeMap{$type};
d599 2
a600 2
        $codeName = $info->{codes}->{$code};
        $codeName = (defined ($codeName) ? "/$codeName" : '');
d604 1
a604 1
        $codeName = "/$code";
d609 1
a609 1
sub quit
a611 1
    my $msg = shift;
d613 2
a614 3
    print STDERR "$me: $msg\n";
    exit ($ec);
}
d616 11
a626 4
sub usage
{
    my $ec = shift;
    my @@msg = @@_;
d628 1
a628 4
    if (scalar (@@msg))
    {
        print STDERR "$me: ", join ("\n", @@msg), "\n\n";
    }
d630 1
a630 2
    print STDERR <<EOT;
usage: $me [-n] [-S] [-D] [-s servicemap] [-A act1,...] host...
a631 11
Parses logging from ipmon and presents it in a comprehensible format. This
program generates two reports: one organized by source address and another
organized by destination address. For the first report, source addresses are
sorted by IP address. For each address, all packets originating at the address
are presented in a tabular form, where all packets with the same source and
destination address and port are counted as a single entry. Any port number
greater than 1023 that does not match an entry in the services table is treated
as a "high" port; all high ports are coalesced into the same entry. The fields
for the source address report are:
    iface action packet-count proto src-port dest-ip dest-port
The fields for the destination address report are:
d634 15
a648 28
Options are:
-n           Disable hostname lookups, and report only IP addresses.
-S           Generate a source address report.
-D           Generate a destination address report.
-s map       Supply an alternate services map to be preloaded. The map should
             be in the same format as /etc/services. Any service name not found
             in the map will be looked for in the system services file.
-A act1,...  Limit the report to the specified actions. The possible actions ar
e
             pass, block, log, short, and nomatch.

If any hostnames are supplied on the command line, the report is limited to
these hosts. If a host has multiple addresses, only the first address will be
considered.

If neither -S nor -D is given, both reports are generated.

Note: if you are logging traffic with ipmon -n, ipmon will already have looked
up and logged addresses as hostnames where possible. This has an important side
effect: this program will translate the hostnames back into IP addresses which
may not match the original addresses of the logged packets because of numerous
DNS issues. If you care about where packets are really coming from, you simply
cannot rely on ipmon -n. An attacker with control of his reverse DNS can map
the reverse lookup to anything he likes. If you haven't logged the numeric IP
address, there's no way to discover the source of an attack reliably. For this
reason, I strongly recommend that you run ipmon without the -n option, and use
this or a similar script to do reverse lookups during analysis, rather than
during logging.
a652 2


@


1.1.1.3
log
@Import base ipfilter 3.4.9 into contrib dir.
@
text
@d323 2
a324 1
                    defined ($services) && &usage (1, qq{too many service maps});
d436 2
a437 1
    if (s/^\w+\s+\d+\s+\d+:\d+:\d+\s+(?:\d\w:)?[\w\.\-]+\s+\S*ipmon\[\d+\]:\s+(?:\[ID\s+\d+\s+[\w\.]+\]\s+)?\d+:\d+:\d+\.\d+\s+//)
d460 2
a461 1
    my @@fields = ($log =~ /^(?:(\d+)x)?\s*(\w+)\s+@@(\d+):(\d+)\s+(\w)\s+([\w\-\..,]+)\s+->\s+([\w\-\.,]+)\s+PR\s+(\w+)\s+len\s+(\d+)\s+\(?(\d+)\)?\s*(.*)$/ox);
d467 2
a468 1
    my ($count, $if, $group, $rule, $act, $src, $dest, $proto, $hlen, $len, $more) = @@fields;
d533 2
a534 1
    next if ($selectHosts && !(exists ($selectHosts{$src}) || exists ($selectHosts{$dest})));
d569 2
a570 1
    &countPacket ($src, 's', $dest, $proto, $count, "$sport:$dport:$if:$act") if ($sTable);
d573 2
a574 1
    &countPacket ($dest, 'd', $src, $proto, $count, "$dport:$sport:$if:$act") if ($dTable);
d591 2
a592 1
        $a[0] <=> $b[0] || $a[1] <=> $b[1] || $a[2] <=> $b[2] || $a[3] <=> $b[3];
d599 2
a600 1
        $bact cmp $aact || $aif cmp $bif || $asport <=> $bsport || $adport <=> $bdport;
d639 3
a641 1
                        printf ("    %-6s %7s %4d %4s %16s %2s %s.%s\n", $if, $act, $count, $protoName, &portName ($sport, $protoName), $arrow, $peerName, &portName ($dport, $protoName));
d645 2
a646 1
                        printf ("    %-6s %7s %4d %4s %16s %2s %s\n", $if, $act, $count, $protoName, &icmpType ($sport), $arrow, $peerName);
d650 2
a651 1
                        printf ("    %-6s %7s %4d %4s %16s %2s %s\n", $if, $act, $count, $protoName, '', $arrow, $peerName);
d675 2
a676 1
        $pn{$pname} = (defined ($name) ? $name : ($port <= 1023 ? $port : '<high>'));
@


1.1.1.4
log
@Import IP Filter 3.4.12
@
text
@d4 2
a5 2
# Date: 2000/04/22
# Version: 0.10
a11 1
#    http://www.antibozo.net/ogata/webtools/plog.pl
d21 1
a21 1
# plog -AF block,log < /var/log/ipf
d24 1
a24 1
#    block or log actions, and report TCP flags and keep state actions.
a36 8
# plog -SFp 192.168.0.0/24 www.example.com/24 < /var/log/ipf
#
#    Generate a source report of all packets whose source or destination
#    address is either in 192.168.0.0/24 or an address associated with
#    the host www.example.com, report packet flags and perform paranoid
#    hostname lookups. This is a handy usage for examining traffic more
#    closely after identifying a potential attack.
#
a46 8
# 2000/04/22 (0.10):
# - Restructured host name and address caches. Hosts are now cached using
#   packed addresses as keys. Conversion to IPv6 should be simple now.
# - Added paranoid hostname lookups.
# - Added netmask qualifications for address arguments.
# - Tweaked usage info.
# 2000/04/20:
# - Added parsing and tracking of TCP and state flags.
d61 2
a62 1
#     Nov 30 04:49:37 raoul ipmon[121]: [ID 702911 local0.warning] 04:49:36.420541 hme0 @@0:34 b 205.152.16.6,58596 -> 204.60.220.24,113 PR tcp len 20 44
d144 5
a148 5
    'p'	=> 'pass',
    'P'	=> 'pass',
    'b'	=> 'block',
    'B'	=> 'block',
    'L'	=> 'log',
d155 122
a276 122
    0	=> +{
	name	=> 'echorep',
	codes	=> +{0	=> undef},
    },
    3	=> +{
	name	=> 'unreach',
	codes	=> +{
	    0	=> 'net-unr',
	    1	=> 'host-unr',
	    2	=> 'proto-unr',
	    3	=> 'port-unr',
	    4	=> 'needfrag',
	    5	=> 'srcfail',
	    6	=> 'net-unk',
	    7	=> 'host-unk',
	    8	=> 'isolate',
	    9	=> 'net-prohib',
	    10	=> 'host-prohib',
	    11	=> 'net-tos',
	    12	=> 'host-tos',
	    13	=> 'filter-prohib',
	    14	=> 'host-preced',
	    15	=> 'preced-cutoff',
	},
    },
    4	=> +{
	name	=> 'squench',
	codes	=> +{0	=> undef},
    },
    5	=> +{
	name	=> 'redir',
	codes	=> +{
	    0	=> 'net',
	    1	=> 'host',
	    2	=> 'tos',
	    3	=> 'tos-host',
	},
    },
    6	=> +{
	name	=> 'alt-host-addr',
	codes	=> +{
	    0	=> 'alt-addr'
	},
    },
    8	=> +{
	name	=> 'echo',
	codes	=> +{0	=> undef},
    },
    9	=> +{
	name	=> 'routerad',
	codes	=> +{0	=> undef},
    },
    10	=> +{
	name	=> 'routersol',
	codes	=> +{0	=> undef},
    },
    11	=> +{
	name	=> 'timex',
	codes	=> +{
	    0	=> 'in-transit',
	    1	=> 'frag-assy',
	},
    },
    12	=> +{
	name	=> 'paramprob',
	codes	=> +{
	    0	=> 'ptr-err',
	    1	=> 'miss-opt',
	    2	=> 'bad-len',
	},
    },
    13	=> +{
	name	=> 'timest',
	codes	=> +{0	=> undef},
    },
    14	=> +{
	name	=> 'timestrep',
	codes	=> +{0	=> undef},
    },
    15	=> +{
	name	=> 'inforeq',
	codes	=> +{0	=> undef},
    },
    16	=> +{
	name	=> 'inforep',
	codes	=> +{0	=> undef},
    },
    17	=> +{
	name	=> 'maskreq',
	codes	=> +{0	=> undef},
    },
    18	=> +{
	name	=> 'maskrep',
	codes	=> +{0	=> undef},
    },
    30	=> +{
	name	=> 'tracert',
	codes	=> +{ },
    },
    31	=> +{
	name	=> 'dgram-conv-err',
	codes	=> +{ },
    },
    32	=> +{
	name	=> 'mbl-host-redir',
	codes	=> +{ },
    },
    33	=> +{
	name	=> 'ipv6-whereru?',
	codes	=> +{ },
    },
    34	=> +{
	name	=> 'ipv6-iamhere',
	codes	=> +{ },
    },
    35	=> +{
	name	=> 'mbl-reg-req',
	codes	=> +{ },
    },
    36	=> +{
	name	=> 'mbl-reg-rep',
	codes	=> +{ },
d281 7
a287 9
my $numeric = 0;	# Don't lookup hostnames.
my $paranoid = 0;	# Do paranoid hostname lookups.
my $verbosity = 0;	# Bla' bla' bla'.
my $sTable = 0;		# Generate source table.
my $dTable = 0;		# Generate destination table.
my @@services = ();	# Preload services tables.
my $showFlags = 0;	# Show TCP flag combinations.
my %selectAddrs;	# Limit report to these hosts.
my %selectActs;		# Limit report to these actions.
d294 53
a346 60
	while (s/^([vnpSD\?hsAF])//)
	{
	    my $flag = $1;
	    if ($flag eq 'v')
	    {
		++$verbosity;
	    }
	    elsif ($flag eq 'n')
	    {
		$numeric = 1;
	    }
	    elsif ($flag eq 'p')
	    {
		$paranoid = 1;
	    }
	    elsif ($flag eq 'S')
	    {
		$sTable = 1;
	    }
	    elsif ($flag eq 'D')
	    {
		$dTable = 1;
	    }
	    elsif ($flag eq 'F')
	    {
		$showFlags = 1;
	    }
	    elsif (($flag eq '?') || ($flag eq 'h'))
	    {
		&usage (0);
	    }
	    else
	    {
		my $arg = shift;
		defined ($arg) || &usage (1, qq{-$flag requires an argument});
		if ($flag eq 's')
		{
		    push (@@services, $arg);
		}
		elsif ($flag eq 'A')
		{
		    my @@acts = split (/,/, $arg);
		    my $a;
		    foreach $a (@@acts)
		    {
			my $aa;
			my $match = 0;
			foreach $aa (keys (%acts))
			{
			    if ($acts{$aa} eq $a)
			    {
				++$match;
				$selectActs{$aa} = $a;
			    }
			}
			$match || &usage (1, qq{unknown action $a});
		    }
		}
	    }
	}
d348 1
a348 1
	&usage (1, qq{unknown option: -$_}) if (length);
d350 1
a350 1
	next;
d354 3
a356 26
    (/^(.+)\/([\d+\.]+)$/) || (/^(.+)$/) || &usage (1, qq{invalid CIDR address $_});
    my ($addr, $mask) = ($1, $2);
    my @@addr = &hostAddrs ($addr);
    (scalar (@@addr)) || &usage (1, qq{cannot resolve hostname $_});
    if (!defined ($mask))
    {
	$mask = (2 ** 32) - 1;
    }
    elsif (($mask =~ /^\d+$/) && ($mask <= 32))
    {
	$mask = (2 ** 32) - 1 - ((2 ** (32 - $mask)) - 1);
    }
    elsif (defined ($mask = &isDottedAddr ($mask)))
    {
	$mask = &integerAddr ($mask);
    }
    else
    {
	&usage (1, qq{invalid CIDR address $_});
    }
    foreach $addr (@@addr)
    {
	# Save mask unless we already have a less specific one for this address.
	my $a = &integerAddr ($addr) & $mask;
	$selectAddrs{$a} = $mask unless (exists ($selectAddrs{$a}) && ($selectAddrs{$a} < $mask));
    }
d366 1
a366 1
my $selectAddrs = scalar (keys (%selectAddrs));
d378 2
a379 3
# Preload any services maps.
my $sm;
foreach $sm (@@services)
d381 2
a382 2
    my $sf = new IO::File ($sm, "r");
    defined ($sf) || &quit (1, qq{cannot open services file $sm});
d386 20
a405 20
	my $text = $_;
	chomp;
	s/#.*$//;
	s/\s+$//;
	next unless (length);
	my ($name, $spec, @@aliases) = split (/\s+/);
	($spec =~ /^([\w\-]+)\/([\w\-]+)$/)
	    || &quit (1, qq{$sm:$.: invalid definition: $text});
	my ($pnum, $proto) = ($1, $2);

	# Enter service definition in pn hash both forwards and backwards.
	my $port;
	my $pname;
	foreach $port ($name, @@aliases)
	{
	    $pname = "$pnum/$proto";
	    $pn{$pname} = $port;
	}
	$pname = "$name/$proto";
	$pn{$pname} = $pnum;
d411 3
a413 5
# Cache for host name -> addr mappings.
my %ipAddr;

# Cache for host addr -> name mappings.
my %ipName;
d437 1
a437 1
	$log = $_;
d441 1
a441 1
	$log = $_;
d445 2
a446 2
	# It don't look like no ipmon output to me, baby.
	next;
d458 1
a458 1
    my @@fields = ($log =~ /^(?:(\d+)x)?\s*(\w+)\s+@@(\d+):(\d+)\s+(\w)\s+([\w\-\.,]+)\s+->\s+([\w\-\.,]+)\s+PR\s+(\w+)\s+len\s+(\d+)\s+\(?(\d+)\)?\s*(.*)$/ox);
d461 2
a462 2
	print STDERR "$me:$.: cannot parse: $_\n";
	next;
d472 1
a472 1
    my ($sport, $dport, @@flags);
d476 12
a487 12
	if ($more =~ s/^icmp (\d+)\/(\d+)\s*//)
	{
	    # We save icmp type and code in both sport and dport. This
	    # allows us to sort icmp packets using the normal port-sorting
	    # code.
	    $dport = $sport = "$1.$2";
	}
	else
	{
	    $sport = '';
	    $dport = '';
	}
d491 16
a506 27
	if ($showFlags)
	{
	    if (($proto eq 'tcp') && ($more =~ s/^\-([A-Z]+)\s*//))
	    {
		push (@@flags, $1);
	    }
	    if ($more =~ s/^K\-S\s*//)
	    {
		push (@@flags, 'state');
	    }
	}
	if ($src =~ s/,([\-\w]+)$//)
	{
	    $sport = &portSimplify ($1, $proto);
	}
	else
	{
	    $sport = '';
	}
	if ($dest =~ s/,([\-\w]+)$//)
	{
	    $dport = &portSimplify ($1, $proto);
	}
	else
	{
	    $dport = '';
	}
d510 2
a511 3
    # IP address later. If the hostname doesn't resolve, punt. If you
    # must use ipmon -n, be ready for weirdness. Use only the first
    # address returned.
d513 1
a513 1
    $x = (&hostAddrs ($src))[0];
d516 2
a517 2
	print STDERR "$me:$.: cannot resolve hostname $src\n";
	next;
d520 1
a520 1
    $x = (&hostAddrs ($dest))[0];
d523 2
a524 2
	print STDERR "$me:$.: cannot resolve hostname $dest\n";
	next;
d529 1
a529 16
    if ($selectAddrs)
    {
	my ($a, $m);
	my $s = &integerAddr ($src);
	my $d = &integerAddr ($dest);
	my $cute = 0;
	while (($a, $m) = each (%selectAddrs))
	{
	    if ((($s & $m) == $a) || (($d & $m) == $a))
	    {
		$cute = 1;
		last;
	    }
	}
	next unless ($cute);
    }
d536 1
a536 1
	my ($host, $dir, $peer, $proto, $count, $packet, @@flags) = @@_;
d538 23
a560 25
	# Make sure host is in the hosts hash.
	$hosts{$host} =
	    +{
		'd'	=> +{ },
		's'	=> +{ },
	    } unless (exists ($hosts{$host}));

	# Get the source/destination traffic hash for the host in question.
	my $trafficHash = $hosts{$host}->{$dir};

	# Make sure there's a hash for the peer.
	$trafficHash->{$peer} = +{ } unless (exists ($trafficHash->{$peer}));

	# Make sure the peer hash has a hash for the protocol number.
	my $peerHash = $trafficHash->{$peer};
	$peerHash->{$proto} = +{ } unless (exists ($peerHash->{$proto}));

	# Make sure there's a counter for this packet type in the proto hash.
	my $protoHash = $peerHash->{$proto};
	$protoHash->{$packet} = +{ '' => 0 } unless (exists ($protoHash->{$packet}));

	# Increment the counter and mark flags.
	my $packetHash = $protoHash->{$packet};
	$packetHash->{''} += $count;
	map { $packetHash->{$_} = undef; } (@@flags);
d564 1
a564 1
    &countPacket ($src, 's', $dest, $proto, $count, "$sport:$dport:$if:$act", @@flags) if ($sTable);
d567 1
a567 1
    &countPacket ($dest, 'd', $src, $proto, $count, "$dport:$sport:$if:$act", @@flags) if ($dTable);
d582 3
a584 1
	&integerAddr ($a) <=> &integerAddr ($b);
d589 3
a591 3
	my ($asport, $adport, $aif, $aact) = split (/:/, $a);
	my ($bsport, $bdport, $bif, $bact) = split (/:/, $b);
	$bact cmp $aact || $aif cmp $bif || $asport <=> $bsport || $adport <=> $bdport;
d597 1
a597 1
	my $traffic = $hosts{$host}->{$dir};
d599 2
a600 2
	# Skip hosts with no traffic.
	next unless (scalar (keys (%{$traffic})));
d602 41
a642 52
	if ($numeric)
	{
	    print &dottedAddr ($host), "\n";
	}
	else
	{
	    print &hostName ($host), " \[", &dottedAddr ($host), "\]\n";
	}

	my $peer;
	foreach $peer (sort ipSort (keys %{$traffic}))
	{
	    my $peerHash = $traffic->{$peer};
	    my $peerName = ($numeric ? &dottedAddr ($peer) : &hostName ($peer));
	    my $proto;
	    foreach $proto (sort (keys (%{$peerHash})))
	    {
		my $protoHash = $peerHash->{$proto};
		my $protoName = &protoName ($proto);

		my $packet;
		foreach $packet (sort packetSort (keys %{$protoHash}))
		{
		    my ($sport, $dport, $if, $act) = split (/:/, $packet);
		    my $packetHash = $protoHash->{$packet};
		    my $count = $packetHash->{''};
		    $act = '?' unless (defined ($act = $acts{$act}));
		    if (($protoName eq 'tcp') || ($protoName eq 'udp'))
		    {
			printf ("    %-6s %7s %4d %4s %16s %2s %s.%s", $if, $act, $count, $protoName, &portName ($sport, $protoName), $arrow, $peerName, &portName ($dport, $protoName));
		    }
		    elsif ($protoName eq 'icmp')
		    {
			printf ("    %-6s %7s %4d %4s %16s %2s %s", $if, $act, $count, $protoName, &icmpType ($sport), $arrow, $peerName);
		    }
		    else
		    {
			printf ("    %-6s %7s %4d %4s %16s %2s %s", $if, $act, $count, $protoName, '', $arrow, $peerName);
		    }
		    if ($showFlags)
		    {
			my @@flags = sort (keys (%{$packetHash}));
			if (scalar (@@flags))
			{
			    shift (@@flags);
			    print ' (', join (',', @@flags), ')' if (scalar (@@flags));
			}
		    }
		    print "\n";
		}
	    }
	}
d661 2
a662 2
	my $name = getservbyport ($port, $proto);
	$pn{$pname} = (defined ($name) ? $name : ($port <= 1023 ? $port : '<high>'));
d675 10
a684 10
	my $number = getservbyname ($port, $proto);
	unless (defined ($number))
	{
	    # I don't think we need to recover from this. How did the port
	    # name get into the log file if we can't find it? Log file from
	    # a different machine? Fix /etc/services on this one if that's
	    # your problem.
	    die ("Unrecognized port name \"$port\" at $.");
	}
	$pn{$pname} = $number;
d698 1
a698 1
	unless ($port =~ /^\d+$/);
d711 2
a712 2
# Translates a numeric address into a hostname. Pass only packed numeric
# addresses to this routine.
d716 2
a717 37
    return $ipName{$ip} if (exists ($ipName{$ip}));

    # Do an inverse lookup on the address.
    my $name = gethostbyaddr ($ip, AF_INET);
    unless (defined ($name))
    {
	# Inverse lookup failed, so map the IP address to its dotted
	# representation and cache that.
	$ipName{$ip} = &dottedAddr ($ip);
	return $ipName{$ip};
    }

    # For paranoid hostname lookups.
    if ($paranoid)
    {
	# If this address already matches, we're happy.
	unless (exists ($ipName{$ip}) && (lc ($ipName{$ip}) eq lc ($name)))
	{
	    # Do a forward lookup on the resulting name.
	    my @@addr = &hostAddrs ($name);
	    my $match = 0;

	    # Cache the forward lookup results for future inverse lookups,
	    # but don't stomp on inverses we've already cached, even if they
	    # are questionable. We want to generate consistent output, and
	    # the cache is growing incrementally.
	    foreach (@@addr)
	    {
		$ipName{$_} = $name unless (exists ($ipName{$_}));
		$match = 1 if ($_ eq $ip);
	    }

	    # Was this one of the addresses? If not, tack on a ?.
	    $name .= '?' unless ($match);
	}
    }
    else
d719 14
a732 2
	# Just believe it and cache it.
	$ipName{$ip} = $name;
d734 1
a734 2

    return $name;
d737 2
a738 3
# Translates a hostname or dotted address into a list of packed numeric
# addresses.
sub hostAddrs
d741 1
a741 14
    my $ip;

    # Check if it's a dotted representation.
    return ($ip) if (defined ($ip = &isDottedAddr ($name)));

    # Return result from cache.
    $name = lc ($name);
    return @@{$ipAddr{$name}} if (exists ($ipAddr{$name}));

    # Look up the addresses.
    my @@addr = gethostbyname ($name);
    splice (@@addr, 0, 4);

    unless (scalar (@@addr))
d743 18
a760 9
	# Again, I don't think we need to recover from this gracefully.
	# If we can't resolve a hostname that ended up in the log file,
	# punt. We want to be able to sort hosts by IP address later,
	# and letting hostnames through will snarl up that code. Users
	# of ipmon -n will have to grin and bear it for now. The
	# functions that get undef back should treat it as an error or
	# as some default address, e.g. 0 just to make things work.
	return ();
    }
d762 2
a763 17
    $ipAddr{$name} = [ @@addr ];
    return @@{$ipAddr{$name}};
}

# If the argument is a valid dotted address, returns the corresponding
# packed numeric address, otherwise returns undef.
sub isDottedAddr
{
    my $addr = shift;
    if ($addr =~ /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/)
    {
	my @@a = (int ($1), int ($2), int ($3), int ($4));
	foreach (@@a)
	{
	    return undef if ($_ >= 256);
	}
	return pack ('C*', @@a);
d765 1
a765 26
    return undef;
}

# Unpacks a packed numeric address and returns an integer representation.
sub integerAddr
{
    my $addr = shift;
    return unpack ('N', $addr);

    # The following is for generalized IPv4/IPv6 stuff. For now, it's a
    # lot faster to assume IPv4.
    my @@a = unpack ('C*', $addr);
    my $a = 0;
    while (scalar (@@a))
    {
	$a = ($a << 8) | shift (@@a);
    }
    return $a;
}

# Unpacks a packed numeric address into a dotted representation.
sub dottedAddr
{
    my $addr = shift;
    my @@a = unpack ('C*', $addr);
    return join ('.', @@a);
d776 9
a784 9
	my $name = scalar (getprotobynumber ($code));
	if (defined ($name))
	{
	    $pr{$code} = $name;
	}
	else
	{
	    $pr{$code} = $code;
	}
d796 9
a804 9
	my $code = scalar (getprotobyname ($name));
	if (defined ($code))
	{
	    $pr{$name} = $code;
	}
	else
	{
	    $pr{$name} = $name;
	}
d824 2
a825 2
	$codeName = $info->{codes}->{$code};
	$codeName = (defined ($codeName) ? "/$codeName" : '');
d829 1
a829 1
	$codeName = "/$code";
d850 1
a850 1
	print STDERR "$me: ", join ("\n", @@msg), "\n\n";
d853 2
a854 2
    print <<EOT;
usage: $me [-nSDF] [-s servicemap] [-A act1,...] [address...]
d865 1
a865 1
    iface action packet-count proto src-port dest-host.dest-port \[\(flags\)\]
d867 1
a867 1
    iface action packet-count proto dest-port src-host.src-port \[\(flags\)\]
a870 1
-p           Perform paranoid hostname lookups.
a872 1
-F           Show all flag combinations associated with packets.
d874 1
a874 1
	     be in the same format as /etc/services. Any service name not found
d876 7
a882 7
-A act1,...  Limit the report to the specified actions. The possible actions
	     are pass, block, log, short, and nomatch.

If any addresses are supplied on the command line, the report is limited to
these hosts. Addresses may be given as dotted IP addresses or hostnames, and
may be qualified with netmasks in CIDR \(/24\) or dotted \(/255.255.255.0\) format.
If a hostname resolves to multiple addresses, all addresses are used.
d901 2
@


1.1.1.4.56.1
log
@file plog was added on branch RELENG_8_4 on 2013-03-28 13:01:21 +0000
@
text
@d1 1061
@


1.1.1.4.56.2
log
@## SVN ## Exported commit - http://svnweb.freebsd.org/changeset/base/248810
## SVN ## CVS IS DEPRECATED: http://wiki.freebsd.org/CvsIsDeprecated
@
text
@a0 1061
#!/usr/bin/perl -wT
#
# Author: Jefferson Ogata (JO317) <jogata@@pobox.com>
# Date: 2000/04/22
# Version: 0.10
#
# Please feel free to use or redistribute this program if you find it useful.
# If you have suggestions, or even better, bits of new code, send them to me
# and I will add them when I have time. The current version of this script
# can always be found at the URL:
#
#    http://www.antibozo.net/ogata/webtools/plog.pl
#    http://pobox.com/~ogata/webtools/plog.txt
#
# Parse ipmon output into a coherent form. This program only handles the
# lines regarding filter actions. It does not parse nat and state lines.
#
# Present lines from ipmon to this program on standard input.
#
# EXAMPLES
#
# plog -AF block,log < /var/log/ipf
#
#    Generate source and destination reports of all packets logged with
#    block or log actions, and report TCP flags and keep state actions.
#
# plog -S -s ./services www.example.com < /var/log/ipf
#
#    Generate a source report of traffic to or from www.example.com using
#    the additional services defined in ./services.
#
# plog -nSA block < /var/log/ipf
#
#    Generate a source report of all blocked packets with no hostname
#    lookups. This is handy for an initial pass to identify portscans or
#    other aggressive traffic.
#
# plog -SFp 192.168.0.0/24 www.example.com/24 < /var/log/ipf
#
#    Generate a source report of all packets whose source or destination
#    address is either in 192.168.0.0/24 or an address associated with
#    the host www.example.com, report packet flags and perform paranoid
#    hostname lookups. This is a handy usage for examining traffic more
#    closely after identifying a potential attack.
#
# TODO
#
# - Handle output from ipmon -v.
# - Handle timestamps from other locales. Anyone with a timestamp problem
#   please email me the format of your timestamps.
# - It looks as though short TCP or UDP packets will break things, but I
#   haven't seen any yet.
#
# CHANGES
#
# 2000/04/22 (0.10):
# - Restructured host name and address caches. Hosts are now cached using
#   packed addresses as keys. Conversion to IPv6 should be simple now.
# - Added paranoid hostname lookups.
# - Added netmask qualifications for address arguments.
# - Tweaked usage info.
# 2000/04/20:
# - Added parsing and tracking of TCP and state flags.
# 2000/04/12 (0.9):
# - Wasn't handling underscore in hostname,servicename fields; these may be
#   logged using ipmon -n. Observation by <ark@@eltex.ru>.
# - Hadn't properly attributed observation and fix for repetition counter in
#   0.8 change log. Added John Ladwig to attribution. Thanks, John.
#
# 2000/04/10 (0.8):
# - Service names can also have hyphens, dummy. I wasn't allowing these
#   either. Observation and fix thanks to Taso N. Devetzis
#   <devetzis@@snet.net>.
# - IP Filter now logs a repetition counter. Observation and fixes (changed
#   slightly) from Andy Kreiling <Andy@@ntcs-inc.com> and John Ladwig
#   <jladwig@@nts.umn.edu>.
# - Added fix to handle new Solaris log format, e.g.:
#     Nov 30 04:49:37 raoul ipmon[121]: [ID 702911 local0.warning] 04:49:36.420541 hme0 @@0:34 b 205.152.16.6,58596 -> 204.60.220.24,113 PR tcp len 20 44
#   Fix thanks to Taso N. Devetzis <devetzis@@SNET.Net>.
# - Added services map option.
# - Added options for generating only source/destination tables.
# - Added verbosity option.
# - Added option for reporting traffic for specific hosts.
# - Added some more ICMP unreachable codes, and made code and type names
#   match the ones in IP Filter parse.c.
# - Condensed output format somewhat.
# - Various minor improvements, perhaps slight speed improvements.
# - Documented new options in usage() and tried to improve wording.
#
# 1999/08/02 (0.7):
# - Hostnames can have hyphens, dummy. I wasn't allowing them in the syslog
#   line. Fix from Antoine Verheijen <antoine.verheijen@@ualberta.ca>.
#
# 1999/05/05 (0.6):
# - IRIX syslog prefixes the hostname with a severity code. Handle it. Fix
#   from John Ladwig <jladwig@@nts.umn.edu>.
#
# 1999/05/05 (0.5):
# - Protocols other than TCP, UDP, or ICMP have packet lengths reported in
#   parentheses for some reason. The script now handles this. Thanks to
#   Dispatcher <dispatch@@blackhelicopters.org>.
# - I had mixed up info-request and info-reply ICMP codes, and omitted the
#   traceroute code. Sorted this out. I had also missed code 0 for type 6
#   (alternate address for host). Thanks to John Ladwig <jladwig@@nts.umn.edu>.
#
# 1999/05/03:
# - Now accepts hostnames in the source and destination address fields, as
#   well as port names in the port fields. This allows the people who are
#   using ipmon -n to still use plog. Note that if you are logging
#   hostnames, you are vulnerable to forgery of DNS information, modified
#   DNS information, and your log files will be larger also. If you are
#   using this program you can have it look up the names for you (still
#   vulnerable to forgery) and keep your logged addresses all in numeric
#   format, so that packets from the same source will always show the same
#   source address regardless of what's up with DNS. Obviously, I don't
#   favor using ipmon -n. Nevertheless, some people wanted this, so here it
#   is.
# - Added S and n flags to %acts hash. Thanks to Stephen J. Roznowski
#   <sjr@@home.net>.
# - Stopped reporting host IPs twice when numeric output was requested.
#   Thanks, yet again, to Stephen J. Roznowski <sjr@@home.net>.
# - Number of minor tweaks that might speed it up a bit, and some comments.
# - Put the script back up on the web site. I had moved the site and
#   forgotten to move the tool.
#
# 1999/02/04:
# - Changed log line parser to accept fully-qualified name in the logging
#   host field. Thanks to Stephen J. Roznowski <sjr@@home.net>.
#
# 1999/01/22:
# - Changed high port strategy to use 65536 for unknown high ports so that
#   they are sorted last.
#
# 1999/01/21:
# - Moved icmp parsing to output loop.
# - Added parsing of icmp codes, and more types.
# - Changed packet sort routine to sort by port number rather than service
#   name.
#
# 1999/01/20:
# - Fixed problem matching ipmon log lines. Sometimes they have "/ipmon" in
#   them, sometimes just "ipmon".
# - Added numeric parse option to turn off hostname lookups.
# - Moved summary to usage() sub.

use strict;
use Socket;
use IO::File;

select STDOUT; $| = 1;

my %hosts;

my $me = $0;
$me =~ s/^.*\///;

# Map of log codes for various actions. Not all of these can occur, but
# I've included everything in print_ipflog() from ipmon.c.
my %acts = (
    'p'	=> 'pass',
    'P'	=> 'pass',
    'b'	=> 'block',
    'B'	=> 'block',
    'L'	=> 'log',
    'S' => 'short',
    'n' => 'nomatch',
);

# Map of ICMP types and their relevant codes.
my %icmpTypeMap = (
    0	=> +{
	name	=> 'echorep',
	codes	=> +{0	=> undef},
    },
    3	=> +{
	name	=> 'unreach',
	codes	=> +{
	    0	=> 'net-unr',
	    1	=> 'host-unr',
	    2	=> 'proto-unr',
	    3	=> 'port-unr',
	    4	=> 'needfrag',
	    5	=> 'srcfail',
	    6	=> 'net-unk',
	    7	=> 'host-unk',
	    8	=> 'isolate',
	    9	=> 'net-prohib',
	    10	=> 'host-prohib',
	    11	=> 'net-tos',
	    12	=> 'host-tos',
	    13	=> 'filter-prohib',
	    14	=> 'host-preced',
	    15	=> 'preced-cutoff',
	},
    },
    4	=> +{
	name	=> 'squench',
	codes	=> +{0	=> undef},
    },
    5	=> +{
	name	=> 'redir',
	codes	=> +{
	    0	=> 'net',
	    1	=> 'host',
	    2	=> 'tos',
	    3	=> 'tos-host',
	},
    },
    6	=> +{
	name	=> 'alt-host-addr',
	codes	=> +{
	    0	=> 'alt-addr'
	},
    },
    8	=> +{
	name	=> 'echo',
	codes	=> +{0	=> undef},
    },
    9	=> +{
	name	=> 'routerad',
	codes	=> +{0	=> undef},
    },
    10	=> +{
	name	=> 'routersol',
	codes	=> +{0	=> undef},
    },
    11	=> +{
	name	=> 'timex',
	codes	=> +{
	    0	=> 'in-transit',
	    1	=> 'frag-assy',
	},
    },
    12	=> +{
	name	=> 'paramprob',
	codes	=> +{
	    0	=> 'ptr-err',
	    1	=> 'miss-opt',
	    2	=> 'bad-len',
	},
    },
    13	=> +{
	name	=> 'timest',
	codes	=> +{0	=> undef},
    },
    14	=> +{
	name	=> 'timestrep',
	codes	=> +{0	=> undef},
    },
    15	=> +{
	name	=> 'inforeq',
	codes	=> +{0	=> undef},
    },
    16	=> +{
	name	=> 'inforep',
	codes	=> +{0	=> undef},
    },
    17	=> +{
	name	=> 'maskreq',
	codes	=> +{0	=> undef},
    },
    18	=> +{
	name	=> 'maskrep',
	codes	=> +{0	=> undef},
    },
    30	=> +{
	name	=> 'tracert',
	codes	=> +{ },
    },
    31	=> +{
	name	=> 'dgram-conv-err',
	codes	=> +{ },
    },
    32	=> +{
	name	=> 'mbl-host-redir',
	codes	=> +{ },
    },
    33	=> +{
	name	=> 'ipv6-whereru?',
	codes	=> +{ },
    },
    34	=> +{
	name	=> 'ipv6-iamhere',
	codes	=> +{ },
    },
    35	=> +{
	name	=> 'mbl-reg-req',
	codes	=> +{ },
    },
    36	=> +{
	name	=> 'mbl-reg-rep',
	codes	=> +{ },
    },
);

# Arguments we will parse from argument list.
my $numeric = 0;	# Don't lookup hostnames.
my $paranoid = 0;	# Do paranoid hostname lookups.
my $verbosity = 0;	# Bla' bla' bla'.
my $sTable = 0;		# Generate source table.
my $dTable = 0;		# Generate destination table.
my @@services = ();	# Preload services tables.
my $showFlags = 0;	# Show TCP flag combinations.
my %selectAddrs;	# Limit report to these hosts.
my %selectActs;		# Limit report to these actions.

# Parse argument list.
while (defined ($_ = shift))
{
    if (s/^-//)
    {
	while (s/^([vnpSD\?hsAF])//)
	{
	    my $flag = $1;
	    if ($flag eq 'v')
	    {
		++$verbosity;
	    }
	    elsif ($flag eq 'n')
	    {
		$numeric = 1;
	    }
	    elsif ($flag eq 'p')
	    {
		$paranoid = 1;
	    }
	    elsif ($flag eq 'S')
	    {
		$sTable = 1;
	    }
	    elsif ($flag eq 'D')
	    {
		$dTable = 1;
	    }
	    elsif ($flag eq 'F')
	    {
		$showFlags = 1;
	    }
	    elsif (($flag eq '?') || ($flag eq 'h'))
	    {
		&usage (0);
	    }
	    else
	    {
		my $arg = shift;
		defined ($arg) || &usage (1, qq{-$flag requires an argument});
		if ($flag eq 's')
		{
		    push (@@services, $arg);
		}
		elsif ($flag eq 'A')
		{
		    my @@acts = split (/,/, $arg);
		    my $a;
		    foreach $a (@@acts)
		    {
			my $aa;
			my $match = 0;
			foreach $aa (keys (%acts))
			{
			    if ($acts{$aa} eq $a)
			    {
				++$match;
				$selectActs{$aa} = $a;
			    }
			}
			$match || &usage (1, qq{unknown action $a});
		    }
		}
	    }
	}

	&usage (1, qq{unknown option: -$_}) if (length);

	next;
    }

    # Add host to hash of hosts we're interested in.
    (/^(.+)\/([\d+\.]+)$/) || (/^(.+)$/) || &usage (1, qq{invalid CIDR address $_});
    my ($addr, $mask) = ($1, $2);
    my @@addr = &hostAddrs ($addr);
    (scalar (@@addr)) || &usage (1, qq{cannot resolve hostname $_});
    if (!defined ($mask))
    {
	$mask = (2 ** 32) - 1;
    }
    elsif (($mask =~ /^\d+$/) && ($mask <= 32))
    {
	$mask = (2 ** 32) - 1 - ((2 ** (32 - $mask)) - 1);
    }
    elsif (defined ($mask = &isDottedAddr ($mask)))
    {
	$mask = &integerAddr ($mask);
    }
    else
    {
	&usage (1, qq{invalid CIDR address $_});
    }
    foreach $addr (@@addr)
    {
	# Save mask unless we already have a less specific one for this address.
	my $a = &integerAddr ($addr) & $mask;
	$selectAddrs{$a} = $mask unless (exists ($selectAddrs{$a}) && ($selectAddrs{$a} < $mask));
    }
}

# Which tables will we generate?
$dTable = $sTable = 1 unless ($dTable || $sTable);
my @@dirs;
push (@@dirs, 'd') if ($dTable);
push (@@dirs, 's') if ($sTable);

# Are we interested in specific hosts?
my $selectAddrs = scalar (keys (%selectAddrs));

# Are we interested in specific actions?
if (scalar (keys (%selectActs)) == 0)
{
    %selectActs = %acts;
}

# We use this hash to cache port name -> number and number -> name mappings.
# Isn't it cool that we can use the same hash for both?
my %pn;

# Preload any services maps.
my $sm;
foreach $sm (@@services)
{
    my $sf = new IO::File ($sm, "r");
    defined ($sf) || &quit (1, qq{cannot open services file $sm});

    while (defined ($_ = $sf->getline ()))
    {
	my $text = $_;
	chomp;
	s/#.*$//;
	s/\s+$//;
	next unless (length);
	my ($name, $spec, @@aliases) = split (/\s+/);
	($spec =~ /^([\w\-]+)\/([\w\-]+)$/)
	    || &quit (1, qq{$sm:$.: invalid definition: $text});
	my ($pnum, $proto) = ($1, $2);

	# Enter service definition in pn hash both forwards and backwards.
	my $port;
	my $pname;
	foreach $port ($name, @@aliases)
	{
	    $pname = "$pnum/$proto";
	    $pn{$pname} = $port;
	}
	$pname = "$name/$proto";
	$pn{$pname} = $pnum;
    }

    $sf->close ();
}

# Cache for host name -> addr mappings.
my %ipAddr;

# Cache for host addr -> name mappings.
my %ipName;

# Hash for protocol number <--> name mappings.
my %pr;

# Under IPv4 port numbers are unsigned shorts. The value below is higher
# than the maximum value of an unsigned short, and is used in place of
# high port numbers that don't correspond to known services. This makes
# high ports get sorted behind all others.
my $highPort = 0x10000;

while (<STDIN>)
{
    chomp;

    # For ipmon output that came through syslog, we'll have an asctime
    # timestamp, an optional severity code (IRIX), the hostname,
    # "ipmon"[process id]: prefixed to the line. For output that was
    # written directly to a file by ipmon, we'll have a date prefix as
    # dd/mm/yyyy (no y2k problem here!). Both formats then have a packet
    # timestamp and the log info.
    my ($log);
    if (s/^\w+\s+\d+\s+\d+:\d+:\d+\s+(?:\d\w:)?[\w\.\-]+\s+\S*ipmon\[\d+\]:\s+(?:\[ID\s+\d+\s+[\w\.]+\]\s+)?\d+:\d+:\d+\.\d+\s+//)
    {
	$log = $_;
    }
    elsif (s/^(?:\d+\/\d+\/\d+)\s+(?:\d+:\d+:\d+\.\d+)\s+//)
    {
	$log = $_;
    }
    else
    {
	# It don't look like no ipmon output to me, baby.
	next;
    }
    next unless (defined ($log));

    print STDERR "$log\n" if ($verbosity);

    # Parse the log line. We're expecting interface name, rule group and
    # number, an action code, a source host name or IP with possible port
    # name or number, a destination host name or IP with possible port
    # number, "PR", a protocol name or number, "len", a header length, a
    # packet length (which will be in parentheses for protocols other than
    # TCP, UDP, or ICMP), and maybe some additional info.
    my @@fields = ($log =~ /^(?:(\d+)x)?\s*(\w+)\s+@@(\d+):(\d+)\s+(\w)\s+([\w\-\.,]+)\s+->\s+([\w\-\.,]+)\s+PR\s+(\w+)\s+len\s+(\d+)\s+\(?(\d+)\)?\s*(.*)$/ox);
    unless (scalar (@@fields))
    {
	print STDERR "$me:$.: cannot parse: $_\n";
	next;
    }
    my ($count, $if, $group, $rule, $act, $src, $dest, $proto, $hlen, $len, $more) = @@fields;

    # Skip actions we're not interested in.
    next unless (exists ($selectActs{$act}));

    # Packet count defaults to 1.
    $count = 1 unless (defined ($count));

    my ($sport, $dport, @@flags);

    if ($proto eq 'icmp')
    {
	if ($more =~ s/^icmp (\d+)\/(\d+)\s*//)
	{
	    # We save icmp type and code in both sport and dport. This
	    # allows us to sort icmp packets using the normal port-sorting
	    # code.
	    $dport = $sport = "$1.$2";
	}
	else
	{
	    $sport = '';
	    $dport = '';
	}
    }
    else
    {
	if ($showFlags)
	{
	    if (($proto eq 'tcp') && ($more =~ s/^\-([A-Z]+)\s*//))
	    {
		push (@@flags, $1);
	    }
	    if ($more =~ s/^K\-S\s*//)
	    {
		push (@@flags, 'state');
	    }
	}
	if ($src =~ s/,([\-\w]+)$//)
	{
	    $sport = &portSimplify ($1, $proto);
	}
	else
	{
	    $sport = '';
	}
	if ($dest =~ s/,([\-\w]+)$//)
	{
	    $dport = &portSimplify ($1, $proto);
	}
	else
	{
	    $dport = '';
	}
    }

    # Make sure addresses are numeric at this point. We want to sort by
    # IP address later. If the hostname doesn't resolve, punt. If you
    # must use ipmon -n, be ready for weirdness. Use only the first
    # address returned.
    my $x;
    $x = (&hostAddrs ($src))[0];
    unless (defined ($x))
    {
	print STDERR "$me:$.: cannot resolve hostname $src\n";
	next;
    }
    $src = $x;
    $x = (&hostAddrs ($dest))[0];
    unless (defined ($x))
    {
	print STDERR "$me:$.: cannot resolve hostname $dest\n";
	next;
    }
    $dest = $x;

    # Skip hosts we're not interested in.
    if ($selectAddrs)
    {
	my ($a, $m);
	my $s = &integerAddr ($src);
	my $d = &integerAddr ($dest);
	my $cute = 0;
	while (($a, $m) = each (%selectAddrs))
	{
	    if ((($s & $m) == $a) || (($d & $m) == $a))
	    {
		$cute = 1;
		last;
	    }
	}
	next unless ($cute);
    }

    # Convert proto to proto number.
    $proto = &protoNumber ($proto);

    sub countPacket
    {
	my ($host, $dir, $peer, $proto, $count, $packet, @@flags) = @@_;

	# Make sure host is in the hosts hash.
	$hosts{$host} =
	    +{
		'd'	=> +{ },
		's'	=> +{ },
	    } unless (exists ($hosts{$host}));

	# Get the source/destination traffic hash for the host in question.
	my $trafficHash = $hosts{$host}->{$dir};

	# Make sure there's a hash for the peer.
	$trafficHash->{$peer} = +{ } unless (exists ($trafficHash->{$peer}));

	# Make sure the peer hash has a hash for the protocol number.
	my $peerHash = $trafficHash->{$peer};
	$peerHash->{$proto} = +{ } unless (exists ($peerHash->{$proto}));

	# Make sure there's a counter for this packet type in the proto hash.
	my $protoHash = $peerHash->{$proto};
	$protoHash->{$packet} = +{ '' => 0 } unless (exists ($protoHash->{$packet}));

	# Increment the counter and mark flags.
	my $packetHash = $protoHash->{$packet};
	$packetHash->{''} += $count;
	map { $packetHash->{$_} = undef; } (@@flags);
    }

    # Count the packet as outgoing traffic from the source address.
    &countPacket ($src, 's', $dest, $proto, $count, "$sport:$dport:$if:$act", @@flags) if ($sTable);

    # Count the packet as incoming traffic to the destination address.
    &countPacket ($dest, 'd', $src, $proto, $count, "$dport:$sport:$if:$act", @@flags) if ($dTable);
}

my $dir;
foreach $dir (@@dirs)
{
    my $order = ($dir eq 's' ? 'source' : 'destination');
    my $arrow = ($dir eq 's' ? '->' : '<-');

    print "###\n";
    print "### Traffic by $order address:\n";
    print "###\n";

    sub ipSort
    {
	&integerAddr ($a) <=> &integerAddr ($b);
    }

    sub packetSort
    {
	my ($asport, $adport, $aif, $aact) = split (/:/, $a);
	my ($bsport, $bdport, $bif, $bact) = split (/:/, $b);
	$bact cmp $aact || $aif cmp $bif || $asport <=> $bsport || $adport <=> $bdport;
    }

    my $host;
    foreach $host (sort ipSort (keys %hosts))
    {
	my $traffic = $hosts{$host}->{$dir};

	# Skip hosts with no traffic.
	next unless (scalar (keys (%{$traffic})));

	if ($numeric)
	{
	    print &dottedAddr ($host), "\n";
	}
	else
	{
	    print &hostName ($host), " \[", &dottedAddr ($host), "\]\n";
	}

	my $peer;
	foreach $peer (sort ipSort (keys %{$traffic}))
	{
	    my $peerHash = $traffic->{$peer};
	    my $peerName = ($numeric ? &dottedAddr ($peer) : &hostName ($peer));
	    my $proto;
	    foreach $proto (sort (keys (%{$peerHash})))
	    {
		my $protoHash = $peerHash->{$proto};
		my $protoName = &protoName ($proto);

		my $packet;
		foreach $packet (sort packetSort (keys %{$protoHash}))
		{
		    my ($sport, $dport, $if, $act) = split (/:/, $packet);
		    my $packetHash = $protoHash->{$packet};
		    my $count = $packetHash->{''};
		    $act = '?' unless (defined ($act = $acts{$act}));
		    if (($protoName eq 'tcp') || ($protoName eq 'udp'))
		    {
			printf ("    %-6s %7s %4d %4s %16s %2s %s.%s", $if, $act, $count, $protoName, &portName ($sport, $protoName), $arrow, $peerName, &portName ($dport, $protoName));
		    }
		    elsif ($protoName eq 'icmp')
		    {
			printf ("    %-6s %7s %4d %4s %16s %2s %s", $if, $act, $count, $protoName, &icmpType ($sport), $arrow, $peerName);
		    }
		    else
		    {
			printf ("    %-6s %7s %4d %4s %16s %2s %s", $if, $act, $count, $protoName, '', $arrow, $peerName);
		    }
		    if ($showFlags)
		    {
			my @@flags = sort (keys (%{$packetHash}));
			if (scalar (@@flags))
			{
			    shift (@@flags);
			    print ' (', join (',', @@flags), ')' if (scalar (@@flags));
			}
		    }
		    print "\n";
		}
	    }
	}
    }

    print "\n";
}

exit (0);

# Translates a numeric port/named protocol to a port name. Reserved ports
# that do not have an entry in the services database are left numeric. High
# ports that do not have an entry in the services database are mapped
# to '<high>'.
sub portName
{
    my $port = shift;
    my $proto = shift;
    my $pname = "$port/$proto";
    unless (exists ($pn{$pname}))
    {
	my $name = getservbyport ($port, $proto);
	$pn{$pname} = (defined ($name) ? $name : ($port <= 1023 ? $port : '<high>'));
    }
    return $pn{$pname};
}

# Translates a named port/protocol to a port number.
sub portNumber
{
    my $port = shift;
    my $proto = shift;
    my $pname = "$port/$proto";
    unless (exists ($pn{$pname}))
    {
	my $number = getservbyname ($port, $proto);
	unless (defined ($number))
	{
	    # I don't think we need to recover from this. How did the port
	    # name get into the log file if we can't find it? Log file from
	    # a different machine? Fix /etc/services on this one if that's
	    # your problem.
	    die ("Unrecognized port name \"$port\" at $.");
	}
	$pn{$pname} = $number;
    }
    return $pn{$pname};
}

# Convert all unrecognized high ports to the same value so they are treated
# identically. The protocol should be by name.
sub portSimplify
{
    my $port = shift;
    my $proto = shift;

    # Make sure port is numeric.
    $port = &portNumber ($port, $proto)
	unless ($port =~ /^\d+$/);

    # Look up port name.
    my $portName = &portName ($port, $proto);

    # Port is an unknown high port. Return a value that is too high for a
    # port number, so that high ports get sorted last.
    return $highPort if ($portName eq '<high>');

    # Return original port number.
    return $port;
}

# Translates a numeric address into a hostname. Pass only packed numeric
# addresses to this routine.
sub hostName
{
    my $ip = shift;
    return $ipName{$ip} if (exists ($ipName{$ip}));

    # Do an inverse lookup on the address.
    my $name = gethostbyaddr ($ip, AF_INET);
    unless (defined ($name))
    {
	# Inverse lookup failed, so map the IP address to its dotted
	# representation and cache that.
	$ipName{$ip} = &dottedAddr ($ip);
	return $ipName{$ip};
    }

    # For paranoid hostname lookups.
    if ($paranoid)
    {
	# If this address already matches, we're happy.
	unless (exists ($ipName{$ip}) && (lc ($ipName{$ip}) eq lc ($name)))
	{
	    # Do a forward lookup on the resulting name.
	    my @@addr = &hostAddrs ($name);
	    my $match = 0;

	    # Cache the forward lookup results for future inverse lookups,
	    # but don't stomp on inverses we've already cached, even if they
	    # are questionable. We want to generate consistent output, and
	    # the cache is growing incrementally.
	    foreach (@@addr)
	    {
		$ipName{$_} = $name unless (exists ($ipName{$_}));
		$match = 1 if ($_ eq $ip);
	    }

	    # Was this one of the addresses? If not, tack on a ?.
	    $name .= '?' unless ($match);
	}
    }
    else
    {
	# Just believe it and cache it.
	$ipName{$ip} = $name;
    }

    return $name;
}

# Translates a hostname or dotted address into a list of packed numeric
# addresses.
sub hostAddrs
{
    my $name = shift;
    my $ip;

    # Check if it's a dotted representation.
    return ($ip) if (defined ($ip = &isDottedAddr ($name)));

    # Return result from cache.
    $name = lc ($name);
    return @@{$ipAddr{$name}} if (exists ($ipAddr{$name}));

    # Look up the addresses.
    my @@addr = gethostbyname ($name);
    splice (@@addr, 0, 4);

    unless (scalar (@@addr))
    {
	# Again, I don't think we need to recover from this gracefully.
	# If we can't resolve a hostname that ended up in the log file,
	# punt. We want to be able to sort hosts by IP address later,
	# and letting hostnames through will snarl up that code. Users
	# of ipmon -n will have to grin and bear it for now. The
	# functions that get undef back should treat it as an error or
	# as some default address, e.g. 0 just to make things work.
	return ();
    }

    $ipAddr{$name} = [ @@addr ];
    return @@{$ipAddr{$name}};
}

# If the argument is a valid dotted address, returns the corresponding
# packed numeric address, otherwise returns undef.
sub isDottedAddr
{
    my $addr = shift;
    if ($addr =~ /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/)
    {
	my @@a = (int ($1), int ($2), int ($3), int ($4));
	foreach (@@a)
	{
	    return undef if ($_ >= 256);
	}
	return pack ('C*', @@a);
    }
    return undef;
}

# Unpacks a packed numeric address and returns an integer representation.
sub integerAddr
{
    my $addr = shift;
    return unpack ('N', $addr);

    # The following is for generalized IPv4/IPv6 stuff. For now, it's a
    # lot faster to assume IPv4.
    my @@a = unpack ('C*', $addr);
    my $a = 0;
    while (scalar (@@a))
    {
	$a = ($a << 8) | shift (@@a);
    }
    return $a;
}

# Unpacks a packed numeric address into a dotted representation.
sub dottedAddr
{
    my $addr = shift;
    my @@a = unpack ('C*', $addr);
    return join ('.', @@a);
}

# Translates a protocol number into a protocol name, or a number if no name
# is found in the protocol database.
sub protoName
{
    my $code = shift;
    return $code if ($code !~ /^\d+$/);
    unless (exists ($pr{$code}))
    {
	my $name = scalar (getprotobynumber ($code));
	if (defined ($name))
	{
	    $pr{$code} = $name;
	}
	else
	{
	    $pr{$code} = $code;
	}
    }
    return $pr{$code};
}

# Translates a protocol name or number into a protocol number.
sub protoNumber
{
    my $name = shift;
    return $name if ($name =~ /^\d+$/);
    unless (exists ($pr{$name}))
    {
	my $code = scalar (getprotobyname ($name));
	if (defined ($code))
	{
	    $pr{$name} = $code;
	}
	else
	{
	    $pr{$name} = $name;
	}
    }
    return $pr{$name};
}

sub icmpType
{
    my $typeCode = shift;
    my ($type, $code) = split ('\.', $typeCode);

    return "?" unless (defined ($code));

    my $info = $icmpTypeMap{$type};

    return "\(type=$type/$code?\)" unless (defined ($info));

    my $typeName = $info->{name};
    my $codeName;
    if (exists ($info->{codes}->{$code}))
    {
	$codeName = $info->{codes}->{$code};
	$codeName = (defined ($codeName) ? "/$codeName" : '');
    }
    else
    {
	$codeName = "/$code";
    }
    return "$typeName$codeName";
}

sub quit
{
    my $ec = shift;
    my $msg = shift;

    print STDERR "$me: $msg\n";
    exit ($ec);
}

sub usage
{
    my $ec = shift;
    my @@msg = @@_;

    if (scalar (@@msg))
    {
	print STDERR "$me: ", join ("\n", @@msg), "\n\n";
    }

    print <<EOT;
usage: $me [-nSDF] [-s servicemap] [-A act1,...] [address...]

Parses logging from ipmon and presents it in a comprehensible format. This
program generates two reports: one organized by source address and another
organized by destination address. For the first report, source addresses are
sorted by IP address. For each address, all packets originating at the address
are presented in a tabular form, where all packets with the same source and
destination address and port are counted as a single entry. Any port number
greater than 1023 that does not match an entry in the services table is treated
as a "high" port; all high ports are coalesced into the same entry. The fields
for the source address report are:
    iface action packet-count proto src-port dest-host.dest-port \[\(flags\)\]
The fields for the destination address report are:
    iface action packet-count proto dest-port src-host.src-port \[\(flags\)\]

Options are:
-n           Disable hostname lookups, and report only IP addresses.
-p           Perform paranoid hostname lookups.
-S           Generate a source address report.
-D           Generate a destination address report.
-F           Show all flag combinations associated with packets.
-s map       Supply an alternate services map to be preloaded. The map should
	     be in the same format as /etc/services. Any service name not found
             in the map will be looked for in the system services file.
-A act1,...  Limit the report to the specified actions. The possible actions
	     are pass, block, log, short, and nomatch.

If any addresses are supplied on the command line, the report is limited to
these hosts. Addresses may be given as dotted IP addresses or hostnames, and
may be qualified with netmasks in CIDR \(/24\) or dotted \(/255.255.255.0\) format.
If a hostname resolves to multiple addresses, all addresses are used.

If neither -S nor -D is given, both reports are generated.

Note: if you are logging traffic with ipmon -n, ipmon will already have looked
up and logged addresses as hostnames where possible. This has an important side
effect: this program will translate the hostnames back into IP addresses which
may not match the original addresses of the logged packets because of numerous
DNS issues. If you care about where packets are really coming from, you simply
cannot rely on ipmon -n. An attacker with control of his reverse DNS can map
the reverse lookup to anything he likes. If you haven't logged the numeric IP
address, there's no way to discover the source of an attack reliably. For this
reason, I strongly recommend that you run ipmon without the -n option, and use
this or a similar script to do reverse lookups during analysis, rather than
during logging.
EOT

    exit ($ec);
}

@


