#!/usr/bin/perl
#
#  networkReporter.pl - Warden client for communication with RT ticketing system
# 
#  Copyright (C) 2012 Masaryk University
#  Author(s): Jakub CEGAN <cegan@ics.muni.cz>
#
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions are met:
#
#   * Redistributions of source code must retain the above copyright notice,
#     this list of conditions and the following disclaimer.
#   * Redistributions in binary form must reproduce the above copyright notice,
#     this list of conditions and the following disclaimer in the documentation
#     and/or other materials provided with the distribution.
#   * Neither the name of Masaryk University nor the names of its contributors may be
#     used to endorse or promote products derived from this software without
#     specific prior written permission.
#
#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
#  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
#  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
#  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
#  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
#  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
#  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
#  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
#  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
#  POSSIBILITY OF SUCH DAMAGE.
#

use warnings;
use strict;

use lib '/opt/warden-client';
use Email::Simple;
use Sys::Hostname;
use Text::Wrap;
use DateTime;


sub sendmailWrapper{
  my $message = shift;

  if(open(my $sendmail, '|/usr/sbin/sendmail -oi -t')){
    print $sendmail $message;
    close $sendmail;
    return 1;
  } else {
    return (0, "Sending email failed: $!");
  }
}

sub timeToLocal{
  my $time = shift;

  my ($y,$m,$d,$h,$mm,$s);
  if(!($$time =~ m/(\d{4})\-(\d{2})\-(\d{2})\ (\d{2})\:(\d{2})\:(\d{2})/)){
    return (0, "Bad time format!\n");
  }

  ($y,$m,$d,$h,$mm,$s) = $$time =~ m/(\d{4})\-(\d{2})\-(\d{2})\ (\d{2})\:(\d{2})\:(\d{2})/;
  eval{
  my $dt = DateTime->new(
        year   => $y,
        month  => $m,
        day    => $d,
        hour   => $h,
        minute => $mm,
        second => $s,
        time_zone =>'gmt');
  $dt->set_time_zone('local');
  $$time = $dt->strftime('%d. %m. %Y v %H:%M');};
  if($@){
    return (0, "Can't convert time to epoch format!\n");
  }
  return 1;
}

#-------------------------------------------------------------------------------
# reportToRT - fuction for creating tickets in the RT system
#
#  param: hash with gateway address and warden event array
#
# return: ok || fail
#-------------------------------------------------------------------------------
sub reportToRT{

  my $inputData  = shift;
  my $toGateway  = $$inputData{'gateway'};
  my @event      = @{$$inputData{'data'}};

  my $fromHostname;
  my $message;
  my ($rc, $err);

  if(!($toGateway)){
    return (0, "Empty 'To' email header!\n");
  }

  eval{
    $fromHostname = hostname();
    if(!($fromHostname =~ m/\.ics\.muni\.cz/gi)){
      $fromHostname .= '.ics.muni.cz';
    }
  };
  if($@){
    return (0, "Can't retrive hostname for 'From' header!\n");
  }

  ($rc, $err) = timeToLocal(\$event[3]);
  if(!$rc){
    return (0, $err);
  }

  my $text = "Dobrý den,
  z Vaší IP adresy $event[6] jsme zaznamenali $event[3] celkem $event[9] pokus(y) o připojení k neexistující službě (tzv. honeypotu). V tomto konkrétním případě se jednalo o protokol $event[7] a port číslo $event[8]. Je pravděpodobné, že se jedná o virus, napadený počítač či zneužitý uživatelský účet. Doporučujeme Vám zkontrolovat zabezpečení tohoto počitače.

  S pozdravem

  CSIRT-MU
  http://www.muni.cz/csirt";

  eval{
  $message = Email::Simple->create(
    header => [
      To                    => $toGateway,
      From                  => 'tools@'.$fromHostname,
      Subject               => 'Pristup na honeypot v siti CESNET'],
      body => fill('','',$text));
  };
  if($@){
    return (0, "Can't create email message\n");
  }

  ($rc, $err) = sendmailWrapper($message->as_string);
  if(!$rc){
    return (0, $err);
  }
  return 1;
}


my $warden_path = '/opt/warden-client';

require $warden_path . '/lib/WardenClientReceive.pm';

my $requested_type = "portscan";
my $ip_reg = '147\.251\.\d+\.\d+';
my $client = 'CESNET_IDS';
my $gateway = 'rt@rt-devel.ics.muni.cz';

$Text::Wrap::columns = 90;


my $logger;
my @new_events;

@new_events = WardenClientReceive::getNewEvents($warden_path, $requested_type);
#@new_events = (["5179620","au1.cesnet.cz","CESNET_IDS","2012-11-08 17:04:56","portscan","IP","147.251.216.8","XXX","666","2","","0","720"]);
foreach (@new_events) {
  my @event = @$_;

  if(($event[6] =~ /^$ip_reg$/i) and ($event[2] =~ /^$client$/i)){
    my %input = (gateway => $gateway, data => \@event);
    my ($rc,$err) = reportToRT(\%input);
    if(!$rc){
      #print "ERR: $err\n";
      syslog("err|Warden client - networkReporter $err\n");
    }
  }
}

exit 0;