Effective dovecot+sieve extension filtering

After some recent conversations with a colleague about creating a simple shield that would stop some of the dangerous crypto/ransomeware I set about creating such a filter.

The premise was simple, move all mail containing predefined attachments under a certain size to a different folder. Sounds like a fine job for the sieve filter to me.

A quick search on the internet resulted in some basic ways to achieve this sort of behavior, however most were plain wrong in the execution of the regex statements. Which as it turns out should not even be used, the pigeonhole addon does all the required mime handling for us.

Problems with most solutions:

  • Regex statement per extension which creates an unreadable mess (and plain kills the server performance on larger emails)
  • Not limiting the search areas, this results in a lot of false positives (e.g. any of the extensions appearing AFTER the filename has been specified (within the encoded attachment) would trigger the rule)
  • Failing to correctly identify and target the different filename formats (filename=”test.zip”, filename=test.zip[\r\n] or filename=test.zip; and in extreme cases just a file= with no filename=)

The result code:

require ["body","fileinto","regex","mime","foreverypart"];
 File potentially dangerous extensions into a seperate folder
foreverypart
{
  if allof (size :under 200K, header :mime :param "name" :matches ["Content-Type", "Content-Disposition"] [ "*.exe", "*.pif", "*.scr", "*.zip", "*.7z", "*.rar", "*.bat", "*.reg", "*.wmf", "*.emf", "*.wmz", "*.emz", "*.com", "*.hta", "*.cmd", "*.vb", "*.vbs", "*.ws", "*.wsf", "*.wsc", "*.wsh", "*.ps1", "*.ps1xml", "*.ps2", "*.ps2xml", "*.psc1", "*.psc2", "*.msh", "*.msh1", "*.msh2", "*.mshxml", "*.msh1xml", "*.msh2xml", "*.scf", "*.lnk", "*.inf", "*.vbe", "*.js", "*.jse", "*.ocx", "*.docm", "*.dotm", "*.docx", "*.xlsm", "*.xltm", "*.xlam", "*.pptm", "*.", "*.potm", "*.ppam", "*.ppsm", "*.sldm" ])
  {
    fileinto "Dangerous";
    stop;
  }
}

Now this doesn’t solve all problems presented with the current ransomeware (or other scams/virusses), but it does prevent a lot of the current exploits which were comming in in bulk.

Don’t forget to specify the folder in doveoct as a required folder:

namespace {
  type = private
  separator = /
  inbox = yes

  mailbox Trash {
    auto = subscribe
    special_use = \Trash
  }
  mailbox Drafts {
    auto = subscribe
    special_use = \Drafts
  }
  mailbox Sent {
    auto = subscribe
    special_use = \Sent
  }
  mailbox Spam {
    auto = subscribe
    special_use = \Junk
  }
  mailbox Virus {
    auto = subscribe
  }
  mailbox Dangerous {
    auto = subscribe
  }
}