Introduction
I wanted to study the mail server for a long time, but I only managed to get around to it now, plus I couldn't find much accurate information, so I decided to write as detailed a publication as possible. This publication will cover not only postfix, dovecot, mysql, postfixadmin, but also spamassassin, clamav-milter (a special version of clamav for mail servers), postgrey, and the possibility of moving spam to the 'Spam' folder (dovecot-pigeonhole).
Preparation
First, let's install the packages needed for operation (postfix, dovecot, and dovecot-pigeonhole need to be installed from the ports; dovecot-sieve can generally be installed from packages, but ports may have newer versions, which can lead to compatibility issues between dovecot and dovecot-sieve). We will install the following packages:
pkg install apache24 php73 mod_php73 php73-extensions php73-mysqli php73-mbstring php73-openssl clamav-milter postgrey spamassassin mysql57-server openssl wget
After installation, we will add the necessary services to autostart:
#postfix и dovecot также добавим, чтобы не возвращаться к этому позже
sysrc postfix_enable="YES"
sysrc dovecot_enable="YES"
sysrc mysql_enable="YES"
sysrc apache24_enable="YES"
sysrc spamd_flags="-u spamd -H /var/spool/spamd"
sysrc spamd_enable="YES"
sysrc postgrey_enable="YES"
sysrc clamav_clamd_enable="YES"
sysrc clamav_milter_enable="YES"
sysrc clamav_freshclam_enable="YES"
#freshclam будем использовать как службу и проверять обновления 12 раз
sysrc clamav_freshclam_flags="--daemon --checks=12"
Let's start the services:
service apache24 start
service mysql-server start
#Before starting spamassassin, the databases need to be updated and rules compiled
sa-update
sa-compile
service sa-spamd start
#Perform clamav database updates before starting
freshclam
service clamav-clamd start
service clamav-freshclam start
service clamav-milter start
#Before starting postgrey, edit the initialization script (\/usr\/local\/etc\/rc.d\/postgrey). To ensure senders are moved to the 'whitelist' after 4 attempts to send emails, find the line: ${postgrey_flags:=--inet=10023} and change it to:
: ${postgrey_flags:=--inet=10023 --auto-whitelist-clients=4}
service postgrey start
Don't forget to add the necessary lines for PHP operation in apache and correct working of postfixadmin in httpd.conf:
SetHandler application/x-httpd-php
SetHandler application/x-httpd-php-source
DirectoryIndex index.php
#Also, it is necessary to change the home directory for the correct operation of postfixadmin
DocumentRoot "/usr/local/www/apache24/data/postfixadmin-3.2/public"
Next, you need to navigate to the directory and download postfixadmin
cd /usr/local/www/apache24/data
Let's download postfixadmin (as of the time of writing, the current version was 3.2)
wget --no-check-certificate https://sourceforge.net/projects/postfixadmin/files/postfixadmin/postfixadmin-3.2/postfixadmin-3.2.tar.gz
After that, it is necessary to extract the archive in this directory and change the directory ownership:
gzip -d postfixadmin-3.2.tar.gz
tar -xvf postfixadmin-3.2.tar
chown -R www:www /usr/local/www/apache24/data
service apache24 restart
Next, we will prepare the database for postfixadmin. Execute the mysql-secure-installation script (the password you create in this script will also need to be set in MySQL using the alter user command) for initial MySQL configuration. Then, enter MySQL, create a database, and set permissions for it:
mysql -p -r
alter user 'root'@'localhost' identified by 'password123';
create database postfix;
grant all privileges on postfix.* to 'postfix'@'localhost' identified by 'password123';
exit
Once the database is configured, you need to edit the config.inc.php file. In this example, this file is located in the directory /usr/local/www/apache24/data/postfixadmin-3.2/. You need to edit several lines in this file and modify them accordingly. After changing the settings, restart Apache. Additionally, create the templates_c directory in /usr/local/www/apache24/data/postfixadmin-3.2 and set its owner to www:
mkdir /usr/local/www/apache24/data/postfixadmin-3.2/templates_c
chown -R www:www /usr/local/www/apache24/data/postfixadmin-3.2/templates_c
$CONF['configured'] = true
# This hash must be generated in the web interface of postfixadmin and added to this line.
$CONF['setup_password'] = 'dd28fb2139a3bca426f02f60e6877fd5:13d2703c477b0ab85858e3ac5e076a0a7a477315';
$CONF['default_language'] = 'en'
$CONF['database_type'] = 'mysqli';
$CONF['database_host'] = 'localhost';
$CONF['database_user'] = 'postfix';
# Password and name of the database created in this example
$CONF['database_password'] = 'password123';
$CONF['database_name'] = 'postfix';
service apache24 restart
SSL
To generate the key, we will use the method suggested on the postfix.org website, creating our own certificate authority. Go to the directory /etc/ssl and execute the script:
cd /etc/ssl
/usr/local/openssl/misc/CA.pl -newca
During the script execution, you will be prompted for a name for the certificate. Do not enter anything, just press Enter. Then the script will ask you to create a password for the certificate, after which there will be standard questions for creating the certificate.
Next, you need to create a private key (without a password) and an unsigned public key certificate (the Organizational Unit Name (e.g., section) [] should differ from that in the certificate created above):
openssl req -new -newkey rsa:4096 -nodes -keyout foo-key.pem -out foo-req.pem
We will sign the public key certificate (specify the number of days as needed):
openssl ca -out foo-cert.pem -days 365 -infiles foo-req.pem
Leave the generated certificates in this directory, or move them to the directory that is more convenient for you. The postfix and dovecot configurations will be set up considering that the certificates will be located in this directory.
User vmail
Before starting the installation of postfix, dovecot, and dovecot-pigeonhole, let's create the user and group (the group will be created automatically) vmail, as well as the directory where the mail will be stored.
pw useradd -n vmail -s /usr/sbin/nologin -u 1000 -d /var/vmail
Let's create a directory for the mail and set the owner to the vmail user:
mkdir /var/vmail
chown -R vmail:vmail /var/vmail
chmod -R 744 /var/vmail
Postfix, dovecot, dovecot-pigeonhole
As I mentioned earlier, we will build these applications from ports. Execute the command to download and unpack the ports:
portsnap fetch extract
After unpacking the ports, go to the dovecot directory, configure the port (be sure to enable mysql support), and start the build (BATCH=yes will tell make not to ask questions during installation):
cd /usr/ports/mail/dovecot
make config
make BATCH=yes install clean
Repeat the same steps for postfix and dovecot-pigeonhole.
dovecot-pigeonhole:
cd /usr/ports/mail/dovecot-pigeonhole
make BATCH=yes install clean
postfix: also enable mysql support in the port configuration
cd /usr/ports/mail/postfix-sasl
make config
make BATCH=yes install clean
Before starting dovecot, copy the configurations:
cp -R /usr/local/etc/dovecot/example-config/* /usr/local/etc/dovecot
After installing postfix and dovecot, start the services:
service postfix start
service dovecot start
It is also necessary to create a directory where the module for forwarding spam to the spam folder will be compiled. In my case, this directory is in /usr/local/etc/dovecot/conf.d. The directory name is def, let's create this directory and a file with code for compilation and set the owner of this directory to the vmail user:
mkdir /usr/local/etc/dovecot/conf.d/def
touch /usr/local/etc/dovecot/conf.d/def/default.sieve
chown -R vmail:vmail /usr/local/etc/dovecot/conf.d/def
chmod -R 744 /usr/local/etc/dovecot/conf.d/def
Place the following lines into this file:
require "fileinto";
if header :contains "X-Spam-Flag" "YES" {
fileinto "Junk";
}
Configurations
In this section, I will provide examples of configurations with comments in them. I am only unsure about the spamassassin configuration, as I haven't found correct descriptions online (I left the default configuration). Please add in the comments how to better configure spamassassin.
Postfix
First, you need to create files to retrieve users, domains, and quotas from the database. Create a directory for storing these files and the necessary files:
mkdir /usr/local/etc/postfix/mysql
touch /usr/local/etc/postfix/mysql/relay_domains.cf
touch /usr/local/etc/postfix/mysql/virtual_alias_maps.cf
touch /usr/local/etc/postfix/mysql/virtual_alias_domain_maps.cf
touch /usr/local/etc/postfix/mysql/virtual_mailbox_maps.cf
The contents of these files will be as follows:
relay_domains.cf
hosts = 127.0.0.1
user = postfix
password = password123
dbname = postfix
query = SELECT domain FROM domain WHERE domain='%s' and backupmx = '1'
virtual_alias_maps.cf
hosts = 127.0.0.1
user = postfix
password = password123
dbname = postfix
query = SELECT goto FROM alias WHERE address='%s' AND active ='1'
virtual_alias_domain_maps.cf
hosts = 127.0.0.1
user = postfix
password = password123
dbname = postfix
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'
virtual_mailbox_maps.cf
hosts = 127.0.0.1
user = postfix
password = password123
dbname = postfix
query = SELECT maildir FROM mailbox WHERE username='%s' AND active = '1'
master.cf
#Указать postfix о том, что необходимо использовать dovecot для доставки почты
dovecot unix - n n - - pipe
flags=DRhu user=vmail:vmail argv=/usr/local/libexec/dovecot/deliver -f ${sender} -d ${recipient}
#Укажем службе smtpd о возможности авторизоваться через sasl, а также о том, что spamassassin будет фильтровать почту
smtp inet n - n - - smtpd
-o content_filter=spamassassin
-o smtpd_sasl_auth_enable=yes
#Использовать порт 587 и возможность авторизации через sasl
submission inet n - n - - smtpd
-o smtpd_sasl_auth_enable=yes
#Указать службе smtp использовать авторизацию через SASL
smtps inet n - n - - smtpd
-o smtpd_sasl_auth_enable=yes
-o smtpd_tls_wrappermode=yes
#Использовать Spamassassin
spamassassin unix - n n - - pipe
flags=DROhu user=vmail:vmail argv=/usr/local/bin/spamc -f -e
/usr/local/libexec/dovecot/deliver -f ${sender} -d ${user}@${nexthop}
#628 inet n - n - - qmqpd
pickup unix n - n 60 1 pickup
cleanup unix n - n - 0 cleanup
qmgr unix n - n 300 1 qmgr
#qmgr unix n - n 300 1 oqmgr
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
proxywrite unix - - n - 1 proxymap
smtp unix - - n - - smtp
relay unix - - n - - smtp
-o syslog_name=postfix/$service_name
# -o smtp_helo_timeout=5 -o smtp_connect_timeout=5
showq unix n - n - - showq
error unix - - n - - error
retry unix - - n - - error
discard unix - - n - - discard
local unix - n n - - local
virtual unix - n n - - virtual
lmtp unix - - n - - lmtp
anvil unix - - n - 1 anvil
scache unix - - n - 1 scache
postlog unix-dgram n - n - 1 postlogd
main.cf
#Если не указать в данном параметре значение dovecot, то почта будет поступать локальным пользователям
local_transport = dovecot
#Не чувствительный к регистру список ключевых слов, которые SMTP-сервер не будет отправлять в ответе EHLO удалённому SMTP клиенту
smtpd_discard_ehlo_keywords = CONNECT GET POST
#Подождать пока придёт вся информация о клиенте и только потом применить ограничения
smtpd_delay_reject = yes
#Требовать начинать сессию с приветствия
smtpd_helo_required = yes
#Запретить узнавать существует определённый почтовый ящик, или нет
disable_vrfy_command = yes
#Этот параметр необходим для работы устаревших клиентов
broken_sasl_auth_clients = yes
#Запретить анонимную авторизацию
smtpd_sasl_security_options = noanonymous noactive nodictionary
smtp_sasl_security_options = noanonymous noactive nodictionary
#Использовать dovecot для авторизации(по умолчанию cyrus)
smtpd_sasl_type = dovecot
smtp_sasl_type = dovecot
#путь до плагина аутентификации
smtpd_sasl_path = private/auth
#Список существующих пользователей
local_recipient_maps = $virtual_mailbox_maps $virtual_alias_maps
#Если пользователя не существует, тогда отклонить почту
smtpd_reject_unlisted_recipient = yes
#Лимиты размера писем
message_size_limit = 10485760
#Каждый получатель получит индивидуальную обработку spamassassin
spamassassin_destination_recipient_limit = 1
#Антивирус
milter_default_action = accept
milter_protocol = 2
#Путь до сокета clamav
smtpd_milters = unix:/var/run/clamav/clmilter.sock
non_smtpd_milters = unix:/var/run/clamav/clmilter.sock
#MYSQL
relay_domains = mysql:/usr/local/etc/postfix/mysql/relay_domains.cf
virtual_alias_maps = mysql:/usr/local/etc/postfix/mysql/virtual_alias_maps.cf, mysql:/usr/local/etc/postfix/mysql/virtual_alias_domain_maps.cf
virtual_mailbox_maps = mysql:/usr/local/etc/postfix/mysql/virtual_mailbox_maps.cf
#Проверка HELO
smtpd_helo_restrictions = permit_sasl_authenticated, reject_non_fqdn_helo_hostname, reject_invalid_hostname
#Ограничения для содержимого писем
smtpd_data_restrictions = permit_sasl_authenticated reject_unauth_pipelining, reject_multi_recipient_bounce
#Правила отправки почты
smtpd_sender_restrictions = permit_sasl_authenticated reject_sender_login_mismatch,reject_unauthenticated_sender_login_mismatch, reject_non_fqdn_sender, reject_unknown_sender_domain
#Правила приёма почты(check_policy_service inet:127.0.0.1:10023 параметр postgrey - запрещает приём почты с первого раза)
smtpd_recipient_restrictions = permit_sasl_authenticated reject_non_fqdn_recipient, reject_unknown_recipient_domain, reject_multi_recipient_bounce, reject_unknown_client_hostname, reject_unauth_destination, check_policy_service inet:127.0.0.1:10023
#Папка для почты
virtual_mailbox_base = /var/vmail
#uid и gid vmail
virtual_minimum_uid = 1000
virtual_uid_maps = static:1000
virtual_gid_maps = static:1000
#Указать виртуальный транспорт
virtual_transport = devecot
dovecot_destination_recipient_limit = 1
#Настройки шифрования
smtp_use_tls=yes
smtp_tls_note_starttls_offer=yes
#строка smtp_tls_security_level=encrypt отвечает за отправку почту только через ssl, если сервер не поддерживает приём почты через ssl, тогда необходимо поставить smtp_tls_security_level=may(если сервер не поддерживает ssl, то отправить в открытом виде)
smtp_tls_security_level=encrypt
smtp_tls_session_cache_database=btree:$data_directory/smtp_tls_session_cache
smtp_tls_CAfile=/etc/ssl/demoCA/cacert.pem
smtp_tls_key_file=/etc/ssl/foo-key.pem
smtp_tls_cert_file=/etc/ssl/foo-cert.pem
smtp_tls_session_cache_timeout=3600s
smtp_tls_protocols=!TLSv1.2
smtp_tls_loglevel=1
#строка smtpd_tls_security_level=encrypt отвечает за отправку почту только через ssl, если сервер не поддерживает приём почты через ssl, тогда необходимо поставить smtpd_tls_security_level=may(если сервер не поддерживает ssl, то отправить в открытом виде)
smtpd_tls_security_level=encrypt
smtpd_use_tls=yes
smtpd_tls_auth_only=yes
smtpd_tls_loglevel=1
smtpd_tls_received_header=yes
smtpd_tls_session_cache_timeout=3600s
smtpd_tls_session_cache_database=btree:$data_directory/smtpd_tls_session_cache
smtpd_tls_key_file=/etc/ssl/foo-key.pem
smtpd_tls_cert_file=/etc/ssl/foo-cert.pem
smtpd_tls_CAfile= /etc/ssl/demoCA/cacert.pem
smtpd_tls_protocols=!TLSv1.2
#Путь до устройства генератора случайных чисел
tls_random_source=dev:/dev/urandom
#Обратная совместимость
compatibility_level = 2
#Сообщить клиенту о том, что почта не отклонена, а необходимо отправит ее ещё раз, но немного позже
soft_bounce = no
#Системная учётная запись UNIX из по которой запускается и работает postfix
mail_owner = postfix
#Имя хоста на котором развёрнут postfix(в данном примере имя домена и имя хоста совпадают)
myhostname = $mydomain
#В данном параметре необходимо указать имя домена
mydomain = virusslayer.su
myorigin = $myhostname
#Какие интерфейсы необходимо использовать
inet_interfaces = all
#Список доменов на которые будет осуществляться доставка почты
mydestination = $mydomain, localhost, localhost.$mydomain
#Отправляет код ответа 550 отправителю который пытается отправить письмо не существующему пользователю
unknown_local_recipient_reject_code = 550
#пересылать почту только от localhost
mynetworks_style = host
#В данном параметре не нужно не чего указывать, так-как подсети указанные в данном параметре будут считаться привилегированными
mynetworks =
#Версия протокола ip
inet_protocols = ipv4
#Алиасы локальных пользователей(если конечно это необходимо)
alias_maps = hash:/etc/mail/aliases
alias_database = dbm:/etc/mail/aliases.db
#Данным сообщением сервер будет представляться при отправке и получении почты
smtpd_banner = $myhostname ESMTP $mail_name
#Указать на сколько подробным должен быть отчёт
debug_peer_level = 2
#Указать между какими доменами отслкживать пересылку (для записи в лог, можно указать например yandex.ru gmail.ru mail.ru и т.д.)
debug_peer_list = 127.0.0.1
#Путь до отладчика
debugger_command =
PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin
ddd $daemon_directory/$process_name $process_id & sleep 5
#Совместимость с sendmail
sendmail_path = /usr/local/sbin/sendmail
mailq_path = /usr/local/bin/mailq
setgid_group = maildrop
#Пути до различных каталогов
html_directory = /usr/local/share/doc/postfix
manpage_directory = /usr/local/man
sample_directory = /usr/local/etc/postfix
readme_directory = /usr/local/share/doc/postfix
meta_directory = /usr/local/libexec/postfix
shlib_directory = /usr/local/lib/postfix
queue_directory = /var/spool/postfix
command_directory = /usr/local/sbin
daemon_directory = /usr/local/libexec/postfix
data_directory = /var/db/postfix
Dovecot
dovecot.conf
#Протоколы с которыми будет работать dovecot
protocols = imap pop3
#Какие адреса необходимо слушать
listen = *, ::
#Путь до файла с параметрами извлечения квот из mysql
dict {
quota = mysql:/usr/local/etc/dovecot/dovecot-dict-sql.conf.ext
}
#Извлечь необходимые конфиги
!include conf.d/*.conf
!include_try local.conf
dovecot-dict-sql.conf.ext
connect = host=127.0.0.1 dbname=postfix user=postfix password=password123
map {
pattern = priv/quota/storage
table = quota2
username_field = username
value_field = bytes
}
map {
pattern = priv/quota/messages
table = quota2
username_field = username
value_field = messages
}
dovecot-sql.conf.ext
#Параметры подключения к базе MYSQL
driver = mysql
connect = host=127.0.0.1 dbname=postfix user=postfix password=password123
#Какая схема используется для паролей
default_pass_scheme = MD5
#Запросы для пользователей, паролей и квот
user_query = SELECT '/var/mail/%d/%n/' AS home, 'maildir:/var/vmail/%d/%n' AS mail, 1000 AS uid, 1000 AS gid, concat('*:bytes=',quota) as quota_rule FROM mailbox
WHERE username ='%u' AND active = '1'
password_query = SELECT username as user, password, '/var/vmail/%d/%n' as userdb_home, 'maildir:/var/vmail/%d/%n' as userdb_mail, 1000 as userdb_uid,
1000 as userdb_gid, concat('*:bytes=',quota) AS userdb_quota_rule FROM mailbox WHERE username ='%u' AND active ='1'
10-auth.conf
#Запретить авторизацию без SSL
disable_plaintext_auth = yes
#Имя Вашего домена
auth_realms = virusslayer.su
auth_default_realm = virusslayer.su
#Использовать авторизацию в открытом виде(обычным текстом, но в данном случаи все будете передаваться через ssl)
auth_mechanisms = plain login
#Необходимо закомментировать все строки, кроме !include auth-sql.conf.ext, так как пользователи будут виртуальные из базы mysql
#!include auth-deny.conf.ext
#!include auth-master.conf.ext
#!include auth-system.conf.ext
!include auth-sql.conf.ext
#!include auth-ldap.conf.ext
#!include auth-passwdfile.conf.ext
#!include auth-checkpassword.conf.ext
#!include auth-vpopmail.conf.ext
#!include auth-static.conf.ext
10-mail.conf
#Путь до почтовых ящиков
mail_location = maildir:/var/vmail/%d/%n
#Возможен только один ящик для приёма писем
namespace inbox {
inbox = yes
}
#uid и gid vmail
mail_uid = 1000
mail_gid = 1000
#Список плагинов, в данном случаи quota
mail_plugins = quota
10-master.conf
#Описание номеров портов и использование ssl
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 submission-login {
inet_listener submission {
port = 587
}
}
#Пользователи и права для их доступа к базе пользователей и авторизации (возможно не корректно описал, но эти параметры я понял именно так)
service auth {
unix_listener auth-userdb {
mode = 0600
user = vmail
group = vmail
}
# Postfix smtp-auth
unix_listener /var/spool/postfix/private/auth {
mode = 0666
user = postfix
group = postfix
}
}
#Права пользователя vmail к квотам
service dict {
unix_listener dict {
mode = 0660
user = vmail
group = vmail
}
}
10-ssl.conf
#Использовать ssl принудительно (попытки использовать авторизацию без sll будут запрещены)
ssl = required
#Пути до сертификатов
ssl_cert = </etc/ssl/foo-cert.pem
ssl_key = </etc/ssl/foo-key.pem
ssl_ca = </etc/ssl/demoCA/cacert.pem
#Какой необходимо использовать протокол
ssl_min_protocol = TLSv1.2
15-lda.conf
quota_full_tempfail = no
lda_mailbox_autosubscribe = yes
protocol lda {
# This line specifies the sieve module, which will redirect spam to the spam folder
mail_plugins = $mail_plugins sieve quota
}
90-plugin.conf
#Необходимо указать каталог в котором будут правила для переноса спам писем в каталог "СПАМ", также необходимо данному каталогу выставить права chown -R vmail:vmail
#В данном каталоге скомпилируется файл для переброса спама в каталог "СПАМ"
plugin {
#setting_name = value
sieve = /usr/local/etc/dovecot/conf.d/def/default.sieve
}
auth-sql.conf.ext
#Файлы с настройками доступа к базе MYSQL
passdb {
driver = sql
# Path for SQL configuration file, see example-config/dovecot-sql.conf.ext
args = /usr/local/etc/dovecot/dovecot-sql.conf.ext
}
userdb {
driver = sql
args = /usr/local/etc/dovecot/dovecot-sql.conf.ext
}
Spamassassin
The spamassassin configuration looks like this, but something tells me these settings are not sufficient, please assist with this configuration:
local.cf
rewrite_header Subject *****SPAM*****
report_safe 0
required_score 5.0
use_bayes 1
bayes_auto_learn 1
ifplugin Mail::SpamAssassin::Plugin::Shortcircuit
endif # Mail::SpamAssassin::Plugin::Shortcircuit
It is also necessary to train on emails both with spam and without:
sa-learn --spam /path/spam/folder
sa-learn --ham /path/ham/folder
Additional
In this section, I will specify the firewall settings based on pf, we will add pf to auto-start and specify the file with the rules:
sysrc pf_enable="YES"
sysrc pf_rules="/etc/0.pf"
We will create a file with the rules:
ee /etc/0.pf
And we will add the rules to it:
#Данный параметр(не фильтровать интерфейс lo0) обязательно необходимо указывать первым, или он не сработает
set skip on lo0
#Настроим доступ к необходимым портам пользователям deovecot, postfix, root
pass in quick proto { tcp, udp } from any to any port {53,25,465,587,110,143,993,995} user {dovecot,postfix,root} flags S/SA modulate state
pass out quick proto { tcp, udp } from any to any port {53,25,465,587,110,143,993,995} user {dovecot,postfix,root}
#разрешить любой исходящий трафик для пользователя root
pass out quick proto {tcp,udp} from any to any user root
#Разрешить заходить на вэб интерфейс
pass in quick proto tcp from any to any port 80 flags S/SA modulate state
#SSH
pass in quick proto tcp from any to any port 22 flags S/SA modulate state
#Разрешить доступ в сеть пользователям clamav и spamd
pass out quick proto {tcp,udp} from any to any user {clamav,spamd}
#DNS и ICMP
pass out quick proto {tcp,udp} from any to any port=53 keep state
pass out quick proto icmp from any to any
block from any to any fragment
block from any to any
block all
pf can be started with the command:
service pf start
Testing
To test all possible connections (STARTTLS, SSL), you can use a mobile client (in my case for iOS) "MyOffice Mail", in this application there are many parameters for configuring connections to the mail server.
To test Spamassassin, use the GTUBE signature, add the following line to the email:
XJS*C4JDBQADN1.NSBN3*2IDNEN*GTUBE-STANDARD-ANTI-UBE-TEST-EMAIL*C.34X
If everything is correct, the email will be marked as spam and correspondingly moved to the spam folder.
To test the antivirus, you need to send an email with a text file that contains the EICAR string:
X5O!P%@AP[4PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*
Naturally, emails need to be sent from external mailboxes.
To view logs in real time, run:
tail -f /var/log/maillog
For proper testing of email delivery to external mailboxes (e.g., yandex.ru, mail.ru, gmail.com, etc.), it is necessary to configure the reverse DNS zone (PTR record). This can be done by contacting your provider (unless you have your own DNS server).
Output
It may seem that setting up a mail server is quite complicated, but if you take the time to configure it, you can achieve a highly functional mail server with protection against spam and viruses.
P.S. If you plan to 'copy-paste' with comments, you need to add the root user (and those who need it) to the logs class russian:
pw usermod root -L russian
After these actions, Russian characters will be displayed correctly.
Source: habr.com
