﻿################################################################################
# send alert if a lots of connection of an IP drops by firewall in a short time.
################################################################################
if (result eq 'DENY') then (
# Alert settings
  v.count_limit = 120; # limit of IP
  v.d_limit = 60; # limit of duration
  v.smtp = "192.168.1.6";
  v.sender = "sender@foo.bar";
  v.receiver = "recvr01@foo.bar,recvr02@foo.bar";
  v.subject = "Alarm detected - " . src . " is blocked more then " . v.count_limit . " times in " . v.d_limit . "sec.";
# End of Alert settings

  v.countfn = "/dev/shm/" . src . "-blocked.hit";
  v.hittimefn = "/dev/shm/" . src . "-blocked.time";

  if (file_exists(v.countfn)) then (
    v.count = read_file(v.countfn);
  ); else (
    write_file(v.countfn, "1");
    v.count = 0;
  );

  v.now = date_time_to_epoc(date_time);

  if (file_exists(v.hittimefn)) then (
    v.insec = read_file(v.hittimefn);
  ); else (
    write_file(v.hittimefn, v.now);
    v.insec = v.now;
  );

  v.pass = v.now - v.insec;

  if ((v.pass < v.d_limit) and (v.count < v.count_limit)) then (
      v.count++;
      write_file(v.countfn, v.count);
  );
  else if ((v.pass <= v.d_limit) and (v.count >= v.count_limit)) then (
  send_email(v.sender,
       v.receiver,
       "Subject: " . v.subject . "\r\n" .
       "To: " . v.receiver . "\r\n" . "\r\n" .
       "Sawmill has detected an alarm:\r\n" .
       "       Time: " . date_time . "\r\n" .
       "     Device: " . logging_device . "\r\n" .
       "       Hits: " . v.count . "\r\n" .
       "   Duration: " . v.pass . " sec.\r\n" .
       "     Source: " . src . "\r\n"
       , v.smtp
    );
    v.insec = v.now;
    v.count = 1;
    write_file(v.countfn, v.count);
    write_file(v.hittimefn, v.insec);
  );
  else if ((v.pass > v.d_limit) and (v.count < v.count_limit)) then (
    delete_file(v.hittimefn);
    delete_file(v.countfn);
  );
);