лечим почтовые вложения winmail.dat

Проблема древняя и как водится связана с попыткой Microsoft навязывать свои стандарты. Откуда берется почтовое вложение winmail.dat вы можете почитать тут: https://support.mozilla.org/ru/kb/chto-oznachaet-vlozhenie-winmaildat

сегодня мы решим эту проблему глобально, прокачаем наш postfix сервер

  1. Установим MIMEDefang.

для CentOS

yum install mimedefang

для Ubuntu

apt-get install mimedefang
  1. Настроим MIMEDefang на определенный порт TCP, наша служба будет слушать этот порт. Для этого исправим конфигурацию

для CentOS: /etc/sysconfig/mimedefang
для Ubuntu: /etc/default/mimedefang

дописываем в конце

SOCKET=inet:10185
  1. Отредактируем файл /etc/mail/mimedefang-filter, можете просто вставить текст ниже
# -*- Perl -*-
#***********************************************************************
#
# mimedefang-filter
#
# Suggested minimum-protection filter for Microsoft Windows clients, plus
# SpamAssassin checks if SpamAssassin is installed.
#
# Copyright (C) 2002 Roaring Penguin Software Inc.
#
# This program may be distributed under the terms of the GNU General
# Public License, Version 2, or (at your option) any later version.
#
# $Id$
#***********************************************************************

#***********************************************************************
# Set administrator's e-mail address here.  The administrator receives
# quarantine messages and is listed as the contact for site-wide
# MIMEDefang policy.  A good example would be 'defang-admin@mydomain.com'
#***********************************************************************
$AdminAddress = 'postmaster@localhost';
$AdminName = "MIMEDefang Administrator's Full Name";

#***********************************************************************
# Set the e-mail address from which MIMEDefang quarantine warnings and
# user notifications appear to come.  A good example would be
# 'mimedefang@mydomain.com'.  Make sure to have an alias for this
# address if you want replies to it to work.
#***********************************************************************
$DaemonAddress = 'mimedefang@localhost';

#***********************************************************************
# If you set $AddWarningsInline to 1, then MIMEDefang tries *very* hard
# to add warnings directly in the message body (text or html) rather
# than adding a separate "WARNING.TXT" MIME part.  If the message
# has no text or html part, then a separate MIME part is still used.
#***********************************************************************
$AddWarningsInline = 0;

#***********************************************************************
# To enable syslogging of virus and spam activity, add the following
# to the filter:
# md_graphdefang_log_enable();
# You may optionally provide a syslogging facility by passing an
# argument such as:  md_graphdefang_log_enable('local4');  If you do this, be
# sure to setup the new syslog facility (probably in /etc/syslog.conf).
# An optional second argument causes a line of output to be produced
# for each recipient (if it is 1), or only a single summary line
# for all recipients (if it is 0.)  The default is 1.
# Comment this line out to disable logging.
#***********************************************************************
md_graphdefang_log_enable('mail', 1);

#***********************************************************************
# Uncomment this to block messages with more than 50 parts.  This will
# *NOT* work unless you're using Roaring Penguin's patched version
# of MIME tools, version MIME-tools-5.411a-RP-Patched-02 or later.
#
# WARNING: DO NOT SET THIS VARIABLE unless you're using at least
# MIME-tools-5.411a-RP-Patched-02; otherwise, your filter will fail.
#***********************************************************************
# $MaxMIMEParts = 50;

#***********************************************************************
# Set various stupid things your mail client does below.
#***********************************************************************

# Set the next one if your mail client cannot handle multiple "inline"
# parts.
$Stupidity{"NoMultipleInlines"} = 0;

# Detect and load Perl modules
detect_and_load_perl_modules();


sub filter {
    my($entity, $fname, $ext, $type) = @_;
 
    ### Convert TNEF winmail.dat format
    ### Note: You must install Convert::TNEF and File::Type from CPAN before using this script
    if (lc($type) eq "application/ms-tnef" or lc($fname) eq "winmail.dat" ) {
        use Convert::TNEF;
        use File::Type;
        use File::Temp qw(tempfile tempdir);
 
        # Create a unique temporary directory under "/tmp"
        my $tnefdir = tempdir(CLEANUP => 1, DIR => "/tmp");
        if (not $tnefdir) {
                md_graphdefang_log('tnef_fail',"Unable to create temporary directory");
                return action_accept();
        }
 
        # If we can't Convert the TNEF file for some reason, just accept the attachment and log the error
        my $tnef = Convert::TNEF->read_ent($entity,{output_dir=>"$tnefdir"});
        if (not $tnef) {
                md_graphdefang_log('tnef_fail',$Convert::TNEF::errstr);
                return action_accept();
        }
 
        my $ft = File::Type->new();
 
        # Append attachments contained in the winmail.dat file to the message.
        for ($tnef->attachments) {
             # Determine the mime-type of the file
             my $mimetype = $ft->mime_type($_->data);
 
                # File::Type doesn't detect text files well, this is a workaround
             if ($mimetype eq "application/octet-stream") {
                  #Set the mime-type to text/plain if the first 1024 characters are printable
                  $text_check = substr($_->data,0,1024);
                  $mimetype = "text/plain" unless $text_check =~ /[^[:print:]s]/;
             }
 
             my $tnef_entity = action_add_part($entity, "$mimetype", "base64", $_->data, $_->longname, "attachment");
             md_graphdefang_log('tnef_ext', "File: " . $_->longname . " Type: $mimetype");
 
             # Run each new TNEF-sourced MIME part back through the filter again, this ensures that bad filenames etc.
             # cannot sneak through by being contained in winmail.dat files
 
             filter ($tnef_entity, $_->longname, "", "$mimetype");
        }
 
        # Deletes working files
        $tnef->purge;

 
        # Remark this if you want still want to keep the original winmail.dat file
        return action_drop();
    }
 
    # Keep the attachment
    return action_accept();
}

# DO NOT delete the next line, or Perl will complain.
1;
  1. Установим модели Perl Convert::TNEF и File::Type

для CentOS

yum install perl-Convert-TNEF.noarch

второй пакет надо скачать и установить

wget https://ftp.tu-chemnitz.de/pub/linux/dag/redhat/el6/en/x86_64/rpmforge/RPMS/perl-File-Type-0.22-1.el6.rf.noarch.rpm
yum install perl-File-Type-0.22-1.el6.rf.noarch.rpm

для Ubuntu

apt-get install libconvert-tnef-perl
apt-get install libfile-type-perl
  1. Проверим синтаксис Perl
# perl -c /etc/mail/mimedefang-filter
  1. Настроим автозапуск службы MIMEDefang и запустим ее
systemctl enable mimedefang.service
service mimedefang restart
  1. Проверим, слушает ли сервис указанный выше порт
# netstat -tlpn | grep 10185
tcp        0      0 0.0.0.0:10185           0.0.0.0:*               LISTEN      7401/mimedefang
  1. Теперь добавим проверку в Postfix, для этого откроем конфиг /etc/postfic/main.cf

и допишем в конце

smtpd_milters = inet:localhost:10185
milter_default_action = accept

готово! Любое письмо, которое будет иметь во вложении winmail.dat, будет обработано нашей службой и вложение будет расшифровано!

Поделиться
Отправить
 845   2020   MIMEDefang   Perl   Postfix   winmail.dat