Copyright (C) 2010 Konstantin Nadezhdin <w.homenki.ru>.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3
or any later version published by the Free Software Foundation;
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
A copy of the license is included in the section entitled "GNU
Free Documentation License".
GNU Free Documentation License
#amavisd-new #Current logs LogFile = amavis.log #Arcvive logs Archive = amavis.log-*
# Configuration overrides for specific logfiles/services may be placed here. logfiles/maillog: LogFile = mail logfiles/maillog: Archive = mail-*
#!/bin/sh # #Copyright 2009 Konstantin Nadezhdin <w.homenki.ru> # #This program is free software: you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation, either version 3 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. # #You should have received a copy of the GNU General Public License #along with this program. If not, see <http://www.gnu.org/licenses/>. Detail="6" # Детализация. Макс. 10 Service="amavisd-new" # Имя сервиса # Range Примеры # today # yesterday # '4 hours ago for that hour' # '-3 days' # 'since 2 hours ago for those hours' # 'between -10 and -2 days' # 'Apr 15, 2005' # 'first Monday in May' # 'between 4/23/2005 and 4/30/2005' # '2005/05/03 10:24:17 for that second' Range="Today" #Print="" # Не печатать на экран Print="--print" # Печатать на экран #Output="html" # mail, html or unformatted Output="unformatted" # По умолчанию unformatted if [ "$Output" = "html" ] ; then Ext="html" else Ext="txt" fi #Save="" # По умолчанию отчет будет отправлен в почтовый ящик root #Save="--save /srv/www/htdocs/logwatch/$Service.$Ext" # Отчет сохранить в файл Save2="/srv/www/htdocs/logwatch/$Service.$Ext" # Отчет сохранить в файл # Все остальные параметры будут считаны по умолчанию из конфига logwatch /usr/sbin/logwatch --detail $Detail --service $Service --range $Range --output $Output $Print > $Save2 test -e /srv/www/htdocs/logwatch/$Service.$Ext && chmod 0644 /srv/www/htdocs/logwatch/$Service.$ExtВ скриптах отличие: только в имени сервиса amavisd-new или postfix-new и детализации 6 или 7 соответственно. Для корректной отработки скрипта должен существовать каталог: /srv/www/htdocs/logwatch
*/30 9-18 * * 1-5 /usr/local/bin/amavisd-logwatch.sh 5,35 9-18 * * 1-5 /usr/local/bin/postfix-logwatch.shскрипты выполнять каждые 30 минут с 9 до 18 часов с понедельника по пятницу, второй скрипт сдвинут на 5 минут чтобы не пересекался. Создать задание можно путем записи строк в файл (напр test.cron) и выполнения команды: crontab -u root test.cron . Проверить задание можно так: crontab -u root -l
Настройка spamassassin
Должны быть установлены следующие модули:[28457] dbg: diag: module installed: Digest::SHA1, version 2.11 [28457] dbg: diag: module installed: HTML::Parser, version 3.56 [28457] dbg: diag: module installed: Net::DNS, version 0.60 [28457] dbg: diag: module installed: MIME::Base64, version 3.07 [28457] dbg: diag: module installed: DB_File, version 1.814 [28457] dbg: diag: module installed: Net::SMTP, version 2.29 [28457] dbg: diag: module installed: IO::Socket::SSL, version 1.07 [28457] dbg: diag: module installed: Compress::Zlib, version 2.005 [28457] dbg: diag: module installed: Time::HiRes, version 1.86 [28457] dbg: diag: module installed: DBI, version 1.58 [28457] dbg: diag: module installed: Getopt::Long, version 2.35 [28457] dbg: diag: module installed: LWP::UserAgent, version 2.036 [28457] dbg: diag: module installed: HTTP::Date, version 1.47 [28457] dbg: diag: module installed: Archive::Tar, version 1.32 [28457] dbg: diag: module installed: IO::Zlib, version 1.06 [28457] dbg: diag: module installed: Encode::Detect, version 1.01проверить можно так:
spamassassin --lint -D 2>&1 | grep -E "module installed"Настройка после установки из репозитария сводится к редактированию файлов в /etc/mail/spamassassin/
loadplugin Mail::SpamAssassin::Plugin::URIDNSBL loadplugin Mail::SpamAssassin::Plugin::Hashcash loadplugin Mail::SpamAssassin::Plugin::SPFВ файле v310.pre произведены изменения, содержит строки:
loadplugin Mail::SpamAssassin::Plugin::AWL loadplugin Mail::SpamAssassin::Plugin::AutoLearnThreshold loadplugin Mail::SpamAssassin::Plugin::TextCat loadplugin Mail::SpamAssassin::Plugin::WhiteListSubject loadplugin Mail::SpamAssassin::Plugin::MIMEHeader loadplugin Mail::SpamAssassin::Plugin::ReplaceTagsнекоторые плагины не используем.
loadplugin Mail::SpamAssassin::Plugin::Check loadplugin Mail::SpamAssassin::Plugin::HTTPSMismatch loadplugin Mail::SpamAssassin::Plugin::URIDetail loadplugin Mail::SpamAssassin::Plugin::Bayes loadplugin Mail::SpamAssassin::Plugin::BodyEval loadplugin Mail::SpamAssassin::Plugin::DNSEval loadplugin Mail::SpamAssassin::Plugin::HTMLEval loadplugin Mail::SpamAssassin::Plugin::HeaderEval loadplugin Mail::SpamAssassin::Plugin::MIMEEval loadplugin Mail::SpamAssassin::Plugin::RelayEval loadplugin Mail::SpamAssassin::Plugin::URIEval loadplugin Mail::SpamAssassin::Plugin::WLBLEval loadplugin Mail::SpamAssassin::Plugin::VBounce loadplugin Mail::SpamAssassin::Plugin::ImageInfoВ файле local.cf произведены изменения, содержит строки:
required_score 5.00 report_safe 0 ifplugin Mail::SpamAssassin::Plugin::URIDNSBL uridnsbl_skip_domain suse.de opensuse.org suse.com suse.org uridnsbl_skip_domain novell.com novell.org novell.ru novell.de novell.hu novell.co.uk endif # Mail::SpamAssassin::Plugin::URIDNSBLЗначение score теоретически игнорируется, так как оно перекрывается настройками amavisd-new, т.е. Оно равно тому, что указано в amavisd-new.
# Normalize charset to UTF-* normalize_charset 0 # BODY checks body RU_PORNO_KOI8R /(n|\xF0|\xD0)(O|o|0|\xEF|\xCF)(P|p|\xF2|\xD2)(H|\xEE|\xCE)(O|o|0|\xEF|\xCF)/s body RU_PORNO_WIN1251 /(n|\xCF|\xEF)(O|o|0|\xCE|\xEE)(P|p|\xD0|\xF0)(H|\xCD|\xED)(O|o|0|\xCE|\xEE)/s score RU_PORNO_KOI8R 4.0 score RU_PORNO_WIN1251 4.0 body RU_REKLAM_KOI8R /(P|p|\xF2|\xD2)(E|e|\xE5|\xC5)(K|k|\xEB|\xCB)(\xE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\)\/]?:?\x20?(\xFA|\xDA|\xFE|\xDE|\xEF|\xCF|\xF7|\xD7|\*|,|;|'|"|\x20|[0-9OoBliSsZz_-]){7,}/s score RU_ZVONITE_KOI8R 4.0 # URI checks uri LOCAL_SPAM_URI_1 /\w{7,}(\d|\w)*\.(chat|narod)\.ru/ score LOCAL_SPAM_URI_1 5.0 uri LOCAL_SPAM_URI_2 /www\.\w{7,}\.(it|org\.ar|com|nl)\/(readme|test)\.html/ score LOCAL_SPAM_URI_2 5.0 uri LOCAL_SPAM_URI_3 /lyubov\w*(\.\w+)?\.ru/ score LOCAL_SPAM_URI_3 7.0 uri LOCAL_SPAM_URI_4 /www\.(best|nice)?-?(xxx|cool|vldeo)-?(video|girl)\w?(xxx)?\.ru/ score LOCAL_SPAM_URI_4 9.0 uri LOCAL_SPAM_URI_5 /www\.porn\w*\.ru/ score LOCAL_SPAM_URI_5 9.0 uri LOCAL_SPAM_URI_6 /rb\.mail\.ru\/clbkjb\/(\d|\w|-)+\.ru\/\?win\/cgi-bin/ score LOCAL_SPAM_URI_6 9.0 uri LOCAL_SPAM_URI_7 /(rebeka|gerana)site\.com/ score LOCAL_SPAM_URI_7 9.0 # HEADER checks header LOCAL_SPAM_FROM_2 From =~ /\@.+\.(au|az|ca|com|co|edu|fl|gov|mn|nc|net|nj|nm|ok|oh|oz|org|pa|qc|sc|tx|ut|wa)\.(au|br|ca|dk|jp|nz|ph|us|uk|za)/i score LOCAL_SPAM_FROM_2 3.0 header LOCAL_SPAM_FROM_1 From =~ /\@.+\.(at|com|cz|de|es|edu|jp|kz|lv|ro|tv|ua)/i score LOCAL_SPAM_FROM_1 2.0 header LOCAL_SPAM_FROM_0 From =~ /\@.+\.(info|net|org)/i score LOCAL_SPAM_FROM_0 1.0 header LOCAL_NO_SPAM_FROM_1 From =~ /\@(blablabank|ch\.misex)\.com/i score LOCAL_NO_SPAM_FROM_1 -2.0 header __LOCAL_NO_SPAM_FROM From =~ /blabla\@blablacentre\.ru/i header __LOCAL_NO_SPAM_RECEIVED Received =~ /78\.221\.28\.187/ meta LOCAL_NO_SPAM (__LOCAL_NO_SPAM_FROM && __LOCAL_NO_SPAM_RECEIVED) score LOCAL_NO_SPAM -5.0 header LOCAL_SPAM_X_MAILER X-mailer =~ /(IPB|mPOP)? ?(vBulletin|MyBB|PHP|Web)( |-)?(Mail)?( .+)?/i score LOCAL_SPAM_X_MAILER 4.0 header __LOCAL_SPAM_X_MAILER_THE_BAT X-mailer =~ /The Bat.( .+)?/i header __LOCAL_NOSPAM_X_MAILER_THE_BAT From =~ /\@blablabank\.ru/i meta LOCAL_SPAM_X_MAILER_THE_BAT (__LOCAL_SPAM_X_MAILER_THE_BAT && !__LOCAL_NOSPAM_X_MAILER_THE_BAT) score LOCAL_SPAM_X_MAILER_THE_BAT 3.0Права на все файлы в папке /var/spool/amavis/.spamassassin: 600 vscan:vscan
LogSyslog yes LogFacility LOG_MAIL PidFile /var/lib/clamav/clamd.pid LocalSocket /var/lib/clamav/clamd-socket TCPSocket 3310 TCPAddr 127.0.0.1 User vscanздесь указан коннектор Clamav и другие необходимые параметры.
LogSyslog yes PidFile /var/lib/clamav/freshclam.pid DatabaseOwner vscan DatabaseMirror db.ru.clamav.net DatabaseMirror database.clamav.net HTTPProxyServer 10.1.1.1 HTTPProxyPort 80 NotifyClamd /etc/clamd.confздесь указаны источники обновления и другие необходимые параметры.
chkconfig -add clamd && chkconfig -add freshclam
use strict; $max_servers = 6; # num of pre-forked children (2..30 is common)(!same as maxproc value in master.cf for amavisfeed), -m $daemon_user = 'vscan'; # (no default; customary: vscan or amavis), -u $daemon_group = 'vscan'; # (no default; customary: vscan or amavis), -g $mydomain = 'mydomain.ru'; # a convenient default for other settings $MYHOME = '/var/spool/amavis'; # a convenient default for other settings, -H $TEMPBASE = "$MYHOME/tmp"; # working directory, needs to exist, -T $ENV{TMPDIR} = $TEMPBASE; # environment variable TMPDIR, used by SA, etc. $QUARANTINEDIR = '/var/spool/amavis/virusmails'; # -Q $log_level = 0; # verbosity 0..5, -d $log_recip_templ = undef; # disable by-recipient level-0 log entries $DO_SYSLOG = 0; # log via syslogd (preferred) $syslog_facility = 'mail'; # Syslog facility as a string $syslog_priority = 'debug'; # Syslog base (minimal) priority as a string, $LOGFILE = "/var/log/amavis.log"; $enable_db = 1; # enable use of BerkeleyDB/libdb (SNMP and nanny) $enable_global_cache = 1; # enable use of libdb-based cache if $enable_db=1 $nanny_details_level = 2; # nanny verbosity: 1: traditional, 2: detailed $enable_dkim_verification = 1; # enable DKIM signatures verification $enable_dkim_signing = 1; # load DKIM signing code, needs keys in dkim_key() @local_domains_maps = ( [".$mydomain"] ); # list of all local domains @mynetworks = qw( 127.0.0.0/8 10.1.1.0/24 ); $insert_received_line = 0; # Do not add Received (default - add: 1) $unix_socketname = "$MYHOME/amavisd.sock"; # amavisd-release or amavis-milter $inet_socket_port = [10024,10026]; # listen on multiple TCP ports $policy_bank{'MYNETS'} = { # mail originating from @mynetworks originating => 1, # is true in MYNETS by default, but let's make it explicit os_fingerprint_method => undef, # don't query p0f for internal clients notify_method => 'smtp:[127.0.0.1]:10025', forward_method => 'smtp:[127.0.0.1]:10025', # set to undef with milter! }; $interface_policy{'10026'} = 'EXTNETS'; $policy_bank{'EXTNETS'} = { notify_method => 'smtp:[127.0.0.1]:10027', forward_method => 'smtp:[127.0.0.1]:10027', insert_received_line => 1, }; $interface_policy{'SOCK'} = 'AM.PDP-SOCK'; # only applies with $unix_socketname $policy_bank{'AM.PDP-SOCK'} = { protocol => 'AM.PDP', auth_required_release => 0, # do not require secret_id for amavisd-release }; $sa_tag_level_deflt = 2.0; # add spam info headers if at, or above that level $sa_tag2_level_deflt = 4; # add 'spam detected' headers at that level $sa_kill_level_deflt = 5; # triggers spam evasive actions (e.g. blocks mail) $sa_dsn_cutoff_level = 10; # spam level beyond which a DSN is not sent $sa_crediblefrom_dsn_cutoff_level = 18; # likewise, but for a likely valid From $penpals_bonus_score = 8; # (no effect without a @storage_sql_dsn database) $penpals_threshold_high = $sa_kill_level_deflt; # don't waste time on hi spam $bounce_killer_score = 100; # spam score points to add for joe-jobbed bounces $sa_mail_body_size_limit = 400*1024; # don't waste time on SA if mail is larger $sa_local_tests_only = 0; # only tests which do not require internet access? $virus_admin = "admin\@$mydomain"; # notifications admin about virus. $mailfrom_notify_admin = "virusalert\@$mydomain"; # notifications admin from $mailfrom_notify_recip = "guard\@$mydomain"; # notifications recip from $mailfrom_notify_spamadmin = "spam.police\@$mydomain"; # notifications spamadmin from $mailfrom_to_quarantine = ''; # null return path; uses original sender if undef $hdrfrom_notify_sender = "\"Content-filter at $mydomain\" <postmaster\@$mydomain>"; @addr_extension_virus_maps = ('virus'); @addr_extension_banned_maps = ('banned'); @addr_extension_spam_maps = ('spam'); @addr_extension_bad_header_maps = ('badh'); $path = '/usr/local/sbin:/usr/local/bin:/usr/sbin:/sbin:/usr/bin:/bin'; $MAXLEVELS = 14; $MAXFILES = 1500; $MIN_EXPANSION_QUOTA = 100*1024; # bytes (default undef, not enforced) $MAX_EXPANSION_QUOTA = 300*1024*1024; # bytes (default undef, not enforced) $sa_spam_subject_tag = '***SPAM*** '; $defang_virus = 1; # MIME-wrap passed infected mail $defang_banned = 1; # MIME-wrap passed mail containing banned name $defang_by_ccat{+CC_BADH.",3"} = 1; # NUL or CR character in header $defang_by_ccat{+CC_BADH.",5"} = 1; # header line longer than 998 characters $defang_by_ccat{+CC_BADH.",6"} = 1; # header field syntax error $myhostname = 'mail.mydomain.ru'; # must be a fully-qualified domain name! $final_virus_destiny = D_DISCARD; $final_banned_destiny = D_DISCARD; $final_spam_destiny = D_DISCARD; $final_bad_header_destiny = D_PASS; $final_destiny_by_ccat{+CC_UNCHECKED} = D_DISCARD; $quarantine_method_by_ccat{+CC_UNCHECKED} = 'local:unchecked-%m'; $quarantine_to_maps_by_ccat{+CC_UNCHECKED} = sub { ca('banned_quarantine_to_maps') }; $admin_maps_by_ccat{+CC_UNCHECKED} = sub { ca('banned_admin_maps') }; $warnrecip_maps_by_ccat{+CC_UNCHECKED} = sub { ca('warnbannedrecip_maps') }; $warnsender_by_ccat{+CC_UNCHECKED} = sub { c('warnbannedsender') }; $warnvirussender = undef; $warnvirusrecip = 1; # (defaults to false (undef)) $warnbannedsender = 1; $warnbannedrecip = 1; # (defaults to false (undef)) @keep_decoded_original_maps = (new_RE( qr'^MAIL-UNDECIPHERABLE$', # recheck full mail if it contains undecipherables qr'^(ASCII(?! cpio)|text|uuencoded|xxencoded|binhex)'i, )); $banned_filename_re = new_RE( qr'^\.(exe-ms|dll)$', # banned file(1) types, rudimentary [ qr'^\.(rpm|cpio|tar)$' => 0 ], # allow any in Unix-type archives qr'.\.(pif|scr)$'i, # banned extensions - rudimentary qr'^application/x-msdownload$'i, # block these MIME types qr'^application/x-msdos-program$'i, qr'^application/hta$'i, qr'\.[^./]*[A-Za-z][^./]*\.\s*(exe|vbs|pif|scr|bat|cmd|com|cpl|dll)[.\s]*$'i, qr'.\.(exe|vbs|pif|scr|cpl)$'i, # banned extension - basic ); @score_sender_maps = ({ # a by-recipient hash lookup table, '.' => [ # the _first_ matching sender determines the score boost new_RE( # regexp-type lookup table, just happens to be all soft-blacklist [qr'^(bulkmail|offers|cheapbenefits|earnmoney|foryou)@'i => 5.0], [qr'^(greatcasino|investments|lose_weight_today|market\.alert)@'i=> 5.0], [qr'^(money2you|MyGreenCard|new\.tld\.registry|opt-out|opt-in)@'i=> 5.0], [qr'^(optin|saveonlsmoking2002k|specialoffer|specialoffers)@'i => 5.0], [qr'^(stockalert|stopsnoring|wantsome|workathome|yesitsfree)@'i => 5.0], [qr'^(your_friend|greatoffers)@'i => 5.0], [qr'^(inkjetplanet|marketopt|MakeMoney)\d*@'i => 5.0], ), { # a hash-type lookup table (associative array) 'nobody@cert.org' => -3.0, 'cert-advisory@us-cert.gov' => -3.0, 'owner-alert@iss.net' => -3.0, 'slashdot@slashdot.org' => -3.0, 'securityfocus.com' => -3.0, 'ntbugtraq@listserv.ntbugtraq.com' => -3.0, 'security-alerts@linuxsecurity.com' => -3.0, 'mailman-announce-admin@python.org' => -3.0, 'amavis-user-admin@lists.sourceforge.net'=> -3.0, 'amavis-user-bounces@lists.sourceforge.net' => -3.0, 'spamassassin.apache.org' => -3.0, 'notification-return@lists.sophos.com' => -3.0, 'owner-postfix-users@postfix.org' => -3.0, 'owner-postfix-announce@postfix.org' => -3.0, 'owner-sendmail-announce@lists.sendmail.org' => -3.0, 'sendmail-announce-request@lists.sendmail.org' => -3.0, 'donotreply@sendmail.org' => -3.0, 'ca+envelope@sendmail.org' => -3.0, 'noreply@freshmeat.net' => -3.0, 'owner-technews@postel.acm.org' => -3.0, 'ietf-123-owner@loki.ietf.org' => -3.0, 'cvs-commits-list-admin@gnome.org' => -3.0, 'rt-users-admin@lists.fsck.com' => -3.0, 'clp-request@comp.nus.edu.sg' => -3.0, 'surveys-errors@lists.nua.ie' => -3.0, 'emailnews@genomeweb.com' => -5.0, 'yahoo-dev-null@yahoo-inc.com' => -3.0, 'returns.groups.yahoo.com' => -3.0, 'clusternews@linuxnetworx.com' => -3.0, lc('lvs-users-admin@LinuxVirtualServer.org') => -3.0, lc('owner-textbreakingnews@CNNIMAIL12.CNN.COM') => -5.0, 'sender@example.net' => 3.0, '.example.net' => 1.0, }, ], # end of site-wide tables }); @decoders = ( ['mail', \&do_mime_decode], ['asc', \&do_ascii], ['uue', \&do_ascii], ['hqx', \&do_ascii], ['ync', \&do_ascii], ['F', \&do_uncompress, ['unfreeze','freeze -d','melt','fcat'] ], ['Z', \&do_uncompress, ['uncompress','gzip -d','zcat'] ], ['gz', \&do_uncompress, 'gzip -d'], ['gz', \&do_gunzip], ['bz2', \&do_uncompress, 'bzip2 -d'], ['lzo', \&do_uncompress, 'lzop -d'], ['rpm', \&do_uncompress, ['rpm2cpio.pl','rpm2cpio'] ], ['cpio', \&do_pax_cpio, ['pax','gcpio','cpio'] ], ['tar', \&do_pax_cpio, ['pax','gcpio','cpio'] ], ['deb', \&do_ar, 'ar'], ['zip', \&do_unzip], ['7z', \&do_7zip, ['7zr','7za','7z'] ], ['rar', \&do_unrar, ['rar','unrar'] ], ['arj', \&do_unarj, ['arj','unarj'] ], ['arc', \&do_arc, ['nomarch','arc'] ], ['zoo', \&do_zoo, ['zoo','unzoo'] ], ['lha', \&do_lha, 'lha'], ['cab', \&do_cabextract, 'cabextract'], ['tnef', \&do_tnef_ext, 'tnef'], ['tnef', \&do_tnef], ['exe', \&do_executable, ['rar','unrar'], 'lha', ['arj','unarj'] ], ); $first_infected_stops_scan = 1; # default is false, all scanners in a section @av_scanners = ( ['ClamAV-clamd', \&ask_daemon, ["CONTSCAN {}\n", "127.0.0.1:3310"], qr/\bOK$/, qr/\bFOUND$/, qr/^.*?: (?!Infected Archive)(.*) FOUND$/ ], ); @av_scanners_backup = ( ['ClamAV-clamscan', 'clamscan', "--stdout --no-summary -r --tempdir=$TEMPBASE {}", [0], qr/:.*\sFOUND$/, qr/^.*?: (?!Infected Archive)(.*) FOUND$/ ], ); 1; # insure a defined returnздесь указаны основные настройки фильтра amavisd-new: коннекторы Postfix и Clamav, настройки spamassassin, правила для типов файлов и др. Подробнее в коментариях и документации к фильтру.
chkconfig -add amavis
#SPAM по IP: /^81\.89\.21(0|4)\.(52|236)$/ 550 SPAM worm mail /^(220\.226\.205\.240|200\.72\.136\.116|116\.122\.36\.54|85\.17\.224\.165)$/ 550 SPAM IP banned #SPAM по имени домена: /^.+\.flytelecom\.net$/ 550 SPAM domain name #SPAM типовой по имени: /^[a-zA-Z0-9_]{1,}(-[0-9]{1,}){2,}(\.[a-zA-Z0-9_-]{1,}){1,}\.[a-zA-Z]{2,3}$/ 550 SPAM wx-x-x-x.w.w name /^[a-zA-Z0-9_]{1,}(\.[0-9]{1,}){2,}(\.[a-zA-Z0-9_-]{1,}){1,}\.[a-zA-Z]{2,3}$/ 550 SPAM wx.x.x.x.w.w name /^([a-zA-Z0-9_]{1,}[-\.]){1,}([0-9]{1,}[-\.]){2,}([a-zA-Z0-9_-]{1,}\.){1,}[a-zA-Z]{2,3}$/ 550 SPAM w.w-wx-x.x-x.w.w name /^([a-zA-Z_-]{0,}[0-9]{1,3}\.){3,}([a-zA-Z_-]{1,}\.){0,}[a-zA-Z]{2,3}$/ 550 SPAM wx.wx.wx.wx.w.w name #SPAM не типовой по имени: /^([0-9]{2,3}(\.[a-zA-Z0-9_-]{0,}|[a-zA-Z0-9_-]{1,})[0-9]{1,3}|[0-9]{10,})[a-zA-Z0-9_-]{0,}\.([a-zA-Z0-9_-]{1,}\.){1,}[a-z]{2,4}$/ 550 SPAM dyn0 name /^([a-z]{1}[0-9]{1,}|[a-z]{1}-web|acc-ppp|access|abn|bhe|cl|cm|cuscon|cust|dh|digsys|fxip|host|iCable|ip|mask|mav|nat-[a-z]{1}|net|node|nvs|OL|pc|ppp|public|ra|round|rt|sc|tdev|ts|unas|vfbb|vlan|wire)(_|-){0,1}[a-zA-Z_-]{0,}[0-9]{2,}[a-zA-Z0-9_-]{0,}\.([a-zA-Z0-9_-]{1,}\.){2,}[a-z]{2,4}$/ 550 SPAM dyn1 name /^([a-zA-Z0-9_-]{1,}\.){0,}(port[0-9]{1,}[a-zA-Z_-]{1,}|elbit|internet|public|home|[a-zA-Z]{1,}[0-9]{1,}|wimax){0,1}(_|-){0,1}(adsl|athedsl|broadband|cab|cable|chello|dhcp|dialup|dsl|dynamic|fix-addr|gprs|ip[0-9]{2,}|ipvpn|lan[0-9]{2,}|nat[0-9]{2,}|pool|port[0-9]{2,}|ppp[0-9]{2,}|pppoe|pppool|static|user|xdsl|sub[0-9]{2,})(_|-){0,1}(([0-9]{1,}|[a-zA-Z_-]{1,}[0-9]{1,}|dynamic)[a-zA-Z0-9_-]{0,}){0,1}\.([a-zA-Z0-9_-]{1,}\.){1,}[a-z]{2,4}$/ 550 SPAM dyn2 name /^(a{0,1}dsl|chello|cablelink|host|ip|ool|ppp|smsdpe|user){0,1}[a-zA-Z0-9_-]{5,}(\.neoplus){0,1}\.(acn|[asv]{0,1}dsl|(b(red|and){0,1}){1,2}|c(able|oner|ust)|[dp](hcp|yn[0-9]{0,}|ip[0-9]{0,1})|internetdsl|kln|p(ila|ppoe-dynamic|ool)|s(tatic|tk|atfilm)|telefonia|u(ser|pc-e)|virtua)(\.(aloo|mls|pacific|pei|spo\.virtua|veloxzone)){0,1}\.(a(liant|stral|licedsl)|b(luecom|ell)|c(ybercity|om|hello)|ermsnet|forthnet|hol|intercable|m(indspring|vb)|net|optonline|sk(anova|y)|t(-dialin|-ipconnect|-online|pnet)|vectranet|waw|3s)\.[a-z]{2,4}$/ 550 SPAM dyn3 nameздесь указаны регулярные выражения для фильтрации писем. Проверка smtpd_client_restrictions и smtpd_helo_restrictions используется в master.cf для писем отправленных из внешней сети.
postmap client_checksФайл header_checks содержит строки:
/^Received: from localhost \(localhost \[127\.0\.0\.1\]\)(\s+)by mail\.mydomain\.ru \(Postfix\)/ IGNORE /^Received: from sexch\.MYDOMAIN\.local \(sexch\.mydomain\.local \[10\.1\.1\.2\]\)(.*)$/ REPLACE Received: from sexch.MYDOMAIN.local (Sexch)${1} /^Received: from .* by sexch\.MYDOMAIN\.local \(\[10\.1\.1\.2\]\) with Microsoft Exchange Server HTTP-DAV/ IGNORE /^Received: from .* by 10\.1\.1\.2/ IGNOREиспользуется для удаления и замены определенных заголовков из письма. Проверка header_body_checks используется в файле master.cf для писем отправленных из внутренней сети.
mydomain.ru REJECT <> PREPEND X-From-MD: yesздесь указан домен отправителя, письма которого будут отвергнуты. Используется в smtpd_sender_restrictions для запрета приема почты от лжеотправителей из интернета.
postmap sender_checksФайл main.cf содержит строки:
queue_directory = /var/spool/postfix command_directory = /usr/sbin daemon_directory = /usr/lib/postfix data_directory = /var/lib/postfix mail_owner = postfix myhostname = mail.mydomain.ru mydomain = mydomain.ru myorigin = $mydomain inet_interfaces = localhost mydestination = local_recipient_maps = local_transport = error:local mail delivery is disabled virtual_alias_maps = hash:/etc/postfix/virtual unknown_local_recipient_reject_code = 550 mynetworks = 127.0.0.0/8, 10.1.1.2/32 relay_domains = $mydomain parent_domain_matches_subdomains = debug_peer_list,mynetworks,smtpd_access_maps relay_recipient_maps = ldap:/etc/postfix/ldap_U.cf, ldap:/etc/postfix/ldap_OU2.cf, ldap:/etc/postfix/ldap_OU1.cf, ldap:/etc/postfix/ldap_PF.cf masquerade_domains = $mydomain transport_maps = hash:/etc/postfix/transport alias_maps = hash:/etc/aliases header_checks = regexp:/etc/postfix/header_checks fast_flush_domains = smtpd_banner = $myhostname ESMTP debug_peer_level = 2 debugger_command = PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin ddd $daemon_directory/$process_name $process_id & sleep 5 sendmail_path = /usr/sbin/sendmail newaliases_path = /usr/bin/newaliases mailq_path = /usr/bin/mailq setgid_group = maildrop html_directory = /usr/share/doc/packages/postfix-doc/html manpage_directory = /usr/share/man sample_directory = /usr/share/doc/packages/postfix-doc/samples readme_directory = /usr/share/doc/packages/postfix-doc/README_FILES inet_protocols = all biff = no strict_rfc821_envelopes = yesздесь указаны глобальные параметры почтового шлюза.
smtp inet n - n - - smtpd pickup fifo n - n 60 1 pickup cleanup unix n - n - 0 cleanup qmgr fifo n - n 300 1 qmgr tlsmgr unix - - n 1000? 1 tlsmgr rewrite unix - - n - - trivial-rewrite bounce unix - - n - 0 bounce defer unix - - n - 0 bounce trace unix - - n - 0 bounce verify unix - - n - 1 verify flush unix n - n 1000? 0 flush proxymap unix - - n - - proxymap smtp unix - - n - - smtp relay unix - - n - - smtp -o fallback_relay= showq unix n - n - - showq error unix - - n - - error discard unix - - n - - discard virtual unix - n n - - virtual lmtp unix - - n - - lmtp anvil unix - - n - 1 anvil scache unix - - n - 1 scache maildrop unix - n n - - pipe flags=DRhu user=vmail argv=/usr/local/bin/maildrop -d ${recipient} cyrus unix - n n - - pipe user=cyrus argv=/usr/lib/cyrus/bin/deliver -e -r ${sender} -m ${extension} ${user} uucp unix - n n - - pipe flags=Fqhu user=uucp argv=uux -r -n -z -a$sender - $nexthop!rmail ($recipient) ifmail unix - n n - - pipe flags=F user=ftn argv=/usr/lib/ifmail/ifmail -r $nexthop ($recipient) bsmtp unix - n n - - pipe flags=Fq. user=foo argv=/usr/local/sbin/bsmtp -f $sender $nexthop $recipient procmail unix - n n - - pipe flags=R user=nobody argv=/usr/bin/procmail -t -m /etc/procmailrc ${sender} ${recipient} retry unix - - n - - error proxywrite unix - - n - 1 proxymap amavisfeed unix - - n - 6 smtp -o smtp_data_done_timeout=1200 -o smtp_send_xforward_command=yes -o disable_dns_lookups=yes -o max_use=20 111.111.111.210:25 inet n - n - - smtpd -o content_filter=amavisfeed:[127.0.0.1]:10026 -o mynetworks= -o receive_override_options=no_address_mappings,no_header_body_checks -o smtpd_client_restrictions=check_client_access,regexp:/etc/postfix/client_checks,reject_unknown_client_hostname -o disable_vrfy_command=yes -o smtpd_helo_required=yes -o smtpd_helo_restrictions=reject_invalid_helo_hostname,reject_non_fqdn_helo_hostname,check_helo_access,regexp:/etc/postfix/client_checks -o smtpd_sender_restrictions=reject_non_fqdn_sender,reject_unknown_sender_domain,check_sender_access,hash:/etc/postfix/sender_checks 10.1.1.1:25 inet n - n - - smtpd -o content_filter=amavisfeed:[127.0.0.1]:10024 -o receive_override_options=no_address_mappings,no_header_body_checks -o disable_vrfy_command=yes 127.0.0.1:10025 inet n - n - - smtpd -o content_filter= -o smtpd_delay_reject=no -o smtpd_client_restrictions=permit_mynetworks,reject -o smtpd_helo_restrictions= -o smtpd_sender_restrictions= -o smtpd_recipient_restrictions=permit_mynetworks,reject -o smtpd_data_restrictions=reject_unauth_pipelining -o smtpd_end_of_data_restrictions= -o smtpd_restriction_classes= -o mynetworks=127.0.0.0/8 -o smtpd_error_sleep_time=0 -o smtpd_soft_error_limit=1001 -o smtpd_hard_error_limit=1000 -o smtpd_client_connection_count_limit=0 -o smtpd_client_connection_rate_limit=0 -o receive_override_options=no_unknown_recipient_checks,no_milters -o local_header_rewrite_clients= 127.0.0.1:10027 inet n - n - - smtpd -o content_filter= -o smtpd_delay_reject=no -o smtpd_client_restrictions=permit_mynetworks,reject -o smtpd_helo_restrictions= -o smtpd_sender_restrictions= -o smtpd_recipient_restrictions=permit_mynetworks,reject -o smtpd_data_restrictions=reject_unauth_pipelining -o smtpd_end_of_data_restrictions= -o smtpd_restriction_classes= -o mynetworks=127.0.0.0/8 -o smtpd_error_sleep_time=0 -o smtpd_soft_error_limit=1001 -o smtpd_hard_error_limit=1000 -o smtpd_client_connection_count_limit=0 -o smtpd_client_connection_rate_limit=0 -o receive_override_options=no_header_body_checks,no_unknown_recipient_checks,no_milters -o local_header_rewrite_clients=здесь добавлен фильтр amavisfeed и коннекторы Postfix, а также запрещена локальная доставка писем. На коннекторе 127.0.0.1:10025 разрешена проверка header_body_checks, на остальных — запрещена.
mydomain.ru smtp:[10.1.1.2]здесь указан транспорт для писем адресованных в домен mydomain.ru — перенаправить на внутренний сервер и всех остальных писем — перенаправить на внешний сервер.
postmap transportФайл virtual содержит строки:
postmaster admin@mydomain.ru abuse admin@mydomain.ru root admin@mydomain.ruздесь указаны правила перенаправления писем для конкретных получателей, так как локальная доставка запрещена, письма для root, postmaster и др. локальных пользователей перенаправлять на конкретный адрес.
postmap virtualПроверка в LDAP:
server_host = 10.1.1.20 search_base = ou=OU1, dc=MYDOMAIN, dc=local query_filter = (&(proxyAddresses=smtp:%s)(|(objectCategory=person)(objectCategory=group))(|(objectClass=user)(objectClass=group)(objectClass=contact))) domain = mydomain.ru result_attribute = mail bind_dn = postldap@mydomain.local bind_pw = p05t1dAp debuglevel = 0/etc/postfix/ldap_OU2.cf:
server_host = 10.1.1.20 search_base = ou=OU2, dc=MYDOMAIN, dc=local query_filter = (&(proxyAddresses=smtp:%s)(|(objectCategory=person)(objectCategory=group))(|(objectClass=user)(objectClass=group)(objectClass=contact))) domain = mydomain.ru result_attribute = mail bind_dn = postldap@mydomain.local bind_pw = p05t1dAp debuglevel = 0/etc/postfix/ldap_PF.cf:
server_host = 10.1.1.20 search_base = cn=Microsoft Exchange System Objects, dc=MYDOMAIN, dc=local query_filter = (&(proxyAddresses=smtp:%s)(objectClass=publicFolder)) domain = mydomain.ru result_attribute = mail bind_dn = postldap@mydomain.local bind_pw = p05t1dAp debuglevel = 0/etc/postfix/ldap_U.cf:
server_host = 10.1.1.20 search_base = cn=Users, dc=MYDOMAIN, dc=local query_filter = (&(proxyAddresses=smtp:%s)(|(objectCategory=person)(objectCategory=group))(|(objectClass=user)(objectClass=group)(objectClass=contact))) domain = mydomain.ru result_attribute = mail bind_dn = postldap@mydomain.local bind_pw = p05t1dAp debuglevel = 0Включить сервис можно либо через Yast, либо так:
chkconfig -add postfix
0 0 * * * /usr/local/bin/amavisdclear.shЧто позволяет проводить очистку каждый день в 00:00. Права на amavisdclear.sh: 755, владелец: root:root.
#!/bin/bash # #Copyright 2009 Konstantin Nadezhdin <w.homenki.ru> # #This program is free software: you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation, either version 3 of the License, or #(at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. # #You should have received a copy of the GNU General Public License #along with this program. If not, see <http://www.gnu.org/licenses/>. rm -rf /var/spool/amavis/virusmails_old mkdir -m 0700 /var/spool/amavis/virusmails_old mv -f /var/spool/amavis/virusmails/* /var/spool/amavis/virusmails_old/ chown -R vscan:vscan /var/spool/amavis/virusmails_old > /dev/null 2>&1 chmod -R 0640 /var/spool/amavis/virusmails_old > /dev/null 2>&1 chmod 0700 /var/spool/amavis/virusmails_old > /dev/null 2>&1
A virus was found: Trojan.Goldun-278 Banned name: multipart/mixed | application/zip,.zip,user-EA49943X-activities.zip | .exe,.exe-ms,user-EA49943X-activities.exe Scanner detecting a virus: ClamAV-clamd Content type: Virus Internal reference code for the message is 26041-15/oEZKA8wP8OMn First upstream SMTP client IP address: [64.207.33.186] mail.bsg-co.com According to a 'Received:' trace, the message originated at: [64.207.33.186], mail.bsg-co.com (mail.bsg-co.com [64.207.33.186]) Return-Path: <marcelo.medeiros@abril.com.br> User-Agent: Thunderbird 2.0.0.12 (Windows/20080213) Message-ID: <33575.riothamus@lance> Subject: Your internet access is going to get suspended The message has been quarantined as: virus-oEZKA8wP8OMn Notification to sender will not be mailed. The message WAS NOT relayed to: <info@mydomain.ru>: 250 2.7.0 Ok, discarded, id=26041-15 - VIRUS: Trojan.Goldun-278 Virus scanner output: p004: Trojan.Goldun-278 FOUNDТаким образом, для разблокировки этого письма и доставки его адресату, достаточно выполнить:
amavisd-release virus-oEZKA8wP8OMnПисьма блокированные вчерашним днем находятся в /var/spool/amavis/virusmails_old/ , чтобы разблокировать такое письмо, его сначала требуется скопировать в /var/spool/amavis/virusmails/ и затем выполнить команду разблокировки. Более старые блокированные письма удаляются безвозвратно!
Описание и пример скрипта подробно изложены здесь: http://nk-rec.ru/samples/lprod/lssalearn/index.html.