﻿################################################################
# send alert if huge the same port connection in a short time.
################################################################
# Alert settings
if (dpt eq '514') then (
  v.count_limit = 50; # limit of connection
  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 - Huge port " . dpt . " connection.";
# End of Alert settings

  v.hit_count_fn = "/dev/shm/" . src . ".hit_count";
  v.hit_time_fn = "/dev/shm/" . src . ".hit_time";

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

  v.now = date_time_to_epoc(date_time);

  if (file_exists(v.hit_time_fn)) then (
    v.insec = read_file(v.hit_time_fn);
  ); else (
    write_file(v.hit_time_fn, 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.hit_count_fn, 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" .
       "Destination: " . dst . "\r\n"
       , v.smtp
    );
    write_file(v.hit_count_fn, 1);
    write_file(v.hit_time_fn, v.now);
  );
  else if ((v.pass > v.d_limit) and (v.count < v.count_limit)) then (
    delete_file(v.hit_count_fn);
    delete_file(v.hit_time_fn);
  );
);
