#!/usr/bin/perl
use Switch;
use Net::Pcap;

my $dev = "eth0"; # interface nads?uchiwania
my $pcap;
my $err;
my $packet;

sub connread;

if ($ARGV[0] eq "-h") {
  print "Usage: ./fhelp.pl <filename>\n\r If no filename given will start live capture\n";
  exit;
}
# sprawdzamy czy zosta?a dana nazwa pliku, je?li tak otwieramy go,
# w przeciwnym razie otwieramy "live capture"
if ($ARGV[0] eq "") {
  if($pcap = Net::Pcap::open_live($dev, 2000, 1, 1000, \$err)) {
    Net::Pcap::loop($pcap, -1, \&connread, '');
  }
  else {
    print "Error\n$err\n";
    exit;
  }
}
else {
  if($pcap = Net::Pcap::open_offline($ARGV[0], \$err)) {
    Net::Pcap::loop($pcap, -1, \&connread, '');
  }
  else {
    print "Error\n$err\n";
    exit;
  }
}


sub connread {
my ($data, $header, $packet) = @_; $get = "n";
my $packet = unpack('H*', $packet); # pobieramy i rozpakowujemy pakiet
# szukamy po??cze? na porty 80 i 21
if ($packet =~ m/^\w{44}(..)(06)(\w{4}|\w{8})(..)(..)(..)(..)\w{8}(....)(0050|0015)(.*)/) {
$curr_ip = sprintf("%d.%d.%d.%d", hex($4), hex($5), hex($6), hex($7)); 
$traffic = sprintf("%s",$10);

# wyszukujemy niepe?ne pakiety http
if ($traffic =~ /(474554|48454144)/) {
if (!($traffic =~ m/^(.*)\w(20485454502f312e(31|30)0d0a)(.*)(557365722d4167656e743a)(.*)/)) {
print "incomplete http header from $curr_ip\n";
print "do you want to block ip $curr_ip on iptables? [y/N]: ";
$get = <>;
if (($get eq "y")|($get eq "Y")) {
system("iptables -A INPUT -p tcp -s $curr_ip -j DROP");
}
}}
# wyszukujemy polecenia port w pakietach ftp
if ($traffic =~ /(706f7274|504f5254)/) {
print "PORT command used in ftp connection from $curr_ip\n";
print "do you want to block ip $curr_ip on iptables? [y/N]: ";
$get = <STDIN>;
if (($get eq "y")|($get eq "Y")) {
system("iptables -A INPUT -p tcp -s $curr_ip -j DROP");
#print("xxxxxxxxxxxx\n");
}}
}}
