Почтовый сервер на Debian Jessie

Компоненты почтового сервера
Dovecot – IMAP и POP3 сервер, MDA (mail delivery agent)
Postfix – MTA (mail transfer agent)
Postixadmin – управление почтовыми ящиками

Генерируем самоподписные сертификаты для SSL/TLS
openssl req -new -x509 -days 36500 -nodes -out /etc/dovecot/dovecot.pem -keyout /etc/dovecot/private/dovecot.pem
chmod 400 /etc/dovecot/dovecot.pem
chmod 400 /etc/dovecot/private/dovecot.pem

Добавляем репозиторий
vim /etc/apt/sources.list:

deb http://ftp.ua.debian.org/debian/ jessie main

aptitude update
aptitude install dovecot-core dovecot-common dovecot-imapd dovecot-mysql dovecot-pop3d dovecot-sieve dovecot-lmtpd postfix-mysql postfixadmin openssl iptables-persistent bind9
aptitude remove exim4-base exim4-config exim4-daemon-light

Настраиваем DNS сервер

Настраиваем dovecot
vim /etc/dovecot/dovecot.conf:

auth_debug = yes #можно выключить после отладки
auth_verbose = yes    #можно выключить после отладки
mail_debug = yes      #можно выключить после отладки
disable_plaintext_auth = no
auth_mechanisms = plain login cram-md5
protocols = imap pop3 lmtp
passdb {
  args = /etc/dovecot/dovecot-sql.conf
  driver = sql
}
userdb {
  driver = sql
  args = /etc/dovecot/dovecot-sql.conf
}
service auth {
unix_listener auth-master {
user = vmail
group = mail
mode = 0660
}
#dict {
  #quota = mysql:/etc/dovecot/dovecot-dict-sql.conf.ext
  #expire = sqlite:/etc/dovecot/dovecot-dict-sql.conf.ext
#}

vim /etc/dovecot/conf.d/10-auth.conf:

#auth_mechanisms = plain

vim /etc/dovecot/conf.d/15-lda.conf:

postmaster_address = admin@example.com
hostname = mail.example.com
lda_mailbox_autocreate = yes
lda_mailbox_autosubscribe = yes
protocol lda {
  mail_plugins = $mail_plugins
}

vim /etc/dovecot/conf.d/auth-sql.conf.ext:

passdb {
args = /etc/dovecot/dovecot-sql.conf
driver = sql
}
userdb {
args = /etc/dovecot/dovecot-sql.conf
driver = sql
}

vim /etc/dovecot/conf.d/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 = 0600
    user = vmail
    group = mail
  }
  unix_listener /var/spool/postfix/private/auth {
    mode = 0666
    user = postfix
    group = postfix
  }
}

vim /etc/dovecot/conf.d/10-mail.conf:

mail_location = maildir:/var/mail/%d/%u
mail_uid = vmail
mail_gid = mail
first_valid_uid = 2000
last_valid_uid = 2000
first_valid_gid = 8
last_valid_gid = 8

vim /etc/dovecot/conf.d/10-ssl.conf:

ssl = yes
ssl_cert = </etc/dovecot/dovecot.pem
ssl_key = </etc/dovecot/private/dovecot.pem
ssl_cipher_list = ALL:!LOW:!SSLv2:!EXP:!aNULL

vim /etc/dovecot/conf.d/20-imap.conf:

protocol imap {
  mail_plugins = $mail_plugins quota imap_quota
}

vim /etc/dovecot/conf.d/15-mailboxes.conf:

namespace inbox {
  mailbox Drafts {
    auto = subscribe
    special_use = \Drafts
  }
  mailbox Junk {
    auto = subscribe
    special_use = \Junk
  }
  mailbox Trash {
    auto = subscribe
    special_use = \Trash
  }
  mailbox Sent {
    auto = subscribe
    special_use = \Sent
  }
  mailbox "Sent Messages" {
    special_use = \Sent
  }
}

vim /etc/dovecot/conf.d/20-pop3.conf:

pop3_uidl_format = %08Xu%08Xv
pop3_client_workarounds = outlook-no-nuls oe-ns-eoh

vim /etc/dovecot/conf.d/auth-system.conf.ext:

#passdb {
#  driver = pam
  # [session=yes] [setcred=yes] [failure_show_msg=yes] [max_requests=]
  # [cache_key=] []
  #args = dovecot
#}
#userdb {
  # 
#  driver = passwd
  # [blocking=no]
  #args =

  # Override fields from passwd
  #override_fields = home=/home/virtual/%u
#}

vim /etc/dovecot/conf.d/10-director.conf:

#service director {
#  unix_listener login/director {
    #mode = 0666
#  }

vim /usr/share/dovecot/protocols.d/imapd.protocol:

#protocols = $protocols imap

vim /usr/share/dovecot/protocols.d/pop3d.protocol:

#protocols = $protocols pop3

vim /usr/share/dovecot/protocols.d/lmtpd.protocol:

#protocols = $protocols lmtp

Создаём файл запросов dovecot для mysql
vim /etc/dovecot/dovecot-sql.conf:

driver = mysql
connect = host=127.0.0.1 dbname=postfix user=postfix password=postfixdbpass
default_pass_scheme = MD5-CRYPT
password_query = SELECT username as user, password FROM mailbox WHERE username = '%u'
user_query = SELECT '/var/mail/%d/%u' AS home, 2000 AS uid, 8 AS gid, CONCAT('*:bytes=', CAST(quota AS CHAR)) AS quota_rule FROM mailbox WHERE username = '%u' AND active = '1'

invoke-rc.d dovecot restart

Настраиваем postfix
cp /usr/share/postfix/main.cf.dist /etc/postfix/main.cf
vim /etc/postfix/main.cf:

queue_directory = /var/spool/postfix
mail_owner = postfix
myhostname = mail.example.com
mydomain = example.com
myorigin = $mydomain
mydestination = $myhostname, localhost.$mydomain, localhost
local_recipient_maps = $virtual_mailbox_maps, $virtual_alias_maps, $alias_maps
mynetworks_style = subnet
mynetworks = 127.0.0.0/8, 192.168.40.0/24 #разрешенные адреса
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
recipient_delimiter = +
mail_spool_directory = /var/mail
mailbox_command = /usr/lib/dovecot/deliver
mailbox_transport = dovecot
debug_peer_level = 2  #после отладки можно выключить
sendmail_path = /usr/sbin/sendmail.postfix
newaliases_path = /usr/bin/newaliases.postfix
mailq_path = /usr/bin/mailq.postfix
setgid_group = postdrop
html_directory = no
manpage_directory = /usr/share/man
sample_directory = no
readme_directory = no
smtpd_client_restrictions = permit_mynetworks,
                            permit_sasl_authenticated,
                            check_client_access hash:/etc/postfix/client_access

smtpd_helo_restrictions = check_helo_access hash:/etc/postfix/hello_access,
                          permit_mynetworks,
                          permit_sasl_authenticated,
                          reject_invalid_helo_hostname,
                          reject_non_fqdn_helo_hostname,
                          reject_unknown_helo_hostname

smtpd_sender_restrictions = permit_mynetworks,
                            check_sender_access hash:/etc/postfix/sender_access,
                            reject_authenticated_sender_login_mismatch,
                            reject_unknown_sender_domain,
                            reject_unlisted_sender,
                            permit_sasl_authenticated

smtpd_recipient_restrictions = permit_mynetworks,
                               permit_sasl_authenticated,
                               reject_unauth_destination,
                               reject_unlisted_recipient,
                               reject_unknown_recipient_domain,
                               reject_non_fqdn_recipient,
                               reject_unverified_recipient

#mysql
virtual_mailbox_base = /var/mail
virtual_mailbox_maps = mysql:/etc/postfix/virtual_mailbox_maps.cf
virtual_alias_maps = mysql:/etc/postfix/virtual_alias_maps.cf
virtual_mailbox_domains = mysql:/etc/postfix/virtual_mailbox_domains.cf
#quota
virtual_mailbox_limit = 52428800
message_size_limit = 100485760
mailbox_size_limit = 524288000

smtpd_etrn_restrictions = reject
smtpd_reject_unlisted_sender = yes
disable_vrfy_command = yes
strict_rfc821_envelopes = yes
show_user_unknown_table_name = no
address_verify_sender = <>
unverified_sender_reject_code = 550
smtpd_helo_required = yes
smtp_always_send_ehlo = yes
smtpd_hard_error_limit = 10
smtpd_timeout = 240s
smtp_helo_timeout = 240s
smtp_rcpt_timeout = 300s
virtual_minimum_uid = 2000
virtual_uid_maps = static:2000
virtual_gid_maps = static:8
virtual_transport = dovecot
dovecot_destination_recipient_limit=1
smtpd_sasl_auth_enable = yes
smtpd_use_tls = yes
smtpd_tls_cert_file = /etc/ssl/certs/dovecot.pem
smtpd_tls_key_file = /etc/ssl/private/dovecot.pem
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtpd_sasl_security_options = noanonymous
broken_sasl_auth_clients = yes
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth

vim /etc/postfix/master.cf:

smtps     inet  n       -       -       -       -       smtpd
  -o syslog_name=postfix/smtps
  -o smtpd_tls_wrappermode=yes
dovecot   unix  -       n       n       -       -       pipe
  flags=DRhu user=vmail:mail argv=/usr/lib/dovecot/deliver -d ${recipient}

Создаем файлы запросов mysql для postfix
vim /etc/postfix/virtual_mailbox_maps.cf:

user = postfix
password = postfixdbpass
dbname = postfix
hosts = 127.0.0.1
table = users
select_field = maildir
where_field = email
additional_conditions = and enabled = 1

vim /etc/postfix/virtual_alias_maps.cf:

user = postfix
password = postfixdbpass
dbname = postfix
table = alias
select_field = goto
where_field = address
hosts = 127.0.0.1

vim /etc/postfix/virtual_mailbox_domains.cf:

user = postfix
password = postfixdbpass
hosts = 127.0.0.1
dbname = postfix
query = SELECT domain FROM domain WHERE domain='%s' AND transport <> 'relay' AND active = '1'

vim /etc/postfix/virtual_mailbox_limit_maps.cf:

user = postfix
password = postfixdbpass
dbname = postfix
table = users
select_field = quota
where_field = email
additional_conditions = and enabled = 1
hosts = 127.0.0.1

Создаем базу данных псевдонимов
newaliases

Создаём файлы базы данных для postfix:
touch /etc/postfix/{client_access,hello_access,sender_access,recipient_access}
postmap /etc/postfix/{client_access,hello_access,sender_access,recipient_access}

Создаём виртуального пользователя, который будет заниматься локальной доставкой почты
useradd -u 2000 -g mail -d /var/mail -s /bin/false vmail

Создаём базу для postfix
mysql -u root -p
CREATE DATABASE postfix;
GRANT ALL ON postfix.* TO 'postfix'@'localhost' IDENTIFIED BY 'postfixdbpass';
quit

invoke-rc.d postfix restart

Настраиваем postfixadmin
vim /usr/share/postfixadmin/config.inc.php:

$CONF['default_language'] = 'ru';
$CONF['database_type'] = 'mysqli';
$CONF['database_host'] = 'localhost';
$CONF['database_user'] = 'postfix';
$CONF['database_password'] = 'postfixdbpass';
$CONF['database_name'] = 'postfix';
$CONF['encrypt'] = 'dovecot:CRAM-MD5';
$CONF['domain_path'] = 'YES';
$CONF['domain_in_mailbox'] = 'NO';
$CONF['postfix_admin_url'] = '/pfa';

vim /etc/apache2/conf-enabled/postfixadmin.conf:

Alias /pfa /usr/share/postfixadmin/
<Directory /usr/share/postfixadmin/>
  AllowOverride all
  DirectoryIndex index.php
  Require all granted
</Directory>

chown -R www-data:www-data /usr/share/postfixadmin/
invoke-rc.d apache2 reload

В /usr/share/postfixadmin/upgrade.php нужно заменить все значения «255» на «100» иначе при установке будет ошибка «Invalid query: Specified key was too long; max key length is 1000 bytes»
sed -i ‘s|255|100|g’ /usr/share/postfixadmin/upgrade.php

Запускаем мастер установки postfixadmin переходим по адресу http://example.com/pfa/setup.php
Генерируем hash пароля установки
Копируем hash в опцию «$CONF[‘setup_password’]» в /usr/share/postfixadmin/config.inc.php
Вводим пароль установки
Логин вводим в виде почтового адреса, например admin@example.com
Пароль администратора
Для управления почтовыми ящиками нужно заходить на http://example.com/pfa

Добавляем записи для почтового сервера в файл зоны DNS
vim /var/bind9/chroot/etc/bind/example.com.wan:

                IN              MX      10      mail.example.com.
mail                 IN              A       192.168.40.1

rndc reload

Отправляем статистику почтового сервера на почту
aptitude install pflogsumm
crontab -e

 01 00 * * * /usr/sbin/pflogsumm -e -d yesterday /var/log/mail.log | mail -s "Postfix Mail Statistics" admin@example.com

Открываем порты для почты
iptables -I INPUT 1 -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -I INPUT 2 -s 192.168.40.0/24 -d 192.168.40.1 -i eth0 -p tcp -m state --state NEW -m multiport --dports 25,80,110,143,465,993,995 -j ACCEPT
invoke-rc.d netfilter-persistent save

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *