-- malware-cymru-alert.lua
--
--  Malware lookup MD5/SHA-1 and generate badfellas alert 
--
-- http://www.team-cymru.org/MHR.html
local JSON=require'JSON'
TrisulPlugin = {

  id = {
    name = "file extraction malware alert  ",
    description = "various aspects of file extraction and generate malware alert ",
    author = "Unleash",
    version_major = 1,
    version_minor = 0,
  },
  onload = function()
  end,


  --
  filex_monitor  = {


    onfile_http  = function ( engine, timestamp, flowkey, path, req_header,resp_header,length )

      -- calculate sha1 for incoming file 
      -- outputstr = hashforfile filepath
      local h = io.popen("sha1sum "..path);
      local outputstr  = h:read("*a");
      h:close();
       
      -- You can get this indata in onresult req variable
      local indata={};

      -- Get the http request path(URL) for the file
      local host = req_header:get_value("Host");
      local url  = req_header:get_path();

      if host and url then
       url = host..url
      elseif host then
       url = host
      else
       url = ""
      end
      -- store all your required field.
      indata["host"]=host;
      indata["url"]=url;
      indata["hash"]=outputstr:match("(%x+)");
      indata["flowid"]=flowkey:id();

      T.async:schedule( 
      {
        data = JSON:encode(indata), 

        onexecute = function( indata) 
          local JSON=require'JSON'
          local indata = JSON:decode(indata);

          -- get the hash value from indata
          local hashval  = indata["hash"]
          --malware hash registry command
          local cymru_command = "whois -h hash.cymru.com ".. hashval;
          local h = io.popen(cymru_command)
          local outputstr  = h:read("*a")

          -- hash,last known GMT Time,detction percentage
          local h,last_seen,count = outputstr:match("(%x+)%s+(%d+)%s+(%d+)")

          if h then 
            local outdata = {};
            outdata["hash"]=h;
            outdata["detection_rate"]=count;
            outdata["last_seen"]=last_seen;
            return JSON:encode(outdata)
          end


        end,

        onresult = function(engine, req, response)
          local JSON=require'JSON'
          local req  = JSON:decode(req)
          local resp = JSON:decode(response)
          engine:add_alert( 
            "{5E97C3A3-41DB-4E34-92C3-87C904FAB83E}", -- GUID for Badfellas 
            req["flowid"],                            -- flow 
            "Lua-Malware-CYMRU",                      -- a sigid (private range)
			      1,										                     -- priority 
            resp["hash"].."<br>CYMRU Detection Rate : "..resp["detection_rate"].."% <br>"..req["url"])  --message

          print("Generated alert CYMRU detected  "..response)
        end
      }
    )
    end,

  }

}

