Главная страница | Добавить в избранное    
   

 

» Статьи » Почтовый сервер для себя! Настройка postfix dovecot 2 spamassasin clamav roundcube postifxadmin

   
main1
pix
 

Почтовый сервер для себя! Настройка postfix dovecot 2 spamassasin clamav roundcube postifxadmin

Статьи  
pix pix pix
Для чего нужна почта, сам себе решает, и каждый сам решает, где он её будет создавать. Я покажу как можно создать почту у себя и как можно настоить себе сервер.
apt-get install postfix postfix-mysql dovecot-mysql dovecot-sieve dovecot-pop3d dovecot-imapd amavisd-new libclass-dbi-mysql-perl spamassassin clamav clamav-daemon postgrey php-apc nginx mysql-server mysql-client php5-mysql php5-curl php5-gd php5-intl php-pear php5-imagick php5-imap php5-mcrypt php5-memcache  php5-pspell php5-recode php5-snmp php5-sqlite php5-tidy php5-xmlrpc php5-xsl php5-fpm php5-mysql php5-sqlite php5-common php5-gd php-xml-parser php5-intl php5-mcrypt php5-curl php5-json ntp php5 curl postfix-mysql postfix-pcre postfix postfix-policyd-spf-python p7zip-full php-apc nginx mysql-server mysql-client php5-mysql php5-curl php5-gd php5-intl php-pear php5-imagick php5-imap php5-mcrypt php5-memcache php5-pspell php5-recode php5-snmp php5-sqlite php5-tidy php5-xmlrpc php5-xsl php5-fpm php5-mysql php5-sqlite php5-common php5-gd php-xml-parser php5-intl php5-mcrypt php5-curl php5-json ntp php5 curl dovecot-managesieved dovecot-antispam wwwconfig-common dbconfig-common

 на вопрос типа настройки postfix выбираем интернет-сайт почтовое имя для домена test.lan В /etc/hostname должно быть имя сервера без доменной части. А в /etc/mailname наоборот - fqdn имя mail.test.lan

Создадим пользователя от имени которого будет работать postfix и dovecot.

 

groupadd -g 5000 vmail
useradd -g vmail -u 5000 vmail -d /vmail -m

/vmail это домашняя папка одноименного пользователя её можно указать любую, хоть на другом физическом ресурсе.

мы делаем хороший сервер, он будет поддерживать TLS\SSL, создадим папку для хранения сертификатов для подключения к серверу

mkdir /etc/postfix/ssl
cd /etc/postfix/ssl

Создадим файл настрок сертификата nano openssl.cnf

[req]
default_bits = 4096                     # Длинна ключа в битах.
default_keyfile = key.pem               # Имя файла, в который будет записан закрытый ключ.
encrypt_key = no                        # Нам не нужно шифровать закрытый ключ паролем.
default_md = sha512                     # Алгоритм хеша.
x509_extensions = v3_req                # Включаем расширение V3.
prompt = no                             # Не нужно запрашивать данные у пользователя, мы всё пропишем здесь.
distinguished_name = req_distinguished_name         # Имя секции с данными (может быть любым).
 
[req_distinguished_name]
C = RU                               # Двухбуквенный код страны
L = Moscow                           # Город
O = Roga-I-Kopita LTD                # Название организации
CN = mail.test.lan                   # Имя домена
emailAddress = postmaster@test.lan   # Адрес электронной почты
# Можно ещё указать следующие поля:
# ST (State - штат, название провинции и т.п.)
# OU (Organizational Unit - название подразделения)
 
[v3_req]

Создадим сертификаты сроком на 100 лет ))

openssl req -new -x509 -days 36500 -config openssl.cnf -out cert.pem -outform PEM -keyout key.pem -keyform PEM

перейдем к настройке самого postfix'а
cd /etc/postfix
файл с настройками это main.cf у меня он принял вот такой вот вид

# See /usr/share/postfix/main.cf.dist for a commented, more complete version
 
# Debian specific:  Specifying a file name will cause the first
# line of that file to be used as the name.  The Debian default
# is /etc/mailname.
#myorigin = /etc/mailname
 
smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU)
biff = no
 
# appending .domain is the MUA's job.
append_dot_mydomain = no
 
# Uncomment the next line to generate "delayed mail" warnings
#delay_warning_time = 4h
 
readme_directory = no
 
# TLS parameters   #
smtp_tls_security_level = may
smtpd_tls_security_level = may
smtpd_tls_received_header = yes
smtpd_tls_session_cache_timeout = 3600s
smtpd_tls_cert_file = /etc/postfix/ssl/cert.pem
smtpd_tls_key_file = /etc/postfix/ssl/key.pem
smtpd_use_tls = yes
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
tls_random_source = dev:/dev/urandom
 
 
# GENEREAL
 
myhostname = mail.example.com
#alias_maps = hash:/etc/aliases
#alias_database = hash:/etc/aliases
myorigin = /etc/mailname
mydestination = $myhostname, localhost.$mydomain, localhost
relayhost =
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mailbox_command = procmail -a "$EXTENSION"
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
max_use = 500
disable_vrfy_command = yes
soft_bounce = no
 
# SASL            #
smtpd_sasl_auth_enable = yes
broken_sasl_auth_clients = yes
smtpd_sasl_authenticated_header = yes
smtpd_sasl_tls_security_options = $smtpd_sasl_security_options
smtpd_sasl_security_options = noanonymous
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
smtpd_helo_required = yes
smtpd_delay_reject = yes
smtpd_discard_ehlo_keywords = etrn, silent-discard
smtpd_recipient_limit = 10
smtpd_sender_login_maps = mysql:/etc/postfix/mysql-users.cf
 
 
# VIRTUAL
virtual_mailbox_domains = mysql:/etc/postfix/mysql-virtual-mailbox-domains.cf
virtual_mailbox_maps = mysql:/etc/postfix/mysql-virtual-mailbox-maps.cf
virtual_alias_maps = mysql:/etc/postfix/mysql-virtual-alias-maps.cf,mysql:/etc/postfix/mysql-email2email.cf,mysql:/etc/postfix/mysql-virtual-alias-domain-maps.cf
virtual_uid_maps = static:5000
virtual_gid_maps = static:5000
virtual_transport = dovecot
dovecot_destination_recipient_limit = 1
 
 
# LIMITS
message_size_limit = 51200000
smtpd_client_connection_count_limit = 20
smtpd_client_connection_rate_limit = 30
 
 
# QUEUE
maximal_queue_lifetime = 1d
bounce_queue_lifetime = 1d
 
 
# RULES
smtpd_client_restrictions =
        permit_mynetworks,
        check_client_access hash:/etc/postfix/sender_access,
        permit_sasl_authenticated,
        reject_unknown_reverse_client_hostname,
        warn_if_reject reject_unknown_client
 
smtpd_helo_restrictions =
        permit_mynetworks,
        check_helo_access hash:/etc/postfix/sender_access,
        reject_invalid_helo_hostname,
        reject_unknown_helo_hostname,
        reject_non_fqdn_helo_hostname
 
smtpd_sender_restrictions =
        permit_mynetworks,
        check_sender_access hash:/etc/postfix/sender_access,
        permit_sasl_authenticated,
        reject_non_fqdn_sender,
        reject_unverified_sender,
        reject_unauthenticated_sender_login_mismatch,
        reject_unknown_sender_domain
 
smtpd_recipient_restrictions =
        permit_mynetworks,
        check_recipient_access hash:/etc/postfix/recipient_access,
        permit_sasl_authenticated,
        reject_non_fqdn_recipient,
        reject_unknown_recipient_domain,
        reject_multi_recipient_bounce,
        reject_unauth_destination,
        reject_unlisted_recipient,
        check_policy_service inet:127.0.0.1:10023
 
smtpd_data_restrictions =
        reject_unauth_pipelining
 
 
# AMAVIS
content_filter = smtp-amavis:[127.0.0.1]:10024

в папке постфикса создадим файлы только замените HOST на 127.0.0.1 а остальные параметры на свои

mysql-email2email.cf

user = USER
password = PASSWORD
hosts = HOST
dbname = DB
query = select username from mailbox where username = '%s'

mysql-users.cf

user = USER
password = PASSWORD
hosts = HOST
dbname = DB
query = select username from mailbox where username='%s' AND active = '1'

mysql-virtual-alias-domain-maps.cf

user = USER
password = PASSWORD
hosts = HOST
dbname = DB
query = select goto from alias,alias_domain where alias_domain.alias_domain = '%d' and alias.address = concat('%u', '@', alias_domain.target_domain) and alias.active = '1'

mysql-virtual-alias-maps.cf

user = USER
password = PASSWORD
hosts = HOST
dbname = DB
query = select goto from alias where address='%s'

mysql-virtual-mailbox-domains.cf

user = USER
password = PASSWORD
hosts = HOST
dbname = DB
query = select domain from domain where domain='%s'

mysql-virtual-mailbox-maps.cf

user = USER
password = PASSWORD
hosts = HOST
dbname = DB
query = select username from mailbox where username='%s' AND active = '1'
chgrp postfix /etc/postfix/mysql-*.cf
chmod u=rw,g=r,o= /etc/postfix/mysql-*.cf
 
touch /etc/postfix/sender_access
touch /etc/postfix/recipient_access
postmap /etc/postfix/sender_access
postmap /etc/postfix/recipient_access

так как у нас будет и спамассисн и проверка на вирусы нам надо пережедать транспорт, сделаем master.cf таким

#
# Postfix master process configuration file.  For details on the format
# of the file, see the master(5) manual page (command: "man 5 master" or
#
# Do not forget to execute "postfix reload" after editing this file.
#
# ==========================================================================
# service type  private unpriv  chroot  wakeup  maxproc command + args
#               (yes)   (yes)   (yes)   (never) (100)
# ==========================================================================
smtp      inet  n       -       -       -       -       smtpd
submission inet n       -       n       -       -       smtpd
   -o syslog_name=postfix/submission
   -o smtpd_tls_wrappermode=no
   -o smtpd_tls_security_level=encrypt
   -o smtpd_sasl_auth_enable=yes
   -o smtpd_recipient_restrictions=permit_mynetworks,permit_sasl_authenticated,reject
   -o milter_macro_daemon_name=ORIGINATING
#smtp      inet  n       -       -       -       1       postscreen
#smtpd     pass  -       -       -       -       -       smtpd
#dnsblog   unix  -       -       -       -       0       dnsblog
#tlsproxy  unix  -       -       -       -       0       tlsproxy
#submission inet n       -       -       -       -       smtpd
#  -o syslog_name=postfix/submission
#  -o smtpd_tls_security_level=encrypt
#  -o smtpd_sasl_auth_enable=yes
#  -o smtpd_reject_unlisted_recipient=no
#  -o smtpd_client_restrictions=$mua_client_restrictions
#  -o smtpd_helo_restrictions=$mua_helo_restrictions
#  -o smtpd_sender_restrictions=$mua_sender_restrictions
#  -o smtpd_recipient_restrictions=
#  -o smtpd_relay_restrictions=permit_sasl_authenticated,reject
#  -o milter_macro_daemon_name=ORIGINATING
#smtps     inet  n       -       -       -       -       smtpd
#  -o syslog_name=postfix/smtps
#  -o smtpd_tls_wrappermode=yes
#  -o smtpd_sasl_auth_enable=yes
#  -o smtpd_reject_unlisted_recipient=no
#  -o smtpd_client_restrictions=$mua_client_restrictions
#  -o smtpd_helo_restrictions=$mua_helo_restrictions
#  -o smtpd_sender_restrictions=$mua_sender_restrictions
#  -o smtpd_recipient_restrictions=
#  -o smtpd_relay_restrictions=permit_sasl_authenticated,reject
#  -o milter_macro_daemon_name=ORIGINATING
#628       inet  n       -       -       -       -       qmqpd
pickup    unix  n       -       -       60      1       pickup
cleanup   unix  n       -       -       -       0       cleanup
qmgr      unix  n       -       n       300     1       qmgr
#qmgr     unix  n       -       n       300     1       oqmgr
tlsmgr    unix  -       -       -       1000?   1       tlsmgr
rewrite   unix  -       -       -       -       -       trivial-rewrite
bounce    unix  -       -       -       -       0       bounce
defer     unix  -       -       -       -       0       bounce
trace     unix  -       -       -       -       0       bounce
verify    unix  -       -       -       -       1       verify
flush     unix  n       -       -       1000?   0       flush
proxymap  unix  -       -       n       -       -       proxymap
proxywrite unix -       -       n       -       1       proxymap
smtp      unix  -       -       -       -       -       smtp
relay     unix  -       -       -       -       -       smtp
#       -o smtp_helo_timeout=5 -o smtp_connect_timeout=5
showq     unix  n       -       -       -       -       showq
error     unix  -       -       -       -       -       error
retry     unix  -       -       -       -       -       error
discard   unix  -       -       -       -       -       discard
local     unix  -       n       n       -       -       local
virtual   unix  -       n       n       -       -       virtual
lmtp      unix  -       -       -       -       -       lmtp
anvil     unix  -       -       -       -       1       anvil
scache    unix  -       -       -       -       1       scache
#
# ====================================================================
# Interfaces to non-Postfix software. Be sure to examine the manual
# pages of the non-Postfix software to find out what options it wants.
#
# Many of the following services use the Postfix pipe(8) delivery
# agent.  See the pipe(8) man page for information about ${recipient}
# and other message envelope options.
# ====================================================================
#
# maildrop. See the Postfix MAILDROP_README file for details.
# Also specify in main.cf: maildrop_destination_recipient_limit=1
#
maildrop  unix  -       n       n       -       -       pipe
  flags=DRhu user=vmail argv=/usr/bin/maildrop -d ${recipient}
#
# ====================================================================
#
# Recent Cyrus versions can use the existing "lmtp" master.cf entry.
#
# Specify in cyrus.conf:
#   lmtp    cmd="lmtpd -a" listen="localhost:lmtp" proto=tcp4
#
# Specify in main.cf one or more of the following:
#  mailbox_transport = lmtp:inet:localhost
#  virtual_transport = lmtp:inet:localhost
#
# ====================================================================
#
# Cyrus 2.1.5 (Amos Gouaux)
# Also specify in main.cf: cyrus_destination_recipient_limit=1
#
#cyrus     unix  -       n       n       -       -       pipe
#  user=cyrus argv=/cyrus/bin/deliver -e -r ${sender} -m ${extension} ${user}
#
# ====================================================================
# Old example of delivery via Cyrus.
#
#old-cyrus unix  -       n       n       -       -       pipe
#  flags=R user=cyrus argv=/cyrus/bin/deliver -e -m ${extension} ${user}
#
# ====================================================================
#
# See the Postfix UUCP_README file for configuration details.
#
uucp      unix  -       n       n       -       -       pipe
  flags=Fqhu user=uucp argv=uux -r -n -z -a$sender - $nexthop!rmail ($recipient)
#
# Other external delivery methods.
#
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=bsmtp argv=/usr/lib/bsmtp/bsmtp -t$nexthop -f$sender $recipient
scalemail-backend unix  -       n       n       -       2       pipe
  flags=R user=scalemail argv=/usr/lib/scalemail/bin/scalemail-store ${nexthop} ${user} ${extension}
mailman   unix  -       n       n       -       -       pipe
  flags=FR user=list argv=/usr/lib/mailman/bin/postfix-to-mailman.py
  ${nexthop} ${user}
dovecot   unix  -   n   n   -   -   pipe
     flags=DRhu user=vmail:vmail argv=/usr/lib/dovecot/deliver -d ${recipient}
smtp-amavis unix -     -       n       -       2       smtp
       -o smtp_data_done_timeout=1200
       -o smtp_send_xforward_command=yes
       -o disable_dns_lookups=yes
       -o max_use=20
 
127.0.0.1:10025 inet   n       -       -       -       - smtpd
       -o content_filter=
       -o local_recipient_maps=
       -o relay_recipient_maps=
       -o smtpd_restriction_classes=
       -o smtpd_delay_reject=no
       -o mynetworks=127.0.0.0/8
       -o smtpd_client_restrictions=permit_mynetworks,permit_sasl_authenticated,reject
       -o smtpd_helo_restrictions=
       -o smtpd_sender_restrictions=
       -o smtpd_recipient_restrictions=permit_mynetworks,permit_sasl_authenticated,reject
       -o smtpd_data_restrictions=reject_unauth_pipelining
       -o smtpd_end_of_data_restrictions=
       -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_address_mappings
       -o local_header_rewrite_clients=

Приступим к редактированию конфигов Dovecot
cd /etc/dovecot/conf.d

10-auth.conf

disable_plaintext_auth = no
auth_realms = example.com
auth_mechanisms = plain login
#!include auth-system.conf.ext
!include auth-sql.conf.ext

example.com замените на свой домен, который прописан в /etc/mailname

10-logging.conf

log_path = syslog
syslog_facility = mail

10-mail.conf

 

mail_location = maildir:/vmail/%d/%n/Maildir
mail_uid = 5000
mail_gid = 5000
mail_plugins = quota
 
namespace inbox {
  type = private
  separator = .
  prefix =
  inbox = yes
}

 10-master.conf

 

service imap-login {
  inet_listener imap {
    port = 143
  }
  inet_listener imaps {
    port = 993
    ssl = yes
  }
}
service pop3-login {
  inet_listener pop3 {
    port = 110
  }
  inet_listener pop3s {
    port = 995
    ssl = yes
  }
}
service auth {
  unix_listener auth-userdb {
    #mode = 0666
    #user =
    #group =
  }
 
  # Postfix smtp-auth
  unix_listener /var/spool/postfix/private/auth {
    mode = 0666
    user = vmail
  }
}
service dict {
  unix_listener dict {
    mode = 0600
    user = vmail
  }
}

10-ssl.conf

ssl = yes
ssl_cert = /etc/postfix/ssl/cert.pem
ssl_key = /etc/postfix/ssl/key.pem

15-lda.conf

 

postmaster_address = postmaster@test.lan
quota_full_tempfail = yes
lda_mailbox_autocreate = yes
lda_mailbox_autosubscribe = yes
mail_plugins = $mail_plugins autocreate sieve
15-mailboxes.conf
 
  # These mailboxes are widely used and could perhaps be created automatically:
  mailbox Drafts {
    auto = subscribe
    special_use = \Drafts
  }
  mailbox Junk {
    auto = subscribe
    special_use = \Junk
  }
  mailbox Trash {
    auto = subscribe
    special_use = \Trash
  }
 
  # For \Sent mailboxes there are two widely used names. We'll mark both of
  # them as \Sent. User typically deletes one of them if duplicates are created.
  mailbox Sent {
    auto = subscribe
    special_use = \Sent
  }

20-imap.conf

mail_plugins = $mail_plugins autocreate imap_quota

90-quota.conf

quota_rule = *:storage=1G
quota_warning = storage=95%% quota-warning 95 %u
quota_warning2 = storage=80%% quota-warning 80 %u
service quota-warning {
  executable = script /usr/local/bin/quota-warning.sh
  user = dovecot
  unix_listener quota-warning {
    user = vmail
  }
}
plugin {
  #quota = dirsize:User quota
  #quota = maildir:User quota
  quota = dict:User quota::proxy::quota
  #quota = fs:User quota
}

90-sieve.conf

sieve_default = /vmail/globalsieverc
sieve_before = /vmail/globalsieverc

/etc/dovecot/dovecot-sql.conf.ext

driver = mysql
connect = host=HOST dbname=DB user=USER password=PASSWORD
default_pass_scheme = MD5-CRYPT
password_query = SELECT username as user, password FROM mailbox WHERE username = '%u'
user_query = SELECT '/vmail/%d/%n' AS home, 5000 AS uid, 5000 AS gid, CONCAT('*:bytes=', CAST(quota AS CHAR)) AS quota_rule FROM mailbox WHERE username = '%u' AND active = '1'

dovecot-dict-sql.conf.ext

connect = host=HOST dbname=DB user=USER password=PASSWORD

и не забываем, что вместо HOST мы пишем 127.0.0.1 и так далее. Ниже надо заменить table = quota на table = quota2. и полностью закоментировать 

#map {
#  pattern = shared/expire/$user/$mailbox
#  table = expires
#  value_field = expire_stamp
#
#  fields {
#    username = $user
#    mailbox = $mailbox
#  }
#}

/etc/dovecot/dovecot.conf

quota = mysql:/etc/dovecot/dovecot-dict-sql.conf.ext

Создадим скрипт оповещения превышении квоты

nano /usr/local/bin/quota-warning.s

#!/bin/sh
PERCENT=$1
FROM="postmaster@test.lan"
USER=$2
cat << EOF | /usr/sbin/sendmail -f $FROM $USER
From: postmaster@test.lan
Subject: quota warning
 
Your mailbox is now $PERCENT% full.
EOF

Сделаем его выполняемым

chmod +x /usr/local/bin/quota-warning.sh && chown dovecot: /usr/local/bin/quota-warning.sh

Настройка антиспам

Раскоментируем строчки в /etc/amavis/conf.d/15-content_filter_mode

@bypass_virus_checks_maps = (
   \%bypass_virus_checks, \@bypass_virus_checks_acl, \$bypass_virus_checks_re);
 
@bypass_spam_checks_maps = (
   \%bypass_spam_checks, \@bypass_spam_checks_acl, \$bypass_spam_checks_re);

 Я не считаю, что письма помеченные как спам надо не доставлять пользователю, так как может произойти ошибочная метка, настроим и это, а потом заставим такие письма самим отправляться в папке "СПАМ"

в /etc/amavis/conf.d/20-debian_defaults

 

$final_spam_destiny       = D_PASS;

Для всех отправителей от нашего домена для нас самих сделаем уровень спама пониже

{ # a hash-type lookup table (associative array)
        '.test.lan'  => -20.0,

Почта у нас будет проверяться только кламавом, поэтому сохраним оригинальный файл настроек и создадим смой только для clamav

mv /etc/amavis/conf.d/15-av_scanners /etc/amavis/conf.d/15-av_scanners.default
touch /etc/amavis/conf.d/15-av_scanners

вот его содержимое:

use strict;
 
##
## AV Scanners (Debian version)
##
 
@av_scanners = (
 
# ['Sophie',
#   \&ask_daemon, ["{}/\n", '/var/run/sophie'],
#   qr/(?x)^ 0+ ( : | [\000\r\n]* $)/m,  qr/(?x)^ 1 ( : | [\000\r\n]* $)/m,
#   qr/(?x)^ [-+]? \d+ : (.*?) [\000\r\n]* $/m ],
 
# ### http://www.csupomona.edu/~henson/www/projects/SAVI-Perl/
# ['Sophos SAVI', \&sophos_savi ],
 
 ['ClamAV-clamd',
   \&ask_daemon, ["CONTSCAN {}\n", "/var/run/clamav/clamd.ctl"],
   qr/\bOK$/m, qr/\bFOUND$/m,
   qr/^.*?: (?!Infected Archive)(.*) FOUND$/m ],
# NOTE: run clamd under the same user as amavisd, or run it under its own
#   uid such as clamav, add user clamav to the amavis group, and then add
#   AllowSupplementaryGroups to clamd.conf;
# NOTE: match socket name (LocalSocket) in clamav.conf to the socket name in
#   this entry; when running chrooted one may prefer socket "$MYHOME/clamd".
 
);
 
@av_scanners_backup = (
 
  ### http://www.clamav.net/   - backs up clamd or Mail::ClamAV
  ['ClamAV-clamscan', 'clamscan',
    "--stdout --no-summary -r --tempdir=$TEMPBASE {}",
    [0], qr/:.*\sFOUND$/m, qr/^.*?: (?!Infected Archive)(.*) FOUND$/m ],
 
);
 
 
1;  # ensure a defined return

там же 50-user 

перед строками

#------------ Do not modify anything below this line -------------
1;  # ensure a defined return

напишем:

@lookup_sql_dsn = (
        ['DBI:mysql:database=DB;host=HOST;port=3306',
        'USER',
        'PASSWORD']);
 
$sql_select_policy = 'SELECT domain FROM domain WHERE CONCAT("@",domain) IN (%k)';

не забываем править его переменные под себя

Настроим права clamav

в /etc/clamav/clamd.conf

 

 

User amavis
LocalSocketGroup amavis

и в /etc/clamav/freshclam.conf

DatabaseOwner amavis

добавлим clamav в группу amavis и наоборот, затем меняем владельца папки /var/log/clamav/

usermod -a -G amavis clamav
usermod -a -G clamav amavis
chown -R amavis:amavis /var/log/clamav

в файле /etc/default/spamassassin укажем запускаться спамассасину как демону

ENABLED=1

что бы письма с флагом "SPAM" попадали сразу в папку спам напишем правило /vmail/globalsieverc

require ["fileinto"];
# Move spam to spam folder
if header :contains "X-Spam-Flag" ["YES"] {
  fileinto "Junk";
  stop;
}

и выполним chown vmail: /vmail/globalsieverc

 все настройки спамассасина лежат тут /etc/spamassassin/local.cf

 приведем его к такому виду

rewrite_header Subject *****SPAM*****
report_safe 0
required_score 4.0
use_bayes 1
bayes_auto_learn 0
bayes_ignore_header X-Bogosity
bayes_ignore_header X-Spam-Flag
bayes_ignore_header X-Spam-Status
  
score DEAR_SOMETHING 5
score T_DKIM_INVALID 1
score HTML_MESSAGE 0.5
score MISSING_MID 1
score FORGET_MUA_OUTLOOK 2.199 2.199 0.963 1.116
score FH_DATE_PAST_20XX 0.0
score DOS_OE_TO_MX_IMAGE 0.0
score DOS_OE_TO_MX 0.0
score DOT_OUTLOOK_TO_MX 0.0
score TO_NO_BRKTS_DIRECT 0.0
score HELO_LOCALHOST 0.0
score FSL_RU_URL 0.0
score FROM_MISSP_EH_MATCH 1.0
score TVD_RCVD_SINGLE 1.0
score TO_IN_SUBJ 1.0
 
#
# TUNING
#
score SUBJ_FULL_OF_8BITS 0.00
score HTML_COMMENT_8BITS 0.01
score HEADER_8BITS 0.00
score TO_NO_USER 0.01
score FORGED_MUA_OUTLOOK 0.5
score X_AUTH_WARNING 0.01
score SUBJ_HAS_UNIQ_ID 9.99
score HTTP_USERNAME_USED 9.99
score FORGED_YAHOO_RCVD 9.99
score FORGED_JUNO_RCVD 16
score UNWANTED_LANGUAGE_BODY 1.02
score MLM 5.55
score RCVD_NUMERIC_HELO 4.95
 
#
# WHITE/BLACK LISTS
#
whitelist_from root@localhost
whitelist_from *@test.lan
blacklist_from *@moyabivshaya.com
auto_whitelist_path /etc/mail/spamassassin/auto-whitelist
auto_whitelist_file_mode 0666
 
endif # Mail::SpamAssassin::Plugin::Shortcircuit

С основной частью законченно, теперь настроим roundcube и postfixadmin, для их работы у нас уже стоит nginx и php5-fpm, мы только будем настраивать виртуальные хосты и пулы от fpm

С сайта http://sourceforge.net/projects/postfixadmin/ скачиваем последнюю версию

cd
wget http://sourceforge.net/projects/postfixadmin/files/postfixadmin/postfixadmin-2.93/postfixadmin_2.93-1_all.deb/download -O postfixadmin_2.93-1_all.deb
dpkg -i postfixadmin_2.93-1_all.deb

На запрос настройки базы отвечаем NO

Настройка виртуального хоста для nginx

server {
       listen 80;
       server_name mailadmin.test.lan;
       root /usr/share/postfixadmin;
        access_log  /var/log/nginx/mailadmin.access.log;
       index index.php index.html;
       location = /favicon.ico {
                log_not_found off;
                access_log off;
       }
       location = /robots.txt {
                allow all;
                log_not_found off;
                access_log off;
       }
       # Deny all attempts to access hidden files such as .htaccess, .htpasswd, .DS_Store (Mac).
       location ~ /\. {
                deny all;
                access_log off;
                log_not_found off;
       }
       client_max_body_size 100M;
       location ~ \.(png|gif|ico|swf|jpe?g|js|css|ttf|svg|eot|woff)$ {
                if (!-e $request_filename){
                    rewrite ^/(.*?)\/(.*)$ /$2 last;
                }
                expires 1w;
       }
       location ~ store_closed.html$ {
                if (!-e $request_filename){
                    rewrite ^/(.*?)\/(.*)$ /$2 last;
                }
       }
       location / {
                index index.php;
                try_files $uri $uri/ /index.php?sef_rewrite=1&$args;
       }
       location ~ \.php$ {
                try_files $uri =404;
                include /etc/nginx/fastcgi_params;
                fastcgi_pass unix:/var/run/postfixadmin-php5-fpm.sock;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                fastcgi_intercept_errors on;
                fastcgi_temp_file_write_size 10m;
                fastcgi_busy_buffers_size    512k;
                fastcgi_buffer_size          512k;
                fastcgi_buffers           16 512k;
                fastcgi_read_timeout 1200;
       }
}

Настройка пула fpm

[postfixadmin]
user = www-data
group = www-data
listen = /var/run/postfixadmin-php5-fpm.sock
listen.owner = www-data
listen.group = www-data
 
pm = dynamic
pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3

Все свои настройки postfixadmin хранит в /etc/postfixadmin


<?php
##
## database access settings in php format
## automatically generated from /etc/dbconfig-common/postfixadmin.conf
## by /usr/sbin/dbconfig-generate-include
## Sun, 25 Oct 2015 02:33:57 +0300
##
## by default this file is managed via ucf, so you shouldn't have to
## worry about manual changes being silently discarded.  *however*,
## you'll probably also want to edit the configuration file mentioned
## above too.
##
$dbuser='root';
$dbpass='123123';
$basepath='';
$dbname='mailsrv';
$dbserver='127.0.0.1';
$dbport='3306';
$dbtype='mysql';

Заходим броузером на адресс http://mailadmin.test.lan/setup.php который создаст базу mailsrv и задаем паоль и адрес администратора, после чего уже можно будет создатб домен и почтовые ящики.

 Royndcube я советую ставить из изсходников, а не качать сборки, так как у нас будет больше возможностей установить нам то что нужно. Идем на сайт https://roundcube.net/download/ и качаем комплит версию

Создаем виртуальный хост и пул fpm

nginx

server {
       listen 80;
       server_name mail.test.lan;
       root /var/www/mail;
        access_log  /var/log/nginx/mail.access.log;
       index index.php index.html;
       location = /favicon.ico {
                log_not_found off;
                access_log off;
       }
       location = /robots.txt {
                allow all;
                log_not_found off;
                access_log off;
       }
       # Deny all attempts to access hidden files such as .htaccess, .htpasswd, .DS_Store (Mac).
       location ~ /\. {
                deny all;
                access_log off;
                log_not_found off;
       }
       client_max_body_size 100M;
       location ~ \.(png|gif|ico|swf|jpe?g|js|css|ttf|svg|eot|woff)$ {
                if (!-e $request_filename){
                    rewrite ^/(.*?)\/(.*)$ /$2 last;
                }
                expires 1w;
       }
       location ~ store_closed.html$ {
                if (!-e $request_filename){
                    rewrite ^/(.*?)\/(.*)$ /$2 last;
                }
       }
       location / {
                index index.php;
                try_files $uri $uri/ /index.php?sef_rewrite=1&$args;
       }
       location ~ \.php$ {
                try_files $uri =404;
                include /etc/nginx/fastcgi_params;
                fastcgi_pass unix:/var/run/mail-php5-fpm.sock;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                fastcgi_intercept_errors on;
                fastcgi_temp_file_write_size 10m;
                fastcgi_busy_buffers_size    512k;
                fastcgi_buffer_size          512k;
                fastcgi_buffers           16 512k;
                fastcgi_read_timeout 1200;
       }
}

пул для php5-fpm

[mail]
user = www-data
group = www-data
listen = /var/run/mail-php5-fpm.sock
listen.owner = www-data
listen.group = www-data
 
pm = dynamic
pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3

распаковываем архив roundcube в /var/www/mail даем ему правильные права chown www-dаta: /var/www/mail

и идем по адресу http://mail.test.lan/install/ а там и так все понятно )




Уважаемый посетитель, Вы зашли на сайт как незарегистрированный пользователь. Мы рекомендуем Вам зарегистрироваться либо войти на сайт под своим именем.
 
Автор: hellevil | 19-07-2017, 09:43 | Просмотров: 1 993
 
pix
  Новости по теме    
pix pix pix
  • Как снять/изменить пароль root'a в MySQL
  • MySQL Error Codes
  • Cacti - снимаем статистику устройств по SNMP
  • Репликация MySQL
  • Munin - статистика сервера
  •  
     
     
    pix
     
    pix
    search
    navi
    poll
    calendar
    «    Март 2024    »
    ПнВтСрЧтПтСбВс
     123
    45678910
    11121314151617
    18192021222324
    25262728293031
    main4
    pix pix pix

    2007 © www.DesktopBSD.ru
    Все права сохранены