[Mimedefang] testing file magic?

James Ralston qralston+ml.mimedefang at andrew.cmu.edu
Wed Jul 23 04:44:01 EDT 2003


On 2003-07-22 at 22:00:55-0400 "David F. Skoll" <dfs at roaringpenguin.com> wrote:

> On Tue, 22 Jul 2003, James Ralston wrote:
> 
> > Has anyone tried using File::MMagic (or similar) to identify
> > hazardous attachments?
> 
> One of my clients did that, a long while ago.
> 
> See the mimedefang.pl source code and MIME::Entity man pages.  The
> filename is in $entity->bodyhandle->path, though you should check
> that $entity->bodyhandle is defined before doing anything with it.

Understood; thanks.

> I don't think it's even necessary to use a fancy Perl module for
> this.  If you read the body, and the first two characters are "MZ",
> treat it as a DOS executable and trash it. :-)

Actually, as I discovered, the File::MMagic module is useless, because
it returns 'application/octet-stream' for far too many things (no
matter what magic source you point it at).

That leaves two choices:

    1.  Call out to /usr/bin/file directly, and read the results.
        This is easy to hack, but hard to Do Correctly (handle fds,
        returns values, etc.).

    2.  Examine the bytes of the file ourselves (as you suggested).

I implemented #2.  Here's a snippet from my filter() function:

    # Check for disguised MS-DOS executables.
    if (defined $entity->bodyhandle) {
      my $path = $entity->bodyhandle->path;
      if ($path) {
        if (open FILE, "<$path") {
          my $file_data;
          my $read_chars;
          $read_chars = read FILE, $file_data, 1024;
          close FILE;
          if ($read_chars > 2) {
            if ((substr ($file_data, 0, 2)) eq 'MZ') {
              # quarantine and/or reject here
            }
          }
        }
      }
    }

At least so far, it seems to work.  Suggestions from others are
welcome...




More information about the MIMEDefang mailing list