Фильтрация почты Сравнение версий

Различия

Здесь показаны различия между двумя версиями данной страницы.

Ссылка на это сравнение

Следующая версия
Предыдущая версия
wiki:руководство_по_ubuntu_server:почтовые_сервисы:mail_filtering [2012/08/31 20:43]
создано
wiki:руководство_по_ubuntu_server:почтовые_сервисы:mail_filtering [2013/02/21 13:06]
[Настройка]
Строка 8: Строка 8:
 =====Фильтрация почты===== =====Фильтрация почты=====
  
-One of the largest issues with email today is the problem of Unsolicited Bulk Email (UBE). Also known as SPAMsuch messages may also carry viruses and other forms of malwareAccording to some reports these messages make up the bulk of all email traffic on the Internet.+Одной из больших проблем с электронной почтой является проблема массовой незатребованной почты (Unsolicited Bulk Email UBE). Такие сообщения,​ более известные как СПАМмогут к тому же содержать вирусы и другие виды вредоносных программВ соответствии с некоторыми отчетами эти сообщения составляют подавляющую часть от всего трафика почтовых сообщений в интернете.
  
-This section will cover integrating ​Amavisd-new,​ Spamassassin, and ClamAV ​with the Postfix Mail Transport Agent (MTA). Postfix ​can also check email validity by passing it through external content filtersThese filters can sometimes determine if a message is spam without needing to process it with more resource intensive applicationsTwo common filters are opendkim ​and python-policyd-spf.+В этом разделе рассматривается интеграция **Amavisd-new****Spamassassin** и **ClamAV** с транспортным почтовым агентом ​(MTA) **Postfix**. Postfix ​может также проверять легальность почты с помощью передачи ее внешним фильтрам содержанияЭти фильтры могут иногда определить что сообщение является спамом без необходимости передачи его более ресурсоемким приложениямПара таких фильтров - это **opendkim** и **python-policyd-spf**.
  
-    ​Amavisd-new ​is a wrapper program that can call any number of content filtering programs for spam detectionantivirusetc.+  -- **Amavisd-new** - это программная оболочкакоторая может вызывать любое количество фильтрующих программ по обнаружению спамаантивирусов и т.п. 
 +  -- **Spamassassin** использует множество механизмов фильтрования почты на основе содержимого сообщений. 
 +  -- **ClamAV** - антивирусное приложение с открытым кодом. 
 +  -- **opendkim** является почтовым фильтром Sendmail для стандарта DKIM (почты,​ заверенной доменными ключами). 
 +  -- **python-policyd-spf** обеспечивает проверку SPF (структуры политики отправителя) с Postfix.
  
-    ​Spamassassin ​uses a variety of mechanisms to filter email based on the message content.+А здесь то, как эти части работают вместе:​ 
 +  -- Почтовое сообщение принимается Postfix. 
 +  -- Это сообщение проходит через некоторые внешние фильтры,​ в том числе opendkim и python-policyd-spf. 
 +  -- Затем сообщение обрабатывается Amavisd-new. 
 +  -- ClamAV используется для проверки сообщения. Если сообщение содержит вирус, Postfix сбросит сообщение. 
 +  -- Чистые сообщения затем будут проверены ​Spamassassin ​на принадлежность к спаму. Spamassassin затем добавит строки **X-Header**,​ позволяющие в дальнейшем Amavisd-new управлять сообщением.
  
-    ClamAV is an open source antivirus application. +Напримересли сообщение содержит уровень спама более пятидесяти,​ оно будет автоматически выброшено из очереди чтобы не беспокоить получателяВ качестве альтернативы помеченное сообщение доставляется до почтового агента пользователя ​(MUA) чтобы пользователь сам определил насколько оно легальное.
- +
-    opendkim implements a Sendmail Mail Filter (Milter) for the DomainKeys Identified Mail (DKIM) standard. +
- +
-    python-policyd-spf enables Sender Policy Framework (SPF) checking with Postfix. +
- +
-This is how the pieces fit together: +
- +
-    An email message is accepted by Postfix. +
- +
-    The message is passed through any external filters opendkim and python-policyd-spf in this case. +
- +
-    Amavisd-new then processes the message. +
- +
-    ClamAV is used to scan the message. If the message contains a virus Postfix will reject the message. +
- +
-    Clean messages will then be analyzed by Spamassassin to find out if the message is spam. Spamassassin will then add X-Header lines allowing Amavisd-new to further manipulate the message. +
- +
-For exampleif a message has a Spam score of over fifty the message could be automatically dropped from the queue without the recipient ever having to be botheredAnother, way to handle flagged messages is to deliver them to the Mail User Agent (MUA) allowing the user to deal with the message as they see fit. +
- +
-    Installation +
-    Configuration +
-    Testing +
-    Troubleshooting +
-    References+
  
 ====Установка==== ====Установка====
  
-See Postfix ​for instructions on installing and configuring ​Postfix. +Смотрите раздел [[wiki:​руководство_по_ubuntu_server:​почтовые_сервисы:​postfix|Postfix]] для установки и настройки ​Postfix.
- +
-To install the rest of the applications enter the following from a terminal prompt:+
  
 +Чтобы установить основные приложения введите следующее в терминале:​
 +<​code>​
 sudo apt-get install amavisd-new spamassassin clamav-daemon sudo apt-get install amavisd-new spamassassin clamav-daemon
 sudo apt-get install opendkim postfix-policyd-spf-python sudo apt-get install opendkim postfix-policyd-spf-python
 +</​code>​
 +Существуют некоторые общие пакеты,​ подключаемые к Spamassassin для лучшего определения спама:
 +<​code>​sudo apt-get install pyzor razor</​code>​
  
-There are some optional packages that integrate with Spamassassin for better spam detection:+Поскольку основным фильтрующим приложениям требуются утилиты архивации для обработки прикрепленных файлов: 
 +<​code>​sudo apt-get install arj cabextract cpio lha nomarch pax rar unrar unzip zip</​code>​
  
-sudo apt-get install pyzor razor +<​note>​Если какие-то пакеты не были найденыпроверьте что хранилище ​multiverse ​разрешено в /​etc/​apt/​sources.list.
- +
-Along with the main filtering applications compression utilities are needed to process some email attachments:​ +
- +
-sudo apt-get install arj cabextract cpio lha nomarch pax rar unrar unzip zip +
- +
-If some packages are not foundcheck that the multiverse ​repository is enabled in /​etc/​apt/​sources.list +
- +
-If you make changes to the file, be sure to run sudo apt-get update before trying to install again.+
  
 +Если вы внесли изменения в этот файл, убедитесь,​ что выполнили
 +<​code>​sudo apt-get update</​code>​
 +перед повторной попыткой установки.</​note>​
 ====Настройка==== ====Настройка====
  
-Now configure everything to work together and filter email.+Теперь настроим чтобы все работало и фильтровало почту.
  
 ===ClamAV=== ===ClamAV===
  
-The default behaviour of ClamAV ​will fit our needsFor more ClamAV configuration options, check the configuration files in /​etc/​clamav. +Стандартное поведение ​ClamAV ​вполне подходит для наших нуждДля дополнительных опций настройки смотрите конфигурационные файлы в /​etc/​clamav.
- +
-Add the clamav user to the amavis group in order for Amavisd-new to have the appropriate access to scan files:+
  
 +Добавьте пользователя clamav в группу amavis, чтобы Amavisd-new имел соответствующие права доступа для сканирования файлов:​
 +<​code>​
 sudo adduser clamav amavis sudo adduser clamav amavis
 sudo adduser amavis clamav sudo adduser amavis clamav
 +</​code>​
  
 ===Spamassassin=== ===Spamassassin===
  
-Spamassassin ​automatically detects optional components and will use them if they are presentThis means that there is no need to configure ​pyzor and razor.+Spamassassin ​автоматически определяет общие компоненты и использует их, если они присутствуютЭто означает,​ что нет необходимости настраивать ​pyzor и razor.
  
-Edit /​etc/​default/​spamassassin ​to activate the Spamassassin ​daemonChange ​ENABLED=0 ​to:+Отредактируйте ​/​etc/​default/​spamassassin ​для активации сервиса ​Spamassassin. ​Измените <​code>​ENABLED=0</​code>​ на <​code>​ENABLED=1</​code>​
  
-ENABLED=1 +Теперь запустим сервис
- +<​code>​sudo /​etc/​init.d/​spamassassin start</​code>​
-Now start the daemon+
- +
-sudo /​etc/​init.d/​spamassassin start+
  
 ===Amavisd-new=== ===Amavisd-new===
  
-First activate spam and antivirus detection in Amavisd-new ​by editing ​/​etc/​amavis/​conf.d/​15-content_filter_mode:​ +Сначала активируем проверку на спам и вирусы в Amavisd-new, отредактировав ​/​etc/​amavis/​conf.d/​15-content_filter_mode:​ 
 +<​code>​
 use strict; use strict;
  
Строка 115: Строка 97:
  
 1;  # insure a defined return 1;  # insure a defined return
 +</​code>​
  
-Bouncing spam can be a bad idea as the return address is often fakedConsider editing ​/​etc/​amavis/​conf.d/​20-debian_defaults ​to set $final_spam_destiny ​to D_DISCARD ​rather than D_BOUNCE, ​as follows+Возврат спама может быть плохой идеей, поскольку обратный адрес часто неверныйПодумайте над тем, чтобы изменить в /​etc/​amavis/​conf.d/​20-debian_defaults ​установку ​$final_spam_destiny ​на D_DISCARD ​вместо ​D_BOUNCE, ​как показано ниже
 +<​code>​
 $final_spam_destiny ​      = D_DISCARD; $final_spam_destiny ​      = D_DISCARD;
- +</​code>​ 
-Additionally,​ you may want to adjust the following options to flag more messages as spam+Дополнительно вы можете захотеть установить следующие опциональные флаги для отметки большего количества сообщений как спам
 +<​code>​
 $sa_tag_level_deflt = -999; # add spam info headers if at, or above that level $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_tag2_level_deflt = 6.0; # add 'spam detected'​ headers at that level
 $sa_kill_level_deflt = 21.0; # triggers spam evasive actions $sa_kill_level_deflt = 21.0; # triggers spam evasive actions
 $sa_dsn_cutoff_level = 4; # spam level beyond which a DSN is not sent $sa_dsn_cutoff_level = 4; # spam level beyond which a DSN is not sent
 +</​code>​
  
-If the server'​s hostname is different from the domain'​s ​MX record you may need to manually set the $myhostname ​optionAlsoif the server receives mail for multiple domains the @local_domains_acl ​option will need to be customizedEdit the /​etc/​amavis/​conf.d/​50-user ​file+Если сетевое имя сервера отличается от MX записи домена,​ вам может потребоваться установить вручную опцию ​$myhostname. ​Также, если сервер принимает почту для нескольких доменовопцию ​@local_domains_acl ​потребуется изменитьОтредактируйте файл ​/​etc/​amavis/​conf.d/​50-user:​ 
 +<​code>​
 $myhostname = '​mail.example.com';​ $myhostname = '​mail.example.com';​
 @local_domains_acl = ( "​example.com",​ "​example.org"​ ); @local_domains_acl = ( "​example.com",​ "​example.org"​ );
 +</​code>​
  
-If you want to cover multiple domains you can use the following in the/​etc/​amavis/​conf.d/​50-user+Если вы хотите покрывать несколько доменов,​ вы можете использовать следующее в файле ​/​etc/​amavis/​conf.d/​50-user
 +<​code>​@local_domains_acl = qw(.);</​code>​
  
-@local_domains_acl = qw(.);+После настройки Amavisd-new требуется перезапустить:​ 
 +<​code>​sudo /etc/init.d/amavis restart</​code>​
  
-After configuration Amavisd-new needs to be restarted:+==Белые списки DKIM==
  
-sudo /etc/init.d/amavis restart+Amavisd-new может быть настроен на автоматическое занесение адресов в белый список из доменов с действительными доменными ключами. Есть несколько предварительно настроенных доменов в /etc/amavis/conf.d/40-policy_banks.
  
-==DKIM Whitelist==+Существует несколько вариантов настройки белого списка для домена:​
  
-Amavisd-new can be configured to automatically Whitelist addresses from domains with valid Domain KeysThere are some pre-configured domains in the /​etc/​amavis/​conf.d/40-policy_banks.+  ​-- **%%'​example.com' => '​WHITELIST',​%%**:​ будет помещен в белый список любой адрес домена %%"​example.com"​%%. 
 +  ​-- **%%'.example.com'​ => '​WHITELIST',​%%**:​ будет помещен в белый список любой адрес любого поддомена,​ который имеет действительную подпись. 
 +  -- **%%'​.example.com/@example.com'​ => '​WHITELIST',​%%**:​ будут помещены в белый список поддомены %%"​example.com"​%%,​ которые используют подпись родительского домена example.com. 
 +  ​-- **%%'​./​@example.com'​ => '​WHITELIST',​%%**:​ добавляет адреса,​ которые имеют действительную подпись от %%"​example.com"​%%. Это обычно используется для дискуссионных групп, которые подписывают свои сообщения.
  
-There are multiple ways to configure the Whitelist for a domain:+Домен может иметь несколько настроек белого списка. После редактирования файла, перезапустите amavisd-new: 
 +<​code>​sudo /​etc/​init.d/​amavis restart</​code>​
  
-    '​example.com'​ ='​WHITELIST'​,: will whitelist any address from the "​example.com"​ domain. +<note>В этом контекстеесли домен добавлен в белый списоксообщение не будет передано каким-либо антивирусным или спам фильтрамЭто может быть как желательнымтак и нежелательным поведением для вашего домена.</note>
- +
-    '​.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=== ===Postfix===
  
-For Postfix ​integrationenter the following from a terminal prompt+Для интеграции ​Postfix, ​введите следующее из терминала
- +<​code>​sudo postconf -e '​content_filter = smtp-amavis:​[127.0.0.1]:​10024'​</code>
-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:+
  
 +Далее отредактируйте /​etc/​postfix/​master.cf,​ добавив следующее в коне файла:
 +<​code>​
 smtp-amavis ​    ​unix ​   -       ​- ​      ​- ​      ​- ​      ​2 ​      smtp smtp-amavis ​    ​unix ​   -       ​- ​      ​- ​      ​- ​      ​2 ​      smtp
         -o smtp_data_done_timeout=1200         -o smtp_data_done_timeout=1200
Строка 193: Строка 171:
         -o smtpd_client_connection_rate_limit=0         -o smtpd_client_connection_rate_limit=0
         -o receive_override_options=no_header_body_checks,​no_unknown_recipient_checks         -o receive_override_options=no_header_body_checks,​no_unknown_recipient_checks
 +</​code>​
  
-Also add the following two lines immediately below the "​pickup" ​transport service:+Также добавьте следующие две строки непосредственно после транспортного сервиса %%"​pickup"​%%: 
 +<​code>​ 
 +        -o content_filter= 
 +        -o receive_override_options=no_header_body_checks 
 +</​code>​ 
 +Это предотвратит от попадания в спам сообщений,​ созданных в качестве отчетов о спаме.
  
-         -o content_filter= +Теперь перезапустите Postfix: 
-         -o receive_override_options=no_header_body_checks+<​code>​sudo /​etc/​init.d/​postfix restart</​code>​
  
-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=== ===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 rulesthe result can cause a situation where a large amount of error messages are sent to the amavis ​user via the amavisd-new ​cron job.+При интеграции ​Amavisd-new ​со Spamassassin, ​если вы решили заблокировать фильтр Байеса,​ отредактировав  ​/​etc/​spamassassin/​local.cf, и использовать ​cron для обновления ночных правилто это может привести к ситуации,​ когда большой объем сообщений об ошибках будет посылаться пользователю ​amavis ​через задание cron amavisd-new.
  
-There are several ways to handle this situation:+Существует несколько вариантов разрешить эту ситуацию:
  
-    Configure your MDA to filter messages you do not wish to see+  -- Настройте ваш ​MDA на фильтрацию сообщений,​ которые вы не желаете видеть
- +  -- Измените ​/​usr/​sbin/​amavisd-new-cronjob ​на проверку,​ что ​use_bayes ​установлен в 0. Напримеротредактируйте ​/​usr/​sbin/​amavisd-new-cronjob, добавив следующее в начало до строк проверки
-    Change ​/​usr/​sbin/​amavisd-new-cronjob ​to check for use_bayes 0. For exampleedit /​usr/​sbin/​amavisd-new-cronjob ​and add the following to the top before the test statements+<​code>​egrep -q "^[ \t]*use_bayes[ \t]*0" /​etc/​spamassassin/​local.cf && exit 0</​code>​
- +
-    ​egrep -q "^[ \t]*use_bayes[ \t]*0" /​etc/​spamassassin/​local.cf && exit 0+
  
 ====Проверка==== ====Проверка====
  
-Firsttest that the Amavisd-new SMTP is listening+Для начала проверьтечто ​Amavisd-new SMTP активен
 +<​code>​
 telnet localhost 10024 telnet localhost 10024
 Trying 127.0.0.1... Trying 127.0.0.1...
Строка 229: Строка 205:
 220 [127.0.0.1] ESMTP amavisd-new service ready 220 [127.0.0.1] ESMTP amavisd-new service ready
 ^] ^]
 +</​code>​
  
-In the Header of messages that go through the content filter you should see+В заголовке сообщений,​ которые будут проходить через фильтр содержимого вы должны увидеть следующее
 +<​code>​
 X-Spam-Level: ​ X-Spam-Level: ​
 X-Virus-Scanned:​ Debian amavisd-new at example.com 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-Status:​ No, hits=-2.3 tagged_above=-1000.0 required=5.0 tests=AWL, BAYES_00
 X-Spam-Level: ​ X-Spam-Level: ​
 +</​code>​
  
-Your output will varybut the important thing is that there are X-Virus-Scanned ​and X-Spam-Status ​entries.+<​note>​Ваш вариант может отличатьсяно важно чтобы присутствовали записи ​X-Virus-Scanned ​и X-Spam-Status.</​note>​
  
 ====Разрешение проблем==== ====Разрешение проблем====
  
-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.+ 1. Для инструкций по журналам **Postfix** смотрите раздел [[wiki:​руководство_по_ubuntu_server:​почтовые_сервисы:​postfix#​решение_проблем|Разрешение проблем]].
  
-    ​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 to 5.+ 2. **Amavisd-new** использует ​Syslog ​для отправки сообщений в /​var/​log/​mail.log. ​Количество деталей может быть увеличено добавлением опции ​$log_level ​в /​etc/​amavis/​conf.d/​50-user ​и установкой значения от до 5. 
 +<​code>​$log_level = 2;</​code>​ 
 +<​note>​Когда вывод журнала Amavisd-new увеличивается,​ то вывод журнала Spamassassin также увеличивается.</​note>​
  
-    $log_level = 2;+ 3. Уровень журналирования ClamAV может быть увеличен редактированием /​etc/​clamav/​clamd.conf и установкой следующей опции:​ 
 +<​code>​LogVerbose true</​code>​ 
 +По уолчанию ClamAV посылает сообщения в журнал /​var/​log/​clamav/​clamav.log.
  
-    When the Amavisd-new log output is increased Spamassassin log output is also increased. +<​note>​После изменения уровня журналирования не забывайте перезапускать сервис для активации новых настроекТакже после установления причины проблем будет хорошей идеей вернуть уровень журналирования к нормальному значению.</note>
- +
-    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+  -- [[http://​www.ijs.si/​software/​amavisd/​amavisd-new-docs.html|Документация по Amavisd-new]] 
 +  -- [[http://​www.clamav.net/​doc/​latest/​html/​|Документация по ClamAV]] и [[http://​wiki.clamav.net/​Main/​WebHome|ClamAV Wiki]] 
 +  -- [[http://​wiki.apache.org/​spamassassin/​|Spamassassin Wiki]] 
 +  -- [[http://​sourceforge.net/​apps/​trac/​pyzor/​|Домашняя страница Pyzor]] 
 +  -- [[http://​razor.sourceforge.net/​|Домашняя страница Razor]] 
 +  -- [[http://​dkim.org/​|DKIM.org]] 
 +  -- [[https://​help.ubuntu.com/​community/​PostfixAmavisNew|Postfix Amavis New]]
  
-Also, feel free to ask questions in the #​ubuntu-server ​IRC channel on freenode.+Также не стесняйтесь задавать вопросы в канале IRC **#​ubuntu-server** на [[http://​freenode.net/​|freenode]].
  
 ---- ----