Postfix+ClamAV+Spamassassin
Источник:
http://www.geocities.com/adilinux/postfix-clamav-clamsmtpd.html
Вступление
Сегодня существует много способов построить почтовую систему. Как правило, существует много документации для почтовых систем больших офисов, с применением реляционных баз данных в качестве хранения писем и экаунтов. Тем не менее, очень мало внимания уделяеться почтовым системам для малых и средних предприятий. Для начала определимся что нам не нужно:
1 Хранение сообщений и паролей в SQL. Думаю, что для небольшого количества почтовых эккаунтов, (от 3 до 100 пользователей), нет никакой необходимости поднимать MySQL, или другую систему баз данных.
2 Коммерческий антивирус. До написания этой статьи, я использовал антивирус для linux-почтовых систем DrWEB. Нареканий на его работу в системе у меня небыло, но к сожалению у него есть ряд серьезных недостатков в его поддержке: Вопервых, он платный. Помимо расходов предприятия на его приобретение и продление, сисадмин должен в обязательном порядке следить за его развитием. То есть, при изменении версии самой программы (исполняемого файла), бывает так, что его антивирусные базы становяться бесполезными. То есть, требуеться переустановка антивируса. В результате в офис на рабочие станции под управлением Windows,лавиной обрушиваються вирусы. На прошедшем СофтТуле, я задал этот вопрос их представителю. Он сказал что они пытаються решить эту проблему, но пока она не преодалена.
Итак, в качестве альтернативы, будем использовать свободно-распространяемый ClamAv.
В качестве проверки его работоспособности, я использовал карантин от DrWeb. Проверка папки этого карантина выявила 95% вирусов. Я считаю что, результат проверки хороший, и ClamAv достоин чтобы его применяли в офисе.
Теперь о том, что мы хотим от нашей системы, с помощью каких програм мы это достигнем:
1 Проверка писем на наличие вирусов с последующем их удалением.
2 Ведение логов этой проверки. Во избежание увеличения трафика, отсылку уведомлений не делать, а заменить ее ведением логов проверки.
3 Выявление спама, и перемещение его в imap-папку “SPAM”.
4 Раскладка писем по соответствующим их тематике imap-папкам.
Нужны програмы:
1 mail-mta/postfix-2.2.5
2 app-antivirus/clamav-0.88
3 mail-filter/clamsmtp-1.6
4 mail-filter/spamassassin-3.1.0
5 mail-filter/procmail-3.22-r7
6 net-mail/courier-imap-4.0.1
Код:
emerge postfix clamav clamsmtp spamassassin procmail courier-imap mutt |
Правим конфиг:
nano /etc/clamd.conf
Код:
LogFile /var/log/clamav/clamd.log LogTime PidFile /var/run/clamav/clamd.pid LocalSocket /var/run/clamav/clamd.sock FixStaleSocket User clamav |
Теперь запустим демон, и добавим в загрузку:
/etc/init.d/clamd start rc-update add clamd default |
Код:
asus etc # /etc/init.d/clamd start * Caching service dependencies ... [ ok ] * Starting clamd ... [ ok ] * Starting freshclam ... [ ok ] asus etc # rc-update add clamd default * clamd added to runlevel default * rc-update complete. |
Проверяем:
ps aux | grep clam Код: clamav 334 0.0 0.9 11100 9392 ? Ss 11:47 0:00 /usr/sbin/clamd clamav 336 0.0 0.1 2668 1040 ? Ss 11:47 0:00 /usr/bin/freshclam -d |
Как видим, помимо демона антивируса, rc-script поднимает и систему обновления.
nano /etc/clamsmtpd.conf
Код:
OutAddress: 10026 Listen: 0.0.0.0:10025 ClamAddress: /var/run/clamav/clamd.sock Header: BEREG-MAIL-SERVER: X-Virus-Scanned: ClamAV using ClamSMTP TempDirectory: /tmp # User to switch to User: clamav # Virus actions: There's an option to run a script every time a virus is found. # !IMPORTANT! This can open a hole in your server's security big enough to drive # farm vehicles through. Be sure you know what you're doing. !IMPORTANT! VirusAction: /etc/postfix/script.sh |
По умолчанию clamsmtpd не отсылает уведомлений. Их конечно можно включить в конфиге, но я предпочел воспользоваться скриптом по добавлению вирусов в карантин и ведения логов.
Вот пример лога
Sender admin@mydomain.ru Recipients admin@mydomain.ru Virus Eicar-Test-Signature ------------------------------------------------------- |
nano /etc/postfix/script.sh
Код:
#!/bin/sh file="/var/clamav/virus.log" dir="/var/clamav/quarantine/" exec 1>>$file exec 2>>$file # Add some fun log lines to the log file echo Sender $SENDER echo Recipients $RECIPIENTS echo Virus $VIRUS echo "-------------------------------------------------------" # Move the virus file to another directory # This only works if Quarantine is enabled if [ -n "$EMAIL" ]; then mv "$EMAIL" "$dir" fi |
Создаем каталог для карантина и дадим права
Код:
mkdir -p /var/clamav/quarantine/ chown clamav:clamav /etc/postfix/script.sh chmod 700 /etc/postfix/script.sh chown clamav:clamav -R /var/clamav/</strong> |
Запускаем:
Код:
asus etc # /etc/init.d/clamsmtpd start * Starting ClamSMTPd ... [ ok ] asus etc # rc-update add clamsmtpd default * clamsmtpd added to runlevel default * rc-update complete.</strong> |
Проверяем:
Код:
asus etc # netstat -l --inet | grep 10025 tcp 0 0 *:10025 *:* LISTEN |
Если ваш сервер находиться внутри локальной сети, то в файле /etc/postfix/header, впишите:
Код:
/192.168.1./ IGNORE |
Полезно создать
nano /etc/postfix/body_checks
Код:
/^[ ]*name=.*.(exe|dll|eml|vbs|pif|com|bat|scr|lnk)"?$/ REJECT /<iframe src=cid:.* height=0 width=0>/i REJECT /^Content-Disposition: attachment; *filename=.*.(exe|dll|eml|vbs|pif|com|bat|scr|lnk).*/i REJECT /^X-Unsent: 1/ REJECT /^X-Mailer: Advanced Mass Sender/ REJECT /^X-Mailer: Mail Bomber/ REJECT /^X-Mailer: .*-VC_IPA [/ REJECT |
Он на самой ранней стадии приема почты, отсеит нежелательные расширения и другие явные “почтовые нарушения”
Отредактируйте алиасы:
nano /etc/mail/aliases
Код:
# Basic system aliases -- these MUST be present. MAILER-DAEMON: postmaster postmaster: root # General redirections for pseudo accounts. adm: root bin: root daemon: root exim: root lp: root mail: root named: root nobody: root postfix: root # Well-known aliases -- these should be filled in! # root: # operator: # Standard RFC2142 aliases abuse: postmaster ftp: root hostmaster: root news: usenet noc: root security: root usenet: root uucp: root webmaster: root www: root root: admin |
В этом примере, все системные сообщение будут приходить на адрес admin@mydomain.ru
Не забудьте создать базу для алиасов командой:newaliases
Код:
newaliases |
nano /etc/postfix/main.cf </pr> Внимание, проверьте чтобы для вашего почтового сервера была в <strong>DNS</strong> запись <strong>MX</strong>, и <strong>DNSDOMAIN</strong> в <strong>/etc/conf.d/domainname</strong> соответствовала тому, что пропмсано в <strong>MX</strong>. Проще говоря, если ваш почтовый домен <strong>mydomaid.ru</strong> то и в вышеописанном тоже должно-быть <strong>mydomaid.ru</strong> Код:<pre lang="bash"> LOCAL PATHNAME INFORMATION # # The queue_directory specifies the location of the Postfix queue. # This is also the root directory of Postfix daemons that run chrooted. # See the files in examples/chroot-setup for setting up Postfix chroot # environments on different UNIX systems. # queue_directory = /var/spool/postfix # The command_directory parameter specifies the location of all # postXXX commands. # command_directory = /usr/sbin # The daemon_directory parameter specifies the location of all Postfix # daemon programs (i.e. programs listed in the master.cf file). This # directory must be owned by root. # daemon_directory = /usr/lib/postfix # QUEUE AND PROCESS OWNERSHIP # # The mail_owner parameter specifies the owner of the Postfix queue # and of most Postfix daemon processes. Specify the name of a user # account THAT DOES NOT SHARE ITS USER OR GROUP ID WITH OTHER ACCOUNTS # AND THAT OWNS NO OTHER FILES OR PROCESSES ON THE SYSTEM. In # particular, don't specify nobody or daemon. PLEASE USE A DEDICATED # USER. # mail_owner = postfix #------------------------- Необходимо для spamassassin mailbox_command = /usr/bin/procmail #------------------------- # The mydomain parameter specifies the local internet domain name. # The default is to use $myhostname minus the first component. # $mydomain is used as a default value for many other configuration # parameters. # #mydomain = domain.tld mydomain = mydomaid.ru # INTERNET HOST AND DOMAIN NAMES # # The myhostname parameter specifies the internet hostname of this # mail system. The default is to use the fully-qualified domain name # from gethostname(). $myhostname is used as a default value for many # other configuration parameters. # myhostname = asus.mydomaid.ru # The inet_interfaces parameter specifies the network interface # addresses that this mail system receives mail on. By default, # the software claims all active interfaces on the machine. The # parameter also controls delivery of mail to user@[ip.address]. # # See also the proxy_interfaces parameter, for network addresses that # are forwarded to us via a proxy or network address translator. # # Note: you need to stop/start Postfix when this parameter changes. # #inet_interfaces = all #inet_interfaces = $myhostname #inet_interfaces = $myhostname, localhost inet_interfaces = all # The mydestination parameter specifies the list of domains that this # machine considers itself the final destination for. # # These domains are routed to the delivery agent specified with the # local_transport parameter setting. By default, that is the UNIX # compatible delivery agent that lookups all recipients in /etc/passwd # and /etc/aliases or their equivalent. # # The default is $myhostname + localhost.$mydomain. On a mail domain # gateway, you should also include $mydomain. # # Do not specify the names of virtual domains - those domains are # specified elsewhere (see VIRTUAL_README). # # Do not specify the names of domains that this machine is backup MX # host for. Specify those names via the relay_domains settings for # the SMTP server, or use permit_mx_backup if you are lazy (see # STANDARD_CONFIGURATION_README). # # The local machine is always the final destination for mail addressed # to user@[the.net.work.address] of an interface that the mail system # receives mail on (see the inet_interfaces parameter). # # Specify a list of host or domain names, /file/name or type:table # patterns, separated by commas and/or whitespace. A /file/name # pattern is replaced by its contents; a type:table is matched when # a name matches a lookup key (the right-hand side is ignored). # Continue long lines by starting the next line with whitespace. # # See also below, section "REJECTING MAIL FOR UNKNOWN LOCAL USERS". # #mydestination = $myhostname, localhost.$mydomain, localhost #mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain #mydestination = $myhostname, localhost.$mydomain, localhost, $mydomain, mydestination = $myhostname, localhost, localhost.$mydomain, mydomaid.ru The local_recipient_maps parameter specifies optional lookup tables # with all names or addresses of users that are local with respect # to $mydestination, $inet_interfaces or $proxy_interfaces. # # If this parameter is defined, then the SMTP server will reject # mail for unknown local users. This parameter is defined by default. # # To turn off local recipient checking in the SMTP server, specify # local_recipient_maps = (i.e. empty). # # The default setting assumes that you use the default Postfix local # delivery agent for local delivery. You need to update the # local_recipient_maps setting if: # # - You define $mydestination domain recipients in files other than # /etc/passwd, /etc/aliases, or the $virtual_alias_maps files. # For example, you define $mydestination domain recipients in # the $virtual_mailbox_maps files. # # - You redefine the local delivery agent in master.cf. # # - You redefine the "local_transport" setting in main.cf. # # - You use the "luser_relay", "mailbox_transport", or "fallback_transport" # feature of the Postfix local delivery agent (see local(8)). # # Details are described in the LOCAL_RECIPIENT_README file. # # Beware: if the Postfix SMTP server runs chrooted, you probably have # to access the passwd file via the proxymap service, in order to # overcome chroot restrictions. The alternative, having a copy of # the system passwd file in the chroot jail is just not practical. # # The right-hand side of the lookup tables is conveniently ignored. # In the left-hand side, specify a bare username, an @domain.tld local_recipient_maps = # The unknown_local_recipient_reject_code specifies the SMTP server # response code when a recipient domain matches $mydestination or # ${proxy,inet}_interfaces, while $local_recipient_maps is non-empty # and the recipient address or address local-part is not found. # # The default setting is 550 (reject mail) but it is safer to start # with 450 (try again later) until you are certain that your # local_recipient_maps settings are OK. unknown_local_recipient_reject_code = 550 # Specify "mynetworks_style = class" when Postfix should "trust" SMTP # clients in the same IP class A/B/C networks as the local machine. # Don't do this with a dialup site - it would cause Postfix to "trust" # your entire provider's network. Instead, specify an explicit # mynetworks list by hand, as described below. # # Specify "mynetworks_style = host" when Postfix should "trust" # only the local machine. mynetworks_style = subnet #список сетей которым разрешено посылать почту через ваш домен mynetworks = 192.168.1.0/24, 127.0.0.0/8, 87.245.9.228/32, 194.186.255.6/32, 80.256.147.50/24, 81.206.16.88/24 # The relay_domains parameter restricts what destinations this system will # relay mail to. See the smtpd_recipient_restrictions description in # postconf(5) for detailed information. # # By default, Postfix relays mail # - from "trusted" clients (IP address matches $mynetworks) to any destination, # - from "untrusted" clients to destinations that match $relay_domains or # subdomains thereof, except addresses with sender-specified routing. # The default relay_domains value is $mydestination. # # In addition to the above, the Postfix SMTP server by default accepts mail # that Postfix is final destination for: # - destinations that match $inet_interfaces or $proxy_interfaces, # - destinations that match $mydestination # - destinations that match $virtual_alias_domains, # - destinations that match $virtual_mailbox_domains. # These destinations do not need to be listed in $relay_domains. # # Specify a list of hosts or domains, /file/name patterns or type:name # lookup tables, separated by commas and/or whitespace. Continue # long lines by starting the next line with whitespace. A file name # is replaced by its contents; a type:name table is matched when a # (parent) domain appears as lookup key. # # NOTE: Postfix will not automatically forward mail for domains that # list this system as their primary or backup MX host. See the # permit_mx_backup restriction description in postconf(5). # relay_domains = $mydestination #если сервер расположен внутри локальной сети masquerade_domains = asus.localdomain.ru mydomain.ru # ALIAS DATABASE # # The alias_maps parameter specifies the list of alias databases used # by the local delivery agent. The default list is system dependent. # # On systems with NIS, the default is to search the local alias # database, then the NIS alias database. See aliases(5) for syntax # details. # # If you change the alias database, run "postalias /etc/aliases" (or # wherever your system stores the mail alias file), or simply run # "newaliases" to build the necessary DBM or DB file. # # It will take a minute or so before changes become visible. Use # "postfix reload" to eliminate the delay. # alias_maps = hash:/etc/mail/aliases alias_database = hash:/etc/mail/aliases # DELIVERY TO MAILBOX # # The home_mailbox parameter specifies the optional pathname of a # mailbox file relative to a user's home directory. The default # mailbox file is /var/spool/mail/user or /var/mail/user. Specify # "Maildir/" for qmail-style delivery (the / is required). # #home_mailbox = Mailbox #home_mailbox = Maildir/ # #Обязательно поставьте этот параметр в .maildir/ home_mailbox = .maildir/ # PARALLEL DELIVERY TO THE SAME DESTINATION # # How many parallel deliveries to the same user or domain? With local # delivery, it does not make sense to do massively parallel delivery # to the same user, because mailbox updates must happen sequentially, # and expensive pipelines in .forward files can cause disasters when # too many are run at the same time. With SMTP deliveries, 10 # simultaneous connections to the same domain could be sufficient to # raise eyebrows. # # Each message delivery transport has its XXX_destination_concurrency_limit # parameter. The default is $default_destination_concurrency_limit for # most delivery transports. For the local delivery agent the default is 2. local_destination_concurrency_limit = 2 default_destination_concurrency_limit = 10 debug_peer_level = 2 # The debugger_command specifies the external command that is executed # when a Postfix daemon program is run with the -D option. # # Use "command .. & sleep 5" so that the debugger can attach before # the process marches on. If you use an X-based debugger, be sure to # set up your XAUTHORITY environment variable before starting Postfix. # debugger_command = PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin xxgdb $daemon_directory/$process_name $process_id & sleep 5 # INSTALL-TIME CONFIGURATION INFORMATION # # The following parameters are used when installing a new Postfix version. # # sendmail_path: The full pathname of the Postfix sendmail command. # This is the Sendmail-compatible mail posting interface. sendmail_path = /usr/sbin/sendmail # newaliases_path: The full pathname of the Postfix newaliases command. # This is the Sendmail-compatible command to build alias databases. # newaliases_path = /usr/bin/newaliases # mailq_path: The full pathname of the Postfix mailq command. This # is the Sendmail-compatible mail queue listing command. # mailq_path = /usr/bin/mailq # setgid_group: The group for mail submission and queue management # commands. This must be a group name with a numerical group ID that # is not shared with other accounts, not even with the Postfix account. # setgid_group = postdrop # manpage_directory: The location of the Postfix on-line manual pages. manpage_directory = /usr/share/man # sample_directory: The location of the Postfix sample configuration files. # This parameter is obsolete as of Postfix 2.1. sample_directory = /etc/postfix/sample # readme_directory = /usr/share/doc/postfix-2.0.11 #mailbox_transport = lmtp:unix:/var/imap/socket/lmtp #mailbox_transport = procmail #Ограничичиваем размер писем message_size_limit = 10485760 #Ограничичиваем число CC в одном письме. smtpd_recipient_limit = 15 # Ограничиваем размер ящика если надо #mailbox_size_limit = 51200000 smtpd_helo_required = yes smtpd_helo_restrictions = permit_mynetworks header_checks = regexp:/etc/postfix/header body_checks = regexp:/etc/postfix/body_checks # Например, если для службы безопасности # требуеться копировать всю почту в отдельный ящик: # В данном примере backup #always_bcc = backup@mydomain.ru header_checks = regexp:/etc/postfix/header body_checks = regexp:/etc/postfix/body_checks #smtpd_sasl_auth_enable = yes #smtpd_sasl_application_name = smtpd #smtpd_client_restrictions = permit_sasl_authenticated #smtpd_helo_restrictions = permit_mynetworks, reject_invalid_hostname #Если используете imap-ssl, создайте сертификаты и раскоментируйте #smtpd_sasl_auth_enable = yes #smtpd_sasl2_auth_enable = yes #smtpd_sasl_security_options = noanonymous #broken_sasl_auth_clients = yes #smtpd_sasl_local_domain = #smtpd_recipient_restrictions = permit_sasl_authenticated, #permit_mynetworks, reject_unauth_destination #smtpd_use_tls = yes #smtpd_tls_auth_only = yes #smtpd_tls_key_file = /etc/postfix/newreq.pem #smtpd_tls_cert_file = /etc/postfix/newcert.pem #smtpd_tls_CAfile = /etc/postfix/cacert.pem #smtpd_tls_loglevel = 3 #smtpd_tls_received_header = yes #smtpd_tls_session_cache_timeout = 3600s #tls_random_source = dev:/dev/urandom # Сюда добавим ссылку на clamsmtp #-------------------- Необходимо для функционирования антивируса - clamsmtp content_filter = scan:127.0.0.1:10025 receive_override_options = no_address_mappings #-------------------- |
А в master.cf надо добавить вот такие строчки:
nano /etc/postfix/master.cf
Код:
... # AV scan filter (used by content_filter) scan unix - - n - 16 smtp -o smtp_send_xforward_command=yes # For injecting mail back into postfix from the filter 127.0.0.1:10026 inet n - n - 16 smtpd -o content_filter= -o receive_override_options=no_unknown_recipient_checks,no_header_body_checks -o smtpd_helo_restrictions= -o smtpd_client_restrictions= -o smtpd_sender_restrictions= -o smtpd_recipient_restrictions=permit_mynetworks,reject -o mynetworks_style=host -o smtpd_authorized_xforward_hosts=127.0.0.0/8 |
Конфиги править необходимости нет. Только запустить и прописать в автозагрузку.
/etc/init.d/courier-imapd start rc-update add courier-imapd default |
Прежде всего заведем группу и пользователя для spamassassin.
Код:
# groupadd spam # useradd -d /etc/mail/spamassassin/ -s /bin/false -g spam spam |
Чтобы spamassassin запускался от имени заведенных нами пользователя и группы, надо в файле /etc/conf.d/spamd, найти строчку: “SPAMD_OPTS=” и поправить ее:
nano /etc/conf.d/spamd
Код:
SPAMD_OPTS="-u spam -m 5 -c -H" |
nano /etc/mail/spamassassin/local.cf
Код:
# This is the right place to customize your installation of SpamAssassin. # # See 'perldoc Mail::SpamAssassin::Conf' for details of what can be # tweaked. # # Only a small subset of options are listed below # ########################################################################### # # Пометим заголовок спамовских писем... rewrite_header Subject *****SPAM***** ( _HITS_ ) # Save spam messages as a message/rfc822 MIME attachment instead of # modifying the original message (0: off, 2: use text/plain instead) # report_safe 1 # Set which networks or hosts are considered 'trusted' by your mail # server (i.e. not spammers) # trusted_networks 192.168.1.0/24 # Set file-locking method (flock is not safe over NFS, but is faster) # # lock_method flock # Set the threshold at which a message is considered spam (default: 5.0) # required_score 5.0 skip_rbl_checks 1 # Use Bayesian classifier (default: 1) # use_bayes 1 # Bayesian classifier auto-learning (default: 1) # bayes_auto_learn 1 # Set headers which may provide inappropriate cues to the Bayesian # classifier # bayes_ignore_header X-Bogosity bayes_ignore_header X-Spam-Flag bayes_ignore_header X-Spam-Status # Белые и черные списки bayes_ignore_from *@mydomain.ru bayes_ignore_to *@mydomain.ru bayes_ignore_from ELiza1101@yandex.ru bayes_ignore_to ELiza1101@yandex.ru # Sensitive data, such as database connection info, should # be stored in /etc/mail/spamassassin/secrets.cf with # appropriate permissions #ok_languages ru en ok_locales ru en report_charset utf8 #lang ru #----------------------------- whitelist_from *@mydomain.ru whitelist_to *@mydomain.ru |
И как всегда:
/etc/init.d/spamd start rc-update add spamd default </pre Заставив postfix работать с procmail, мы убьем сразу двух зайцев: 1 Сможем помечать и определять в соответствующую папку спам-письма. 2 Сможем распихивать по созданным вами папкам соответствующие им темы писем. Приступим: <strong>nano /etc/procmailrc</strong> или в домашнем каталоге пользователя <strong>nano .procmailrc</strong> Код:<pre lang="bash"> DEFAULT=$HOME/.maildir/ :0fw | /usr/bin/spamc :0 * ^Subject:.*SPAM $HOME/.maildir/.SPAM/cur :0 * ^Subject:.*CRON $HOME/.maildir/.CRON/cur :0 * ^Subject:.*filonly $HOME/.maildir/.FILONLY/cur :0 * ^Subject:.*M O N I T O R I N G $HOME/.maildir/.MONITORING/cur :0 * ^Subject:.*REPLICATION $HOME/.maildir/.REPLICATION/cur :0 * ^Subject:.*Undelivered mail $HOME/.maildir/.Undelivered/cur |
Не забудьте в своем почтовом клиенте создать вышеперечисленные imap-папки.
Для проверки работы VlamSmtp, пошлите себе письмо с сигнатурой Eicar
Код:
X5O!P%@AP[4PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H* |
Для проверки работы Spamassassin, пошлите себе письмо вот с таким содержимым:
Код:
This is the GTUBE, the Generic Test for Unsolicited Bulk Email If your spam filter supports it, the GTUBE provides a test by which you can verify that the filter is installed correctly and is detecting incoming spam. You can send yourself a test mail containing the following string of characters (in upper case and with no white spaces and line breaks): XJS*C4JDBQADN1.NSBN3*2IDNEN*GTUBE-STANDARD-ANTI-UBE-TEST-EMAIL*C.34X You should send this test mail from an account outside of your network. -- |
Я не считаю себя польшим профи в создании почтовых серверов, тем не менее, конфигурация, которая приведена выше, несмотря ниначто функционирует!
При этом, никаких тормозов не наблюдаеться.