Pull to refresh

Настройка exim+postgresql+dbmail+spamassassin в Gentoo

Reading time 10 min
Views 10K
В сети множество статей о настройке exim + mysql + чтонибудь еще, и всего парочка об exim+postgresql да и то с битыми ссылками, поэтому я решил поделится своим опытом и собрать в одном месте инструкции по установке и настройке exim+postgresql+dbmail+spamassassin.

Устанавливаем софт


Добавляем в USE-флаги postgres exiscan exiscan-acl затем устанавливаем
emerge exim virtual/postgresql-server dbmail spamassassin



Настройка



Postgresql


Конфигурируем postgresql для первого запуска
emerge --config postgresql


Запускаем
/etc/init.d/postgresql start



Создаем пользователя для работы с почтовой базой
createuser -U postgres -P dbmail


Создаем базу
createdb -U postgres --owner dbmail dbmail


Вместе с dbmail идут заготовки базы, распаковываем и заливаем
bunzip2 /usr/share/doc/dbmail-2.2.10/create_tables.pgsql.bz2
psql -U dbmail -d dbmail < /usr/share/doc/dbmail-2.2.10/create_tables.pgsql

В этом дампе нету таблицы для работы с виртуальными доменами, создадим ее
CREATE TYPE dtype AS ENUM (
 'LOCAL',
 'VIRTUAL',
 'RELAY'
);

ALTER TYPE public.dtype OWNER TO dbmail;

SET default_with_oids = true;

CREATE TABLE dbmail_domains (
 uid integer NOT NULL,
 domain character varying(128) NOT NULL,
 type dtype NOT NULL
);

INSERT INTO dbmail_domains (uid, domain, type) VALUES (1, 'example.com', 'LOCAL');

Все база готова.

Exim


Cразу приведу рабочий exim.conf
#!/bin/sh
######################################################################
# Runtime configuration file for Exim #
######################################################################
#######################################################################
# MAIN CONFIGURATION SETTINGS #
######################################################################

primary_hostname = example.com
domainlist local_domains = ${lookup pgsql{SELECT domain FROM dbmail_domains \
WHERE domain='${domain}' AND \
(type='LOCAL' OR type='VIRTUAL')}}
domainlist relay_to_domains = ${lookup pgsql{SELECT domain FROM dbmail_domains \
WHERE domain='${domain}' AND type='RELAY'}}
hostlist relay_from_hosts = 127.0.0.1: localhost
auth_advertise_hosts = *
daemon_smtp_ports = 25
log_selector = \
+all_parents \
+lost_incoming_connection \
+received_sender \
+received_recipients \
+smtp_confirmation \
+smtp_syntax_error \
+smtp_protocol_error \
-queue_run
acl_smtp_rcpt = acl_check_rcpt
acl_smtp_mime = acl_check_mime
acl_smtp_data = acl_check_content
qualify_domain = example.com
allow_domain_literals = false
exim_user = mail
exim_group = mail
never_users = root
host_lookup = *
#rfc1413_hosts = *
rfc1413_query_timeout = 0s
ignore_bounce_errors_after = 30m
timeout_frozen_after = 3d
freeze_tell = postmaster

#av_scanner = clamd:/var/run/clamav/clamd.ctl #если нужен антивирус раскоментировать и незабыть его поставить
spamd_address = 127.0.0.1 783

message_size_limit = 10M
smtp_accept_max = 1000
smtp_accept_max_per_connection = 150
smtp_accept_max_per_host = 30
split_spool_directory = true
remote_max_parallel = 15
smtp_banner = "Welcome on our mail server!\n\
This system does not accept Unsolicited \
Commercial Email\nand will blacklist \
offenders via our spam processor.\nHave a \
nice day!\n\n${primary_hostname} ESMTP"

hide pgsql_servers = localhost/dbmail/dbmail/PasSWorD

######################################################################
# ACL CONFIGURATION #
# Specifies access control lists for incoming SMTP mail #
######################################################################
begin acl

acl_check_rcpt:

warn
set acl_m0 = 0s
warn
hosts = !+relay_from_hosts:!213.243.111.115/32
set acl_m0 = 30s
warn
condition = ${if and {\
{match{$sender_host_name}\
{\N^[-a-z]*\d{0,3}[-a-z]*\.?[-a-z]*\d{0,3}[-a-z]*\.\w+$\N}} \
{!eq{$acl_c0}{outblaze_helo}} \
}{yes}{no}}
set acl_m0 = 1s

warn
condition = ${if and {\
{match{$sender_helo_name}{\N^\w*\.\w{3}$\N}} \
{eq{$acl_c1}{}} \
}{yes}{no}}
set acl_m0 = 99s

warn
condition = ${if and {\
{!match{$sender_host_name}{\N.+.outblaze.com$\N}} \
{eq{$acl_c0}{outblaze_helo}} \
}{yes}{no}}
set acl_m0 = 99s

warn
condition = ${if and {\
{!match{$sender_host_name}{\N.+.outblaze.com$\N}} \
{eq{$acl_c2}{outblaze_domain}} \
}{yes}{no}}
set acl_m0 = 99s

warn
condition = ${if or {\
{eq{$sender_address}{}} \
{eq{$acl_m1}{0s}} \
} {yes}{no}}
set acl_m0 = 0s

warn
logwrite = Delay $acl_m0 for $sender_host_name \
[$sender_host_address] with HELO=$sender_helo_name. \
Mail from $sender_address to $local_part@$domain.
set acl_m1 = 0s
delay = $acl_m0

accept hosts = :

deny domains = +local_domains
local_parts = ^[.] : ^.*[@%!/|]

deny domains = !+local_domains
local_parts = ^[./|] : ^.*[@%!] : ^.*/\\.\\./

accept local_parts = postmaster
domains = +local_domains

require verify = sender

deny message = HELO/EHLO required by SMTP RFC
condition = ${if eq{$sender_helo_name}{}{yes}{no}}

deny message = Go Away! You are spammer.
condition = ${if match{$sender_host_name} \
{bezeqint\\.net|net\\.il|dialup|dsl|pool|peer|dhcp} \
{yes}{no}}

deny message = message from \
$sender_host_address rejected - see njabl.org
log_message = found in $dnslist_domain
dnslists = dnsbl.njabl.org

deny message = rejected because $sender_host_address \
is in a black list at $dnslist_domain\n$dnslist_text
log_message = found in $dnslist_domain
dnslists = dialups.mail-abuse.org
deny message = rejected because $sender_host_address \
is in a black list at $dnslist_domain\n$dnslist_text
log_message = found in $dnslist_domain
dnslists = list.dsbl.org
deny message = Spam blocked see: \
www.spamcop.net/w3m?action=checkblock&ip=$sender_host_address
log_message = found in $dnslist_domain
dnslists = bl.spamcop.net
deny message = rejected, $sender_host_address \
Open Proxy, see: $dnslist_domain\n$dnslist_text
log_message = found in $dnslist_domain
dnslists = dnsbl.void.ru

accept domains = +local_domains
endpass
message = unknown user
verify = recipient

accept domains = +relay_to_domains
endpass
message = unrouteable address
verify = recipient

accept hosts = +relay_from_hosts
accept authenticated = *
deny message = relay not permitted

acl_check_mime:

warn decode = default

deny message = Blacklisted file extension detected ($mime_filename)
condition = ${if match \
{${lc:$mime_filename}} \
{\N(\.exe|\.pif|\.bat|\.scr|\.lnk|\.com|\.vbs|\.cpl)$\N} \
{1}{0}}

deny message = Sorry, noone speaks chinese here
condition = ${if eq{$mime_charset}{gb2312}{1}{0}}

accept

acl_check_content:
# deny message = Virus found ($malware_name)
# malware = *

warn message = X-Spam-Score: $spam_score ($spam_bar)
hosts = !+relay_from_hosts
spam = spamd:true

warn message = X-Spam-Report: $spam_report
hosts = !+relay_from_hosts
spam = spamd:true

warn message = Subject: ***SPAM*** $h_Subject:
hosts = !+relay_from_hosts
spam = spamd

deny message = This message scored $spam_score spam points.
spam = spamd:true
hosts = !+relay_from_hosts
condition = ${if >{$spam_score_int}{120}{1}{0}}

accept

######################################################################
# ROUTERS CONFIGURATION #
# Specifies how addresses are handled #
######################################################################
# THE ORDER IN WHICH THE ROUTERS ARE DEFINED IS IMPORTANT! #
# An address is passed to each router in turn until it is accepted. #
######################################################################

begin routers

dnslookup:
driver = dnslookup
domains = ! +local_domains
transport = remote_smtp
ignore_target_hosts = 0.0.0.0 : 127.0.0.0/8
no_more

dbmailuser:
driver = accept
condition = ${lookup pgsql{SELECT alias_idnr FROM \
dbmail_aliases WHERE \
alias='${quote_pgsql:$local_part@$domain}' OR \
alias='${quote_pgsql:@$domain}'}{yes}{no}}
transport = dbmail_delivery

######################################################################
# TRANSPORTS CONFIGURATION #
######################################################################
# ORDER DOES NOT MATTER #
# Only one appropriate transport is called for each delivery. #
######################################################################

begin transports

remote_smtp:
driver = smtp

dbmail_delivery:
driver = pipe
check_string =
command = /usr/sbin/dbmail-smtp -d ${pipe_addresses}
group = mail
message_prefix = ""
message_suffix = ""
path="/bin:/sbin:/usr/bin:/usr/sbin"
# Имя программы
address_pipe:
driver = pipe
return_output

address_reply:
driver = autoreply

######################################################################
# RETRY CONFIGURATION #
######################################################################

begin retry

* quota
* * F,2h,15m; G,16h,1h,1.5; F,4d,6h

######################################################################
# REWRITE CONFIGURATION #
######################################################################

begin rewrite

######################################################################
# AUTHENTICATION CONFIGURATION #
######################################################################

begin authenticators

auth_plain:
driver = plaintext
public_name = PLAIN
server_condition = ${lookup pgsql{SELECT user_idnr FROM \
dbmail_users WHERE userid = \
'${quote_pgsql:$1}' AND passwd = \
'${quote_pgsql:$2}'}{yes}{no}}
server_prompts = :
server_set_id = $2

# Вроде по этому оутглюк, а по предыдущему нетскейп.
auth_login:
driver = plaintext
public_name = LOGIN
server_condition = ${lookup pgsql{SELECT user_idnr FROM \
dbmail_users WHERE userid = \
'${quote_pgsql:$1}' AND passwd = \
'${quote_pgsql:$2}'}{yes}{no}}
server_prompts = Username:: : Password::
server_set_id = $1

# А так авторизуется "Летучая Мышь" - TheBat!
auth_cram_md5:
driver = cram_md5
public_name = CRAM-MD5
server_secret = ${lookup pgsql{SELECT passwd FROM \
dbmail_users WHERE userid \
= '${quote_pgsql:$1}'}{$value}fail}
server_set_id = $1
# End of Exim configuration file
###ps спасибо lissyara, некоторые части его конфигов используются здесь



DBMail


dbmail.conf почти все по умолчанию кроме настроек соединения с бд
# (c) 2000-2006 IC&S, The Netherlands
#
# Configuration file for DBMAIL

[DBMAIL]
#
# Database settings
#

#
# Supported drivers are mysql, pgsql, sqlite.
#
driver =pgsql

#
# Supported drivers are sql, ldap.
#
authdriver =sql

#
# Host for database, set to localhost if database is on
# the same host as dbmail and you want to use a local
# socket for connecting.
#
host =localhost

#
# If you want to use TCP/IP for connecting to the database,
# and have the database running on a non-standard port.
#
sqlport =5432

#
# When using a local socket connection to the database, fill
# in the path to the socket here (e.g. /var/run/mysql.sock).
#
sqlsocket =

#
# Database username.
#
user =dbmail

#
# Database password.
#
pass =PasWoRd

#
# Database name.
#
db =dbmail

#
# Table prefix. Defaults to "dbmail_" if not specified.
#
table_prefix =dbmail_

#
# encoding must match the database/table encoding.
# i.e. latin1, utf8
encoding = utf8

#
# messages with unknown encoding will be assumed to have
# default_msg_encoding
# i.e. iso8859-1, utf8
default_msg_encoding = utf8

#
# Postmaster's email address for use in bounce messages.
#
#postmaster = DBMAIL-MAILER

#
# Sendmail executable for forwards, replies, notifies, vacations.
# You may use pipes (|) in this command, for example:
# dos2unix|/usr/sbin/sendmail works well with Qmail.
# You may use quotes (") for executables with unusual names.
#
sendmail = /usr/sbin/sendmail

#
#
# The following items can be overridden in the service-specific sections.
#
#

#
# Trace level to send to syslog. Default is 2 (messages, errors, fatals).
#
TRACE_SYSLOG = 3

#
# Trace level to send to stderr. Default is 0 (fatals).
#
TRACE_STDERR = 1

#
# Root privs are used to open a port, then privs
# are dropped down to the user/group specified here.
#
EFFECTIVE_USER = dbmail
EFFECTIVE_GROUP = dbmail

#
# The IP addresses the services will bind to.
# Use * for all local interfaces.
# Use 127.0.0.1 for localhost only.
# Separate multiple entries with spaces ( ) or commas (,).
#
BINDIP = *

#
# Default number of child processes to start.
#
NCHILDREN = 2

#
# Maximum number of child processes allowed.
#
MAXCHILDREN = 10

#
# Unused children to always have availale.
#
MINSPARECHILDREN = 2

#
# Maximum unused children allowed to be active.
#
MAXSPARECHILDREN = 4

#
# Child process is restarted after handling this many connections.
#
MAXCONNECTS = 10000

#
# Child process will restart after this many connection errors.
#
MAX_ERRORS = 500

#
# Idle time allowed before a connection is shut off.
#
TIMEOUT = 300

#
# Idle time allowed before a connection is shut off if you have not logged in yet.
#
login_timeout = 60

#
# If yes, resolves IP addresses to DNS names when logging.
#
RESOLVE_IP = no

#
# logfile for stdout messages
#
logfile = /var/log/dbmail.log

#
# logfile for stderr messages
#
errorlog = /var/log/dbmail.err

#
# directory for storing PID files
#
pid_directory = /var/run

#
# directory for storing the daemon statefiles
#
state_directory = /var/run

#
# directory for locating libraries (normally has a sane default compiled-in)
#
#library_directory = /usr/lib/dbmail

[SMTP]
# In fact, there isn't anything here by default.

[LMTP]
#
# Port to bind to.
#
PORT = 24

[POP]
#
# Port to bind to.
#
PORT = 110

#
# If yes, allows SMTP access from the host IP connecting by POP3.
# This requires addition configuration of your MTA
#
POP_BEFORE_SMTP = no

[IMAP]

#
# Port to bind to.
#
PORT = 143

#
# IMAP prefers a longer timeout than other services.
#
TIMEOUT = 4000

#
# If yes, allows SMTP access from the host IP connecting by IMAP.
# This requires addition configuration of your MTA
#
IMAP_BEFORE_SMTP = no

#
# during IDLE, how many seconds between checking the mailbox
# status (default: 30)
#
# idle_timeout = 30

#
# Provide a CAPABILITY to override the default
#
# capability = IMAP4 IMAP4rev1 AUTH=LOGIN ACL NAMESPACE CHILDREN SORT QUOTA THREAD=ORDEREDSUBJECT UNSELECT IDLE

[SIEVE]
#
# Port to bind to.
#
PORT = 2000

[LDAP]
PORT = 389
VERSION = 3
HOSTNAME = ldap
BASE_DN = ou=People,dc=mydomain,dc=com

#
# If your LDAP library supports ldap_initialize(), then you can use the
# alternative LDAP server DSN like following.
#
# URI = ldap://127.0.0.1:389
# URI = ldapi://%2fvar%2frun%2fopenldap%2fldapi/

#
# Leave blank for anonymous bind.
# example: cn=admin,dc=mydomain,dc=com
#
BIND_DN =

#
# Leave blank for anonymous bind.
#
BIND_PW =
SCOPE = SubTree
USER_OBJECTCLASS = top,account,dbmailUser
FORW_OBJECTCLASS = top,account,dbmailForwardingAddress
CN_STRING = uid
FIELD_PASSWD = userPassword
FIELD_UID = uid
FIELD_NID = uidNumber
MIN_NID = 10000
MAX_NID = 15000
FIELD_CID = gidNumber
MIN_CID = 10000
MAX_CID = 15000
FIELD_MAIL = mail
FIELD_QUOTA = mailQuota
FIELD_FWDTARGET = mailForwardingAddress

[DELIVERY]
#
# Run Sieve scripts as messages are delivered.
#
SIEVE = yes

#
# Use 'user+mailbox@domain' format to deliver to a mailbox.
#
SUBADDRESS = yes

#
# Turn on/off the Sieve Vacation extension.
#
SIEVE_VACATION = yes

#
# Turn on/off the Sieve Notify extension
#
SIEVE_NOTIFY = yes

#
# Turn on/off additional Sieve debugging.
#
SIEVE_DEBUG = no

#
# Use the auto_notify table to send email notifications.
#
AUTO_NOTIFY = no

#
# Use the auto_reply table to send away messages.
#
AUTO_REPLY = no
#
# Defaults to "NEW MAIL NOTIFICATION"
#
#AUTO_NOTIFY_SUBJECT =

#
# Defaults to POSTMASTER from the DBMAIL section.
#
#AUTO_NOTIFY_SENDER =

#
# If you set this to 'yes' dbmail will check for duplicate
# messages in the relevant mailbox during delivery using
# the Message-ID header
#
suppress_duplicates = no

# end of configuration file




Spamassassin


Может работать и сразу, но если ругается в логе на отсутствие домашней директории, то надо создать пользователя с домашней директорией к примеру /etc/spamasassin, и запускать его с этим пользователем, ибо по умолчанию он стартует под nobody

local.cf
rewrite_header Subject ***SPAM***
report_safe 1
trusted_networks 192.168/16 127/8
# lock_method flock
required_score 5.0
use_bayes 1
bayes_auto_learn 1
# bayes_ignore_header X-Bogosity
# bayes_ignore_header X-Spam-Flag
# bayes_ignore_header X-Spam-Status
auto_whitelist_path /etc/mail/spamassassin/auto_whitelist
bayes_path /etc/mail/spamassassin/bayes
bayes_file_mode 0666
bayes_min_ham_num 1
bayes_min_spam_num 1
auto_learn_threshold_nonspam -2
auto_learn_threshold_spam 5
bayes_learn_to_journal 1
skip_rbl_checks 0

ok_languages ru en
ok_locales ru en



Уфф вроде все .. теперь это можно запускать
/etc/init.d/exim start
/etc/init.d/spamd start
#по вкусу если нужен pop3 да и для проверки конфигурации
/etc/init.d/dbmail-pop3d



Если нету ругани в логах, и оно все нормально стартовало то остается прописать в автозагрузку
rc-update add postgresql default
rc-update add exim default
rc-update add spamd default
rc-update add dbmail-pop3d default



и добавить либо пользователя которому будут отсылатся письма либо алиас, если читать хочется с внешнего ящика
dbmail-users -a admin@example.com -s admin@example.com -p plaintext -w 123123



вот и все, остается протестировать по вкусу и в бой

Tags:
Hubs:
+7
Comments 1
Comments Comments 1

Articles