Различия
Здесь показаны различия между двумя версиями данной страницы.
Предыдущая версия справа и слева Предыдущая версия Следующая версия | Предыдущая версия | ||
wiki:руководство_по_ubuntu_server:почтовые_сервисы:mail_filtering [2012/09/01 12:33] [Фильтрация почты] |
wiki:руководство_по_ubuntu_server:почтовые_сервисы:mail_filtering [2013/02/21 13:06] (текущий) [Настройка] |
||
---|---|---|---|
Строка 25: | Строка 25: | ||
-- Чистые сообщения затем будут проверены Spamassassin на принадлежность к спаму. Spamassassin затем добавит строки **X-Header**, позволяющие в дальнейшем Amavisd-new управлять сообщением. | -- Чистые сообщения затем будут проверены Spamassassin на принадлежность к спаму. Spamassassin затем добавит строки **X-Header**, позволяющие в дальнейшем Amavisd-new управлять сообщением. | ||
- | Например, если сообщение содержит уровень спама более пятидесяти, оно будет автоматически выброшено из очереди чтобы не беспокоить получателя. В качестве альтернативы помеченное сообщение доставляется до почтового агента пользователя (MUA) чтобы пользователь сам определил насколько оно важное. | + | Например, если сообщение содержит уровень спама более пятидесяти, оно будет автоматически выброшено из очереди чтобы не беспокоить получателя. В качестве альтернативы помеченное сообщение доставляется до почтового агента пользователя (MUA) чтобы пользователь сам определил насколько оно легальное. |
====Установка==== | ====Установка==== | ||
- | 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 found, check 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 needs. For 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 present. This means that there is no need to configure pyzor and razor. | + | Spamassassin автоматически определяет общие компоненты и использует их, если они присутствуют. Это означает, что нет необходимости настраивать pyzor и razor. |
- | Edit /etc/default/spamassassin to activate the Spamassassin daemon. Change 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; | ||
Строка 100: | Строка 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 faked. Consider 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 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: | + | Если сетевое имя сервера отличается от 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 Keys. There 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 integration, enter 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 | ||
Строка 178: | Строка 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 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. | + | При интеграции 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 example, edit /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 | + | |
====Проверка==== | ====Проверка==== | ||
- | First, test 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... | ||
Строка 214: | Строка 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 vary, but 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 1 to 5. | + | 2. **Amavisd-new** использует Syslog для отправки сообщений в /var/log/mail.log. Количество деталей может быть увеличено добавлением опции $log_level в /etc/amavis/conf.d/50-user и установкой значения от 1 до 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]]. |
---- | ---- |