Почтовый сервер на базе Postfix Dovecot SASL Amavis OpenDKIM OpenDMARC SPF postgrey MySQL 8.0 debian 11 ubuntu 20.04
- После установки debian 11 выполним обновление пакетов
Code:
sudo apt-get update sudo apt-get upgrade
- Устанавливаем Postfix, Dovecot, MySQL и другие необходимые пакеты
Code:
apt-get install postfix dovecot-common dovecot-imapd mysql-server mysql-client postfix-mysql dovecot-mysql sasl2-bin opendkim opendkim-tools [SIZE=16px][FONT=Roboto Mono][COLOR=#000000]opendmarc[/COLOR][/FONT][/SIZE] clamav-daemon amavisd-new spamassassin spamc -y
- Подключаемся к MySQL
Code:
mysql -u root –p
Code:CREATE DATABASE base0;
создаем таблицу доменов.Code:[SIZE=14px][FONT=SFMono-Regular][COLOR=#212529]> USE base0; > CREATE TABLE `virtual_domains` ( `id` INT NOT NULL AUTO_INCREMENT, `name` VARCHAR(50) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;[/COLOR][/FONT][/SIZE]
Code:[SIZE=14px][FONT=SFMono-Regular][COLOR=#212529]> USE base01 > CREATE TABLE `virtual_domains` ( `id` INT NOT NULL AUTO_INCREMENT, `name` VARCHAR(50) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;[/COLOR][/FONT][/SIZE][B][FONT=Playfair Display][COLOR=#212529][/COLOR][/FONT][/B]
Code:[SIZE=14px][FONT=SFMono-Regular][COLOR=#212529]> CREATE TABLE `virtual_users` ( `id` INT NOT NULL AUTO_INCREMENT, `domain_id` INT NOT NULL, `password` VARCHAR(106) NOT NULL, `email` VARCHAR(120) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `email` (`email`), FOREIGN KEY (domain_id) REFERENCES virtual_domains(id) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8;[/COLOR][/FONT][/SIZE][B][FONT=Playfair Display][COLOR=#212529][/COLOR][/FONT][/B]
Code:[SIZE=14px][FONT=SFMono-Regular][COLOR=#212529]> CREATE TABLE `virtual_aliases` ( `id` INT NOT NULL AUTO_INCREMENT, `domain_id` INT NOT NULL, `source` varchar(100) NOT NULL, `destination` varchar(100) NOT NULL, PRIMARY KEY (`id`), FOREIGN KEY (domain_id) REFERENCES virtual_domains(id) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8;[/COLOR][/FONT][/SIZE]
Code:[SIZE=14px][FONT=SFMono-Regular][COLOR=#212529]INSERT INTO bse01.virtual_domains (`id` ,`name`) VALUES ('1', 'sun-torrents.name');[/COLOR][/FONT][/SIZE]
Code:[SIZE=14px][FONT=SFMono-Regular][COLOR=#212529]> INSERT INTO `base0`.`virtual_users` (`id`, `domain_id`, `password` , `email`) VALUES ('1', '1', ENCRYPT('nVD4Xvz7JZTHB2', CONCAT('$6$', SUBSTRING(SHA(RAND()), -16))), 'support@newintlaw.org'),[/COLOR][/FONT][/SIZE]
- Настройте Postfix. В данной части статьи, объяснения конфигурации постфикс, приводится не будут. Для удобства, будет представлен, рабочий конфиг файла main.cf для реконфигурации постфикс, введите команду
Code:nano /etc/postfix/main.cf
Code:smtpd_banner = $myhostname ESMTP #Отключаем использование comsat biff = no #Запрещаем автоматически дополнять неполное доменное имя в адресе письма append_dot_mydomain = no #Указываем имя нашего хоста myhostname = smtp.sun-torrents.name mynetworks = 127.0.0.0/8 10.16.10.0/29 # Указываем файл с псевдонимами почтовых ящиков alias_maps = hash:/etc/aliases #Указываем, для каких доменов будем принимать почту mydestination = localhost smtp.sun-torrents.name # Не будем ограничивать размер почтовых ящиков mailbox_size_limit = 0 recipient_delimiter = + #Указываем прослушивание на всех сетевых интерфейсах inet_interfaces = all #Указываем обязательность использование клиентами команды helo smtpd_helo_required = yes smtp_always_send_ehlo = yes #Описываем доступ доменам, почтовым ящикам и т.д. virtual_transport = dovecot virtual_mailbox_domains = mysql:/etc/postfix/database-domains.cf virtual_mailbox_maps = mysql:/etc/postfix/database-users.cf virtual_mailbox_base = /var/vmail virtual_alias_maps = mysql:/etc/postfix/database-alias.cf virtual_minimum_uid = 100 virtual_uid_maps = static:5000 virtual_gid_maps = static:5000 policy-spf_time_limit = 3600s home_mailbox = Maildir/ local_recipient_maps = $virtual_mailbox_maps #Описываем авторизацию по SMTP для клиентов не из доверенной зоны smtpd_sasl_type = dovecot smtpd_sasl_auth_enable = yes smtpd_sasl_path = private/auth smtpd_sasl_security_options = noanonymous #broken_sasl_auth_clients = yes #Указываем каталог очереди для Postfix queue_directory = /var/spool/postfix ################################################## # header_checks = pcre:/etc/postfix/header_checks disable_vrfy_command = yes additional_config_dir = /etc/postfix/config white_client = pcre:/etc/postfix/config/white_client block_dsl = regexp:$additional_config_dir/block_dsl white_client_ip = check_client_access pcre:$additional_config_dir/white_client_ip helo_access = check_helo_access pcre:$additional_config_dir/helo_checks mx_access = check_sender_mx_access cidr:$additional_config_dir/mx_access, check_sender_access hash:/etc/postfix/domain_mx_whitelist invalid_hostname_reject_code = 550 non_fqdn_reject_code = 550 unknown_address_reject_code = 550 unknown_client_reject_code = 550 unknown_hostname_reject_code = 550 unverified_recipient_reject_code = 550 unverified_sender_reject_code = 550 smtpd_reject_unlisted_recipient = yes smtpd_restriction_classes = block_dsl, helo_access, mx_access, white_client_ip, white_client smtpd_client_restrictions = block_dsl, helo_access, mx_access, white_client_ip, white_client, permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination, reject_unknown_address, reject_unauth_pipelining, reject_unknown_sender_domain, permit smtpd_sender_restrictions = check_sender_access hash:/etc/postfix/sender_access, check_sender_access hash:/etc/postfix/domain_mx_whitelist smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination, check_policy_service inet:127.0.0.1:10023, reject_unauth_pipelining, reject_non_fqdn_recipient, reject_unknown_recipient_domain, check_recipient_access regexp:/etc/postfix/recipient_access, reject_unknown_client_hostname, reject_unknown_reverse_client_hostname, reject_invalid_helo_hostname, reject_non_fqdn_helo_hostname, reject_unknown_helo_hostname, check_sender_access hash:/etc/postfix/domain_mx_whitelist, check_policy_service unix:private/policy-spf permit proxy_read_maps = $local_recipient_maps $mydestination $virtual_alias_maps $virtual_alias_domains $virtual_mailbox_maps $virtual_mailbox_domains $relay_recipient_maps $relay_domains $canonical_maps $sender_canonical_maps $recipient_canonical_maps $relocated_maps $transport_maps $mynetworks $virtual_mailbox_limit_maps smtp_use_tls = yes smtpd_use_tls = yes smtp_tls_note_starttls_offer = yes smtpd_tls_key_file = /etc/dovecot/sun-torrents.key smtpd_tls_cert_file = /etc/dovecot/sun-torrents.cert smtpd_tls_loglevel = 1 smtpd_tls_received_header = yes smtpd_tls_session_cache_timeout = 1s smtp_skip_5xx_greeting = no smtpd_reject_unlisted_sender = yes tls_random_source = dev:/dev/urandom milter_protocol = 2 milter_default_action = accept smtpd_milters = inet:localhost:12301 non_smtpd_milters = inet:localhost:12301 content_filter = smtp-amavis:[127.0.0.1]:10024 opendmarc_milter = unix:var/run/opendmarc/opendmarc.sock smtpd_relay_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination, check_policy_service inet:127.0.0.1:10023, reject_unauth_pipelining, reject_non_fqdn_recipient, reject_unknown_recipient_domain, check_recipient_access regexp:/etc/postfix/recipient_access, reject_unknown_client_hostname, reject_unknown_reverse_client_hostname, reject_invalid_helo_hostname, reject_non_fqdn_helo_hostname, reject_unknown_helo_hostname, check_sender_access hash:/etc/postfix/domain_mx_whitelist, check_policy_service unix:private/policy-spf permit [B][FONT=Playfair Display][COLOR=#212529][/COLOR][/FONT][/B]
- Создайте mysql-virtual-mailbox-domains.cf
Code:nano /etc/postfix/mysql-virtual-mailbox-domains.cf
Code:user = terra password = hosts = 127.0.0.1 dbname = base0 query = SELECT 1 FROM virtual_domains WHERE name='%s'
- Создайте mysql-virtual-mailbox-maps.cf
Code:nano /etc/postfix/mysql-virtual-mailbox-maps.cf
Code:user = terra password = hosts = 127.0.0.1 dbname = base01 query = SELECT 1 FROM virtual_users WHERE email='%s'
- Создайте mysql-virtual-alias-maps.cf
Code:nano /etc/postfix/mysql-virtual-alias-maps.cf
Code:user = terra password = hosts = 127.0.0.1 dbname = base01 query = SELECT destination FROM virtual_aliases WHERE source='%s'
- Настроить master.cf
Code:nano /etc/postfix/master.cf
Code:# # Postfix master process configuration file. For details on the format # of the file, see the master(5) manual page (command: "man 5 master"). # # 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 - - - 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_client_restrictions=permit_sasl_authenticate d,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_client_restrictions=permit_sasl_authenticate d,reject # -o milter_macro_daemon_name=ORIGINATING #628 inet n - - - - qmqpd smtp inet n - y - - smtpd pickup fifo n - y 60 1 pickup cleanup unix n - y - 0 cleanup qmgr fifo n - n 300 1 qmgr #qmgr fifo n - n 300 1 oqmgr tlsmgr unix - - y 1000? 1 tlsmgr rewrite unix - - y - - trivial-rewrite bounce unix - - y - 0 bounce defer unix - - y - 0 bounce trace unix - - y - 0 bounce verify unix - - y - 1 verify flush unix n - y 1000? 0 flush proxymap unix - - n - - proxymap proxywrite unix - - n - 1 proxymap smtp unix - - y - - smtp # -o smtp_helo_timeout=5 -o smtp_connect_timeout=5 relay unix - - y - - smtp showq unix n - y - - showq error unix - - y - - error retry unix - - y - - error discard unix - - y - - discard local unix - n n - - local virtual unix - n n - - virtual lmtp unix - - y - - lmtp anvil unix - - y - 1 anvil # # ================================================== ================== # 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 # scache unix - - y - 1 scache 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 dovecot unix - n n - - pipe flags=DRhu user=vmail:vmail argv=/usr/lib/dovecot/deliver -d ${recipient} submission inet n - y - - smtpd -o smtpd_tls_security_level=encrypt -o smtpd_sasl_auth_enable=yes -o smtpd_sasl_type=dovecot -o smtpd_sasl_path=private/auth -o smtpd_sasl_security_options=noanonymous -o smtpd_sasl_local_domain=$myhostname -o smtpd_client_restrictions=permit_sasl_authenticate d,reject -o smtpd_sender_login_maps=hash:/etc/postfix/virtual -o smtpd_sender_restrictions=reject_sender_login_mism atch -o smtpd_recipient_restrictions=reject_non_fqdn_recip ient,reject_unknown_recipient_domain,permit_sasl_a uthenticated,reject -o content_filter=spamassassin smtps inet n - n - - smtpd -o syslog_name=postfix/smtps -o smtpd_tls_wrappermode=yes -o smtpd_sasl_auth_enable=yes policy-spf unix - n n - 0 spawn user=nobody argv=/usr/bin/policyd-spf /etc/postfix-policyd-spf-python/policyd-spf.conf smtp-amavis unix - - y - 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 - y - - smtpd -o content_filter= -o local_recipient_maps= -o relay_recipient_maps= -o smtpd_restriction_classes= -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,rej ect -o smtpd_data_restrictions=reject_unauth_pipelining -o smtpd_end_of_data_restrictions= -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 #smtp inet n - - - - smtpd # -o content_filter=spamassassin #submission inet n - - - - smtpd # -o content_filter=spamassassin spamassassin unix - n n - - pipe user=debian-spamd argv=/usr/bin/spamc -f -e /usr/sbin/sendmail -oi -f ${sender} ${recipient}
- Создаем группу vmail и пользователя vmail, входящего в эту группу.
Code:
sudo groupadd -g 5000 vmail sudo useradd -g vmail -u 5000 vmail
- Создадим каталог, где будут размещаться почтовые ящики:
Code:
sudo mkdir /var/vmail
Code:sudo chown vmail:vmail /var/vmail
Code:sudo chmod 770 /var/vmail
- Задаем сообщение, которое будет выводить Postfix в случае, если отправитель будет представляться именем нашего сервера
Code:
sudo nano /etc/postfix/helo.list example.org 550 Don't use my hostname
Code:sudo postmap /etc/postfix/helo.list
- Задаем сообщение, которое будет выводить Postfix в случае, если отправитель извне будет говорить, что он из нашей сети
Code:
sudo nano /etc/postfix/ext_sender example.org 450 Do not use my domain in your envelope sender
Code:sudo postmap /etc/postfix/ext_sender
- Настраиваем демон saslauthd для взаимодействия с Postfix
Code:
sudo mkdir -p /var/spool/postfix/var/run/saslauthd sudo nano /etc/default/saslauthd
Code:START=yes DESC="SASL Authentication Daemon" NAME="saslauthd" MECHANISMS="pam" MECH_OPTIONS="" THREADS=5 OPTIONS="-c -m /var/spool/postfix/var/run/saslauthd -r"
- Настраиваем pam-аутентификацию
Code:
sudo nano /etc/pam.d/smtp
Code:auth required pam_mysql.so user=mail_admin passwd=mail_admin_password host=127.0.0.1 db=mail table=users usercolumn=user passwdcolumn=password crypt=1 account sufficient pam_mysql.so user=mail_admin passwd=mail_admin_password host=127.0.0.1 db=mail table=users usercolumn=user passwdcolumn=password crypt=1
- Настраиваем Postfix для взаимодействия с saslauthd
Code:
sudo nano /etc/postfix/sasl/smtpd.conf
Code:pwcheck_method: saslauthd mech_list: plain login allow_plaintext: true auxprop_plugin: mysql sql_hostnames: 127.0.0.1 sql_user: root sql_passwd: 12345 sql_database: base0 sql_select: SELECT password FROM users WHERE user = '%u'
- Владельцем данных файлов должен быть root
Code:
sudo chown root /etc/pam.d/smtp /etc/postfix/sasl/smtpd.conf
- Добавляем пользователя postfix в группу sasl
Code:
sudo adduser postfix sasl
- Настроить dovecot.conf
Code:
nano /etc/dovecot/dovecot.conf
Code:!include_try /usr/share/dovecot/protocols.d/*.protocol protocols = imap lmtp
- Настроить 10-mail.conf
Code:
nano /etc/dovecot/conf.d/10-mail.conf
Code:#mail_location = mbox:~/mail:INBOX=/var/mail/%u на mail_location = maildir:/var/vmail//%d/%n
Code:mail_privileged_group = vmail
- Настроить 10-auth.conf
Code:nano /etc/dovecot/conf.d/10-auth.conf
Code:#disable_plaintext_auth = yes
Code:disable_plaintext_auth = yes
Code:auth_mechanisms = plain login
Code:#!include auth-system.conf.ext !include auth-sql.conf.ext]
Comment