﻿################################################################
# send alert if a lots of IPs connect to an IP in a short time.
################################################################
# Alert settings
  v.count_limit = 1000; # 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 - " . v.count_limit . " IPs connect to " . dst . ":" . dpt .  " in " . v.d_limit . "sec.";
# End of Alert settings

  v.countfn = "/dev/shm/" . dst . "-" . dpt . ".phit";
  v.hittimefn = "/dev/shm/" . dst . "-" . dpt . ".ptime";
  v.srclistfn = "/dev/shm/" . dst . "-" . dpt . ".srclist";

  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.srclistfn)) then (
    v.srclist = read_file(v.srclistfn);
  ); else (
    write_file(v.srclistfn, " ");
    v.srclist = " ";
  );

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

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