postfix+dovecot+mysql on FreeBSD

Introduction

I wanted to study the mail server for a long time, but I only got my hands on it now, and I didn’t manage to find much correct information, so I decided to write as detailed a publication as possible. This publication will discuss not only postfix, dovecot, mysql, postfixadmin, but also spamassassin, clamav-milter (a special version of clamav for mail servers), postgrey, as well as the possibility of moving spam to the Spam folder (dovecot- pigeon hole).

Prepare

First of all, we will install the packages that will be needed for work (postfix, dovecot and dovecot-pigeonhole must be installed from ports, dovecot-sieve can in principle be installed from packages, but there are newer versions in ports and for this reason dovecot may not be compatible with dovecot- sieve). Let's 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 put the necessary services in 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
#Перед запуском spamassassin необходимо обновить базы и скомпилировать правила
sa-update
sa-compile
service sa-spamd start
#Выполните обновления баз clamav перед запуском
freshclam
service clamav-clamd start
service clamav-freshclam start
service clamav-milter start
#Перед запуском postgrey необходимо отредактировать скрип инициализации(/usr/local/etc/rc.d/postgrey), для того чтобы отправители переносились в "белый" список после 4-х попыток отправки писем, необходимо найти строку : ${postgrey_flags:=--inet=10023} и привести её к виду:
: ${postgrey_flags:=--inet=10023 --auto-whitelist-clients=4}
service postgrey start

Do not forget to add the lines necessary for php to work in apache and postfixadmin to work correctly in httpd.conf:

<FilesMatch ".php$">
    SetHandler application/x-httpd-php
</FilesMatch>
<FilesMatch ".phps$">
    SetHandler application/x-httpd-php-source
</FilesMatch>

<IfModule dir_module>
    DirectoryIndex index.php
</IfModule>

#А также необходимо изменить домашний каталог для корректной работы postfixadmin

DocumentRoot "/usr/local/www/apache24/data/postfixadmin-3.2/public"

Next, you need to go to the directory and download postfixadmin

cd /usr/local/www/apache24/data

Download postfixadmin (at 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, you need to unpack the archive into this directory and change the owner of the directory:

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, prepare the database for postfixadmin, run the mysql-secure-installation script (the password that you create in this script will need to be created in mysql with the alter user command), for the initial mysql setup, then enter mysql, create a database and rights for her:

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

After the database is configured, you need to edit the config.inc.php file, in this example, this file is located in the /usr/local/www/apache24/data/postfixadmin-3.2/ directory, you need to edit several lines in this file and bring them to As you can see, after changing the configuration data, restart apache, you also need to create the templates_c directory in the /usr/local/www/apache24/data/postfixadmin-3.2 directory and assign the www owner to it:

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
#данный хэш необходимо сгенерировать в вэб интерфейсе postfixadmin и добавить в данную строку.
$CONF['setup_password'] = 'dd28fb2139a3bca426f02f60e6877fd5:13d2703c477b0ab85858e3ac5e076a0a7a477315';
$CONF['default_language'] = 'ru'
$CONF['database_type'] = 'mysqli';
$CONF['database_host'] = 'localhost';
$CONF['database_user'] = 'postfix';
#Пароль и имя баз данных использую которые создал в данном примере
$CONF['database_password'] = 'password123';
$CONF['database_name'] = 'postfix';

service apache24 restart

SSL

To generate the key, we will use the method proposed on the postfix.org website, with the creation of our own certification authority, you must go to the /etc/ssl directory and execute the script:

cd /etc/ssl
/usr/local/openssl/misc/CA.pl -newca

During the execution of the script, a name for the certificate will be requested, do not enter anything, press Enter, then the script will ask you to create a password for the certificate, then there will be standard questions for creating a certificate.

Next, you need to create a private key (without a password) and an unsigned public key certificate (Organizational Unit Name (eg, section) [] must be different from what is specified in the certificate created above):

openssl req -new -newkey rsa:4096 -nodes -keyout foo-key.pem -out foo-req.pem

Let's sign a public key certificate (specify the number of days as much as you need):

openssl ca -out foo-cert.pem -days 365 -infiles foo-req.pem

Leave the created certificates in this directory, or transfer them to the directory that is more convenient for you, the postfix and dovecote “configs” will be configured taking into account that the certificates will be located in this directory.

vmail user

Before proceeding with the installation of postfix, dovecot and dovecot-pigeonhole, let's create a user and group (the group will be created automatically) vmail, as well as a directory in which the mail will be located.

pw useradd -n vmail -s /usr/sbin/nologin -u 1000 -d /var/vmail

Let's create a directory for mail and assign 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 wrote earlier, we will assemble application data from ports, run the command to download and unpack the ports:

portsnap fetch extract

Once the ports have been unpacked, change to the dovecot directory, configure the port (you need to check mysql support), and run 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

Do the same with postfix and dovecot-pigeonhole

dovecot-pigeonhole:

cd /usr/ports/mail/dovecot-pigeonhole
make BATCH=yes install clean

postfix: also check the port setting to support mysql

cd  /usr/ports/mail/postfix-sasl
make config
make BATCH=yes install clean

Before running dovecot, copy the "configs":

 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 in which the module will be compiled to send spam to the spam folder, in my case this directory is located in the /usr/local/etc/dovecot/conf.d folder, the name of the directory is def, let's create this directory and a file with the 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

In this file put the lines:

require "fileinto";
if header :contains "X-Spam-Flag" "YES" {
    fileinto "Junk";
}

"Configs"

In this section I will give examples of “configs” with comments in them, I doubt only the “config” of spamassassin, since I did not find the correct descriptions on the network (I left the “config” by default), please add in the comments how best to configure spamassassin.

Postfix

The first step is to create files to pull users, domains, quotas from the database. Create a directory to store 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 content 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 {
# В данной строке указан модуль sieve, который будет перенаправлять спам в папку спам
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 “config” of spamassassin looks like this, but something tells me that the configuration data is not enough, please help with the “config” data:

site.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 with and without spam:

sa-learn --spam /path/spam/folder
sa-learn --ham /path/ham/folder

Additionally

In this section, I will specify the pf-based firewall settings, add pf to autorun, and specify the file with the rules:

sysrc pf_enable="YES"
sysrc pf_rules="/etc/0.pf"

Let's create a file with rules:

ee /etc/0.pf

And add 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

You can start pf with the command:

service pf start

The test is

To test all possible connections (STARTTLS, SLL), you can use the client for mobile devices (in my case for ios) "MyOffice Mail", this application has many options for setting up connections to the mail server.

To test spaassasin, we 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 message will be marked as spam and accordingly moved to the spam folder.

To test the antivirus, you need to send an email with a text file, this file will contain the EICAR sequence:

X5O!P%@AP[4PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*

Letters naturally need to be sent from external mailboxes.
To view logs in real time, run:

tail -f /var/log/maillog

Also, in order to correctly test sending mail to external mailboxes (for example, to yandex.ru, mail.ru, gmail.com, etc.), you need to register a reverse DNS zone (PTR record), you can do this by contacting your provider (if you certainly do not have your own DNS server).

Hack and predictor Aviator

Of course, it may seem that the mail server is a rather complicated thing, but if you figure it out, this is not at all the case; spending a little time on the configuration, you can get a fairly functional mail server, with spam and virus protection.

PS If you plan to "copy-paste" with comments, then you need to add the root user (and those who need it) to the russian class logs:

pw usermod root -L russian

After these steps, Russian characters will be displayed correctly.

Source: habr.com

Add a comment