﻿############################################################################
# send alert if external single IP connect to a lots of IPs in a short time.
############################################################################
if (not (starts_with(source_ip, '172.29.') or starts_with(source_ip, '10.'))) then (
# Alert settings
  v.count_limit = 10; # limit of IP
  v.d_limit = 30; # 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 . " connect to more then " . v.count_limit . " IPs in " . v.d_limit . "sec.";
# End of Alert settings

  v.countfn = "/dev/shm/" . src . ".hit";
  v.hittimefn = "/dev/shm/" . src . ".time";
  v.dstlistfn = "/dev/shm/" . src . ".dstlist";

  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;
  );

  if (file_exists(v.dstlistfn)) then (
    v.dstlist = read_file(v.dstlistfn);
  ); else (
    write_file(v.dstlistfn, " ");
    v.dstlist = " ";
  );

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

  if ((v.pass < v.d_limit) and (v.count < v.count_limit)) then (
    if (!contains(v.dstlist, dst)) then (
      v.count++;
      v.dstlist = "<" . dst . ":" . dpt . ">, " . v.dstlist ;
      write_file(v.countfn, v.count);
      write_file(v.dstlistfn, v.dstlist);
    );
  );
  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: " . v.dstlist . "\r\n"
       , v.smtp
    );
    v.insec = v.now;
    v.count = 1;
    write_file(v.countfn, v.count);
    write_file(v.dstlistfn, "<" . dst . ":" . dpt . ">, ");
    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);
    delete_file(v.dstlistfn);
  );
);