Это старая версия документа.


Фильтрация почты

Одной из больших проблем с электронной почтой является проблема массовой незатребованной почты (Unsolicited Bulk Email - UBE). Такие сообщения, более известные как СПАМ, могут к тому же содержать вирусы и другие виды вредоносных программ. В соответствии с некоторыми отчетами эти сообщения составляют подавляющую часть от всего трафика почтовых сообщений в интернете.

В этом разделе рассматривается интеграция Amavisd-new, Spamassassin и ClamAV с транспортным почтовым агентом (MTA) Postfix. Postfix может также проверять легальность почты с помощью передачи ее внешним фильтрам содержания. Эти фильтры могут иногда определить что сообщение является спамом без необходимости передачи его более ресурсоемким приложениям. Пара таких фильтров - это opendkim и python-policyd-spf.

  1. Amavisd-new - это программная оболочка, которая может вызывать любое количество фильтрующих программ по обнаружению спама, антивирусов и т.п.

  2. Spamassassin использует множество механизмов фильтрования почты на основе содержимого сообщений.

  3. ClamAV - антивирусное приложение с открытым кодом.

  4. opendkim является почтовым фильтром Sendmail для стандарта DKIM (почты, заверенной доменными ключами).

  5. python-policyd-spf обеспечивает проверку SPF (структуры политики отправителя) с Postfix.

А здесь то, как эти части работают вместе:

  1. Почтовое сообщение принимается Postfix.

  2. Это сообщение проходит через некоторые внешние фильтры, в том числе opendkim и python-policyd-spf.

  3. Затем сообщение обрабатывается Amavisd-new.

  4. ClamAV используется для проверки сообщения. Если сообщение содержит вирус, Postfix сбросит сообщение.

  5. Чистые сообщения затем будут проверены Spamassassin на принадлежность к спаму. Spamassassin затем добавит строки X-Header, позволяющие в дальнейшем Amavisd-new управлять сообщением.

Например, если сообщение содержит уровень спама более пятидесяти, оно будет автоматически выброшено из очереди чтобы не беспокоить получателя. В качестве альтернативы помеченное сообщение доставляется до почтового агента пользователя (MUA) чтобы пользователь сам определил насколько оно легальное.

Установка

Смотрите раздел Postfix для установки и настройки Postfix.

Чтобы установить основные приложения введите следующее в терминале:

sudo apt-get install amavisd-new spamassassin clamav-daemon
sudo apt-get install opendkim postfix-policyd-spf-python

Существуют некоторые общие пакеты, подключаемые к Spamassassin для лучшего определения спама:

sudo apt-get install pyzor razor

Поскольку основным фильтрующим приложениям требуются утилиты архивации для обработки прикрепленных файлов:

sudo apt-get install arj cabextract cpio lha nomarch pax rar unrar unzip zip
Если какие-то пакеты не были найдены, проверьте что хранилище multiverse разрешено в /etc/apt/sources.list.

Если вы внесли изменения в этот файл, убедитесь, что выполнили

sudo apt-get update

перед повторной попыткой установки.

Настройка

Now configure everything to work together and filter email.

ClamAV

The default behaviour of ClamAV will fit our needs. For more ClamAV configuration options, check the configuration files in /etc/clamav.

Add the clamav user to the amavis group in order for Amavisd-new to have the appropriate access to scan files:

sudo adduser clamav amavis sudo adduser amavis clamav

Spamassassin

Spamassassin automatically detects optional components and will use them if they are present. This means that there is no need to configure pyzor and razor.

Edit /etc/default/spamassassin to activate the Spamassassin daemon. Change ENABLED=0 to:

ENABLED=1

Now start the daemon:

sudo /etc/init.d/spamassassin start

Amavisd-new

First activate spam and antivirus detection in Amavisd-new by editing /etc/amavis/conf.d/15-content_filter_mode:

use strict;

# You can modify this file to re-enable SPAM checking through spamassassin # and to re-enable antivirus checking.

# # Default antivirus checking mode # Uncomment the two lines below to enable it #

@bypass_virus_checks_maps = (

 \%bypass_virus_checks, \@bypass_virus_checks_acl, \$bypass_virus_checks_re);

# # Default SPAM checking mode # Uncomment the two lines below to enable it #

@bypass_spam_checks_maps = (

 \%bypass_spam_checks, \@bypass_spam_checks_acl, \$bypass_spam_checks_re);

1; # insure a defined return

Bouncing spam can be a bad idea as the return address is often faked. Consider editing /etc/amavis/conf.d/20-debian_defaults to set $final_spam_destiny to D_DISCARD rather than D_BOUNCE, as follows:

$final_spam_destiny = D_DISCARD;

Additionally, you may want to adjust the following options to flag more messages as spam:

$sa_tag_level_deflt = -999; # add spam info headers if at, or above that level $sa_tag2_level_deflt = 6.0; # add 'spam detected' headers at that level $sa_kill_level_deflt = 21.0; # triggers spam evasive actions $sa_dsn_cutoff_level = 4; # spam level beyond which a DSN is not sent

If the server's hostname is different from the domain's MX record you may need to manually set the $myhostname option. Also, if the server receives mail for multiple domains the @local_domains_acl option will need to be customized. Edit the /etc/amavis/conf.d/50-user file:

$myhostname = 'mail.example.com'; @local_domains_acl = ( «example.com», «example.org» );

If you want to cover multiple domains you can use the following in the/etc/amavis/conf.d/50-user

@local_domains_acl = qw(.);

After configuration Amavisd-new needs to be restarted:

sudo /etc/init.d/amavis restart

DKIM Whitelist

Amavisd-new can be configured to automatically Whitelist addresses from domains with valid Domain Keys. There are some pre-configured domains in the /etc/amavis/conf.d/40-policy_banks.

There are multiple ways to configure the Whitelist for a domain:

  'example.com' => 'WHITELIST',: will whitelist any address from the "example.com" domain.
  '.example.com' => 'WHITELIST',: will whitelist any address from any subdomains of "example.com" that have a valid signature.
  '.example.com/@example.com' => 'WHITELIST',: will whitelist subdomains of "example.com" that use the signature of example.com the parent domain.
  './@example.com' => 'WHITELIST',: adds addresses that have a valid signature from "example.com". This is usually used for discussion groups that sign their messages.

A domain can also have multiple Whitelist configurations. After editing the file, restart amavisd-new:

sudo /etc/init.d/amavis restart

In this context, once a domain has been added to the Whitelist the message will not receive any anti-virus or spam filtering. This may or may not be the intended behavior you wish for a domain.

Postfix

For Postfix integration, enter the following from a terminal prompt:

sudo postconf -e 'content_filter = smtp-amavis:[127.0.0.1]:10024'

Next edit /etc/postfix/master.cf and add the following to the end of the file:

smtp-amavis unix - - - - 2 smtp

  1. o smtp_data_done_timeout=1200
  2. o smtp_send_xforward_command=yes
  3. o disable_dns_lookups=yes
  4. o max_use=20

127.0.0.1:10025 inet n - - - - smtpd

  1. o content_filter=
  2. o local_recipient_maps=
  3. o relay_recipient_maps=
  4. o smtpd_restriction_classes=
  5. o smtpd_delay_reject=no
  6. o smtpd_client_restrictions=permit_mynetworks,reject
  7. o smtpd_helo_restrictions=
  8. o smtpd_sender_restrictions=
  9. o smtpd_recipient_restrictions=permit_mynetworks,reject
  10. o smtpd_data_restrictions=reject_unauth_pipelining
  11. o smtpd_end_of_data_restrictions=
  12. o mynetworks=127.0.0.0/8
  13. o smtpd_error_sleep_time=0
  14. o smtpd_soft_error_limit=1001
  15. o smtpd_hard_error_limit=1000
  16. o smtpd_client_connection_count_limit=0
  17. o smtpd_client_connection_rate_limit=0
  18. o receive_override_options=no_header_body_checks,no_unknown_recipient_checks

Also add the following two lines immediately below the «pickup» transport service:

  1. o content_filter=
  2. o receive_override_options=no_header_body_checks

This will prevent messages that are generated to report on spam from being classified as spam.

Now restart Postfix:

sudo /etc/init.d/postfix restart

Content filtering with spam and virus detection is now enabled.

Amavisd-new и Spamassassin

When integrating Amavisd-new with Spamassassin, if you choose to disable the bayes filtering by editing /etc/spamassassin/local.cf and use cron to update the nightly rules, the result can cause a situation where a large amount of error messages are sent to the amavis user via the amavisd-new cron job.

There are several ways to handle this situation:

  Configure your MDA to filter messages you do not wish to see.
  Change /usr/sbin/amavisd-new-cronjob to check for use_bayes 0. For example, edit /usr/sbin/amavisd-new-cronjob and add the following to the top before the test statements:
  egrep -q "^[ \t]*use_bayes[ \t]*0" /etc/spamassassin/local.cf && exit 0

Проверка

First, test that the Amavisd-new SMTP is listening:

telnet localhost 10024 Trying 127.0.0.1… Connected to localhost. Escape character is '^]'. 220 [127.0.0.1] ESMTP amavisd-new service ready

In the Header of messages that go through the content filter you should see:

X-Spam-Level: X-Virus-Scanned: Debian amavisd-new at example.com X-Spam-Status: No, hits=-2.3 tagged_above=-1000.0 required=5.0 tests=AWL, BAYES_00 X-Spam-Level:

Your output will vary, but the important thing is that there are X-Virus-Scanned and X-Spam-Status entries.

Разрешение проблем

The best way to figure out why something is going wrong is to check the log files.

  For instructions on Postfix logging see the Troubleshooting section.
  Amavisd-new uses Syslog to send messages to /var/log/mail.log. The amount of detail can be increased by adding the $log_level option to /etc/amavis/conf.d/50-user, and setting the value from 1 to 5.
  $log_level = 2;
  When the Amavisd-new log output is increased Spamassassin log output is also increased.
  The ClamAV log level can be increased by editing /etc/clamav/clamd.conf and setting the following option:
  LogVerbose true
  By default ClamAV will send log messages to /var/log/clamav/clamav.log.

After changing an applications log settings remember to restart the service for the new settings to take affect. Also, once the issue you are troubleshooting is resolved it is a good idea to change the log settings back to normal.

Ссылки

For more information on filtering mail see the following links:

  Amavisd-new Documentation
  ClamAV Documentation and ClamAV Wiki
  Spamassassin Wiki
  Pyzor Homepage
  Razor Homepage
  DKIM.org
  Postfix Amavis New

Also, feel free to ask questions in the #ubuntu-server IRC channel on freenode.