Home » Blogs » diem's blog
 

mac geekery

Get your geek on.

Primary links

  • about
  • recent items
  • user blogs
  • forums
  • contact
  • advertising

Configuring Mail to Scan Incoming Email for Malware

  • Automation
  • Moderately Involved
June 1, 2007 - 7:55am

We may not like it, but OS X malware is on the rise. Even if you prefer the lalala-I'm-not-listening approach to security, you may want to do the decent thing and not forward such nasties from your Windows-using colleagues. Here's how to set things up.

 

  1. Install clamav (the pre-eminent open source virus scanner).

    The easiest way to do this is download and install ClamXav. This includes a nice OS X front end for clamav and an on-access folder-watching utility.

  2.  

  3. Configure clamd.

    This step is optional but strongly recommended. clamd will eat ~40MB of your RAM whilst quiescent, but provides support for asynchronous scanning and hence improves system responsiveness immeasurably. I found Mail somewhat unresponsive whilst receiving mail without it. YMMV.

    • Edit clamd.conf

      - comment out any line that begins "Example" - this will enable clamd.

      - modify DatabaseDirectory to point to where your clamav virus database resides. On a standard ClamXav install this is /usr/local/clamXav/share/clamav .

      - I've tweaked some of the other settings, notably the location and quality of logging, but the above is the minimum needed to get things working.

    • Make clamd launch at boot time

      On Tiger, you'd use launchd for this, but since I use Panther I've had to compose a StartupItem:

      - drop into a Terminal, and create a clamd StartupItem folder: mkdir /Library/StartupItems/clamd and cd into it.

      - paste the following into a pico session and save as 'clamd':

      #!/bin/sh
      ##
      # clamd
      ##
      
      . /etc/rc.common
      
      StartService ()
      
      {
          ConsoleMessage "Starting clamd"
          /usr/local/clamXav/sbin/clamd -c /usr/local/clamXav/etc/clamd.conf
      }
      
      StopService ()
      
      {
         ConsoleMessage "Stopping clamd"
         /usr/local/clamXav/sbin/clamd SHUTDOWN
      }
      
      RestartService ()
      {
          StopService
          StartService
      }
      
      RunService "$1"

      - make this script executable:
      chmod a+x clamd

      - paste the following into a pico session and save as 'StartupParameters.plist':

      <?xml version="1.0" encoding="UTF-8"?>
      <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
      <plist version="1.0">
      <dict>
         <key>Description</key>
         <string>daemon to support clamdscan</string>
         <key>Messages</key>
         <dict>
            <key>start</key>
            <string>Starting clamd</string>
            <key>stop</key>
            <string>Stopping clamd</string>
         </dict>
         <key>OrderPreference</key>
         <string>None</string>
         <key>Provides</key>
         <array>
            <string>clamd</string>
         </array>
         <key>Requires</key>
         <array>
            <string>Disks</string>
         </array>
      </dict>
      </plist>

    • Finished clamd config - on your next reboot you should see 'Starting clamd' amongst all the other messages that display before the login window comes up.

  4.  

  5. Script to check email content.

    Paste the following into Script Editor, 'compile' to check it for errors, and save it wherever you keep your handy dandy Applescripts. Note that if you decided not to use clamd (step 2), you must substitute clamscan for clamdscan on the 'do shell script' line:

    using terms from application "Mail"
    --testing() -- uncomment to test-run from script editor
    on testing()
    set theList to the selection of application "Mail"
    do_viruscheck(theList)
    end testing
    on perform mail action with messages ruleMessages for rule theRule
    do_viruscheck(ruleMessages)
    end perform mail action with messages
    on do_viruscheck(theMessages)
    tell application "Mail"
    repeat with thisMessage in theMessages
      set msgSource to source of thisMessage
      tell application "System Events"
        -- get a free name for a temporary file
        set tmpdir to (path to "temp" from user domain as text)
        set tmpnam to "tmp-clamAVscan"
        set tmpfil to tmpdir & tmpnam as text
        -- should usually be ok, but now add counter if file still exists
        set tmp to tmpfil
        set c to 0
        set ok to false
        repeat while (exists file tmpfil)
          set c to c + 1
          set tmpfil to (tmp & c) as text
        end repeat
        -- copy message to temporary file
        set f to (open for access file tmpfil with write permission)
        set eof of f to 0 -- overwrite file
        write msgSource to f as string
        close access f
      end tell
    
      try
        do shell script "/usr/local/clamXav/bin/clamdscan --quiet --stdout " & POSIX path of file tmpfil
        on error errMsg number exitCode
        if (exitCode = 1) then
          set currentSubject to subject of thisMessage
          set subject of thisMessage to "[**VIRUS** - ClamAV] " & currentSubject
          -- set junk mail status of thisMessage to true
          -- set accountName to name of account of mailbox of thisMessage
          -- set mailbox of thisMessage to mailbox "Junk" of account accountName
        else
          -- ?? should we add something to the subject to say clamscan had trouble?
          display dialog "Something unexpected has happened to clamAV scan: Exit Code = " & exitCode
          -- make sure display dialog doesnt get too much..
          display dialog "Error Message (head):" & words 1 thru 20 of errMsg
          -- if user cancels script here, the temporary file will not be removed
        end if
      end try
    
      -- clean up temporary file
      tell application "System Events" to delete file tmpfil
    end repeat
    end tell
    end do_viruscheck
    end using terms from

  6.  

  7. Add a rule to Mail to run the scan script.
    • In Mail, go Preferences.. Rules.. and add a new rule that, for all mail, runs an Applescript. Navigate to your script using the Choose.. button.
    • Drag your new rule to the top of the list of rules (so that it is the first rule processed) and close Preferences.
  8.  

  9. Test it.

    - Send yourself an email with the eicar test file attached to it - if that mail has "[**VIRUS** - ClamAV]" prepended to its subject line then the script is working as designed.

 

There you go then - you can now feel all warm and fuzzy that you too are contributing to keeping the world's malware at bay.

Average: 4 (2 votes)

About diem

View full user profile
  • diem's blog
  • flag this
  • Printer-friendly version
June 1, 2007 - 9:54am
Adam Knight said
Adam Knight's picture

I prefer the “lalala” approach because I’ve not seen or heard of “Mac OS X malware” other than from the vendor of software that proclaims to remove it.

However, doing virus checks for the sake of getting it out of my inbox when a compatriot’s Windows machine gets one is worth the effort.

  • flag this
June 1, 2007 - 11:58am
diem said

To be fair I've not yet heard of any malware (I use that term because "virus" just doesn't cover the bases these days!) explicitly targetting OS X. There are however signs of activity, such as this recent proof-of-concept:

http://www.virusbtn.com/Session-5625ab4d6a78b4fb808c58e238215bb0/news/virus_news/2007/05_23.xml

that targets OpenOffice's StarBasic macro language and has payloads that'll execute on Windows, Linux and OS X :-\

  • flag this
June 1, 2007 - 11:46am
Ken said

Somebody needs a dictionary.

I used to work for a company that sent out a directive that we should always say “prepend” to mean “prefix.” Then someone looked it up in a dictionary and they sent out another memo saying, essentially, “never mind.”

Prepend means to ponder or consider.

  • flag this
June 1, 2007 - 12:59pm
diem said

Erm, no it doesn't. It means the opposite of append.

http://dictionary.reference.com/cite.html?qh=prepend&ia=foldoc

I hope that during your grammar check you managed to notice that the above is tip on how to customise OS X rather than an exercise in English Puzzled

  • flag this
June 1, 2007 - 1:32pm
Nick said

“... you may want … not [to] forward such nasties [to] your Windows-using colleagues.”

Oh, I don’t know. You don’t know my colleagues Smiling

But surely a competent IT department would ensure scanning was done at the mail gateway, anyway — and would ensure my colleagues had AV on the individual machines if they were using Windows.

“The easiest way to do this is download and install ClamXav”

Yes, but if these colleagues of mine who haven’t been provided with AV (why?) are in such danger from my propensity to forward attachments I know nothing about to them, hadn’t I better ask for something a bit heavier-duty than ClamXav, and never mind what’s easy for me? I saw a comparative test of Mac AV programs on infected Office documents some while back. One of the universities had done it. Anyway, ClamXav was staggeringly ineffective at finding and disinfecting them when compared to some of the other solutions. I don’t know what the latest versions are like, but that’s not encouraging.

But in any event, it seems to me that there’s something contradictory in insisting it’s necessary to use AV, and then recommending a solution on the basis that it’s the “easiest way”. So far as Macs go, I’m a home user myself. But if it’s necessary for someone to pass on questionable attachments (including Office documents) from Windows users and, therefore, necessary to scan/clean them, surely he should be looking for the best, not the easiest, solution.

  • flag this
June 1, 2007 - 1:57pm
jay said

Erm, yes use commercial virus software and watch your Mac experience circle the drain. I used three versions of Virex and the last one in it’s default form made a 45 minute Carbon Copy Clone operation take more than 8 hours. I’ve not heard anything encouraging about Virex’s competitor either. McAfee’s slogan for Virex should be “Virex: DoS in a Box!”

I’ve been using ClamXav for at least 18 months. It’s not perfect but it doesn’t get in my way either. And it has flagged viruses sent from Windows boxes that passed our corporate scanner.

  • flag this
June 5, 2007 - 3:37am
diem said

Ah, I see where you’re coming from. Please replace the word ‘colleagues’ with ‘friends’ in reading my text and all should be clearer. I’m targetting home setups, not corporates.

As to my proposing ‘the easiest way’, please note that what I said was that ClamXav was the easiest way to install clamav, not that I was offering the easiest way to get email antivirus scanning working on a Mac. Indeed, my complete solution involves a certain amount of work at the CLI – hardly an easy way to get email virus scanning working for the average Mac user! I start from the (possibly invalid) assumption that Mac users are in general not inclined towards the concept of anti-virus, hence offering a free and step-by-step way to get a fair level of security might be more attractive than a paid solution.

Further, though I have no hard data on the accuracy of paid VS free antivirus products, Jay’s comment mirrors my experience on Windows; the paid products are so invasive and ‘heavy’ that I find them unacceptable. My preferred solution is to go with open source – there the developers are motivated by factors other than market share and the associated bloat. To quote the usual abridging of Doug McIlroy’s Unix philosophy “Do one thing and do it well”.

  • flag this
June 5, 2007 - 4:08am
Anonymous said

dunno but someone’s listening on port *.9878 (if netstat is right)

  • flag this
June 18, 2007 - 3:05pm
Anonymous said

Another way to do this is through an AppleScript available here:
http://scriptbuilders.net/files/clamavscan1.0.html

I came across mention of it at the ClamXAV.com website:
http://www.clamxav.com/index.php?page=prefs

  • flag this
June 18, 2007 - 3:50pm
diem said

Yes, that script forms the basis of the one I posted here. Whilst I cannot claim ‘my’ script (it was developed in concert with other posters at the clamxav forum) is flawless, it works around a serious security flaw in the scriptbuilders one. To whit, in that script the complete content of the mail message is passed ‘raw’ to the command line, and hence could be exploited by placing parseable shell commands in the text of the message. rm -r -f / anyone?

  • flag this
February 3, 2008 - 12:35am
Anonymous said

i’m still having a problem with this approach.

the subject field isn’t changed with infected incoming mail. the daemon detects it etc and the script says it’s changed the subject field but it doesn’t appear in Mail.

however, uncommenting and using the debugging code (run from inside script editor) based on a manual selection of messages in Mail does actually change the subject field of infected messages in the selection.

any idea why? i’d love to get this working on incoming messages.

i was initially going to use the “parent” clamavscan1.0 script mentioned earlier but refrained because of the security hole. well done for fixing that in this improved script. also for the very clear setup instructions.

  • flag this
Syndicate content

Search

Navigation

  • Popular content
  • Recent votes
  • Top rated

User login

What is OpenID?
  • Log in using OpenID
  • Cancel OpenID login
  • Create new account
  • Request new password

Today's popular content

  • View hidden files and folders in Finder. (62)
  • Basic Mac OS X Security (61)
  • Handling Filenames with Spaces in Bash (40)
  • Nondestructively Resizing Volumes (39)
  • Optimizing AirPort Connectivity (25)
more

Active forum topics

  • How to burn avchd to dvd for dvd player
  • How to burn Mpeg video to DVD for dvd player
  • How to burn WMV video to DVD for dvd player
  • Import Panasonic TM700 1080 60p Videos to Kdenlive on Mac
  • How to burn QuickTime/MOV to DVD for home player
more



blog advertising is good for you


blog advertising is good for you

Locations of visitors to this page

© 2005-2010 Adam Knight, unless otherwise indicated.