Recipe 17.20 Program: backsniff

This program logs attempts to connect to ports. It uses the Sys::Syslog module to log the connection attempt through a Unix socket, with logging level LOG_NOTICE and facility LOG_DAEMON. It uses getsockname to find out what port was connected to and getpeername to find out what machine made the connection. It uses getservbyport to convert the local port number (e.g., 7) into a service name (e.g, "echo").

It produces entries in the system log file like this:

May 25 15:50:22 coprolith sniffer: Connection from 207.46.131.141 to 207.46.130.164:echo

Install it in the inetd.conf file with a line like this:

echo    stream  tcp nowait  nobody /usr/scripts/snfsqrd sniffer

The program is shown in Example 17-9.

Example 17-9. backsniff
  #!/usr/bin/perl -w   # backsniff - log attempts to connect to particular ports   use strict;   use Sys::Syslog qw(:DEFAULT setlogsock);   use Socket;   # identify my port and address   my $sockname       = getsockname(STDIN)                        or die "Couldn't identify myself: $!\n";   my ($port, $iaddr) = sockaddr_in($sockname);   my $my_address     = inet_ntoa($iaddr);   # get a name for the service   my $service = (getservbyport ($port, "tcp"))[0] || $port;   # now identify remote address   $sockname          = getpeername(STDIN)                            or die "Couldn't identify other end: $!\n";   ($port, $iaddr)    = sockaddr_in($sockname);   my $ex_address     = inet_ntoa($iaddr);   # and log the information   setlogsock("unix");   openlog("sniffer", "ndelay", "daemon");   syslog("notice", "Connection from %s to %s:%s\n", $ex_address,           $my_address, $service);   closelog( );


Perl Cookbook
Perl Cookbook, Second Edition
ISBN: 0596003137
EAN: 2147483647
Year: 2003
Pages: 501

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net