Огляд
											
										
																			
											
												Початкове налаштування
											
										
																			
											
												Налаштування брандмауера
											
										
																			
											
												OpenSMTPd
											
										
																			
											
												Налаштування spamd
											
										
																			
											
												Голубятня
											
										
																			
											
												Висновок
											
										
																	
												
Запуск власного сервера електронної пошти може бути дуже корисним. Ви відповідаєте за свої дані. Це також надає вам більшу гнучкість щодо варіантів доставки. Однак є кілька проблем. Ви ризикуєте відкрити свій сервер для виявлення вразливостей, а також зробити його потенційним ретранслятором для спамерів.
Покінчивши з цим, давайте перейдемо до роботи нашого власного поштового сервера.
Огляд
Є три необхідні частини програмного забезпечення для встановлення, які не включені в базову систему FreeBSD: 
- OpenSMTPd
- Голубятня
- spamd
OpenSMTPd — це агент передачі пошти (MTA) і агент доставки пошти (MDA). Це означає, що він може спілкуватися з іншими поштовими серверами за SMTPпротоколом, а також обробляє доставку пошти до поштових скриньок окремих користувачів. Ми налаштуємо OpenSMTPd, щоб він міг зв’язуватися із зовнішніми серверами (відфільтрований через spamd) і доставляти пошту локальним користувачам, а також доставляти локальну пошту від користувача до користувача.
Dovecot — це MDA, який зчитує локальні поштові скриньки та обслуговує їх користувачам через IMAP або POP3. Він використовуватиме поштові скриньки локальних користувачів для обслуговування цього вмісту.
Spamd — це служба фільтрації пошти. Ми можемо пересилати пошту через spamd, і вона фільтруватиме пошту на основі різноманітних чорних, білих та сірих списків.
Загальна ідея для цього поштового сервера вимагає кількох різних шляхів:
Outside world -> Firewall -> spamd -> OpenSMTPD -> User mail boxes
Outside world -> Firewall (spamd-whitelist) -> OpenSMTPD -> User mailboxes
Outside world -> Firewall (IMAP/POP3) -> Dovecot
Outside world -> Firewall (SMTPD submission)
У цьому підручнику ми будемо використовувати FreeBSD версію PF OpenBSD для нашого брандмауера. Ви також можете використовувати ipfw, де конфігурація дуже схожа.
Примітка:  Vultr за замовчуванням блокує порт 25, який використовується SMTP-серверами всюди. Якщо ви хочете запустити повністю функціональний сервер електронної пошти, вам доведеться відкрити цей порт.
Початкове налаштування
Спочатку нам потрібно встановити необхідні програми.
Припускаючи, що ви працюєте як користувач із налаштованим доступом sudo, ми можемо запустити наступні команди. Вони будуть відрізнятися залежно від того, чи використовуєте ви порти чи пакети.
Пакети (рекомендовано)
Якщо вам не потрібні спеціальні функції, вбудовані в ці утиліти, рекомендується встановлювати їх через пакети. Це простіше, займає менше часу та ресурсів сервера, а також забезпечує інтуїтивно зрозумілий, зручний інтерфейс.
sudo pkg install opensmtpd dovecot spamd
Наступні makeкоманди нададуть вам багато параметрів компіляції, стандартні параметри працюватимуть нормально. Не змінюйте їх, якщо ви точно не знаєте, що робите.
sudo portsnap fetch update   # or run portsnap fetch extract if using ports for the first time
cd /usr/ports/mail/opensmtpd  
make install  # Installs openSMTPd
make clean
cd /usr/ports/mail/dovecot
make install  # Installs dovecot
make clean
cd /usr/ports/mail/spamd
make install  # Installs spamd
make clean
Нам потрібно буде додати наступні рядки до /etc/rc.conf:
pf_enable="YES"
pf_rules="/usr/local/etc/pf.conf"
pflog_enable="YES"
pflog_logfile="/var/log/pflog"
obspamd_enable="YES"
obspamd_flags="-v"
obspamlogd_enable="YES"
dovecot_enable="YES"
Налаштування брандмауера
Щоб налаштувати PF, ми можемо створити наш /usr/local/etc/pf.conf:
## Set public interface ##
ext_if="vtnet0"
## set and drop IP ranges on the public interface ##
martians = "{ 127.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12, \
          10.0.0.0/8, 169.254.0.0/16, 192.0.2.0/24, \
          0.0.0.0/8, 240.0.0.0/4 }"
table <spamd> persist
table <spamd-white> persist
# Whitelisted webmail services
table <webmail> persist file "/usr/local/etc/pf.webmail.ip.conf"
## Skip loop back interface - Skip all PF processing on interface ##
set skip on lo
## Sets the interface for which PF should gather statistics such as bytes in/out and packets passed/blocked ##
set loginterface $ext_if
# Deal with attacks based on incorrect handling of packet fragments 
scrub in all
# Pass spamd whitelist
pass quick log on $ext_if inet proto tcp from <spamd-white> to $ext_if port smtp \
    -> 127.0.0.1 port 25
# Pass webmail servers
rdr pass quick log on $ext_if inet proto tcp from <gmail> to $ext_if port smtp \
    -> 127.0.0.1 port 25
# pass submission messages.
pass quick log on $ext_if inet proto tcp from any to $ext_if port submission modulate state
# Pass unknown mail to spamd
rdr pass log on $ext_if inet proto tcp from {!<spamd-white> <spamd>} to $ext_if port smtp \
    -> 127.0.0.1 port 8025 
## Blocking spoofed packets
antispoof quick for $ext_if
## Set default policy ##
block return in log all
block out all
# Drop all Non-Routable Addresses 
block drop in quick on $ext_if from $martians to any
block drop out quick on $ext_if from any to $martians
pass in inet proto tcp to $ext_if port ssh
# Allow Ping-Pong stuff. Be a good sysadmin 
pass inet proto icmp icmp-type echoreq
# Open up imap/pop3 support
pass quick on $ext_if proto tcp from any to any port {imap, imaps, pop3, pop3s} modulate state
# Allow outgoing traffic
pass out on $ext_if proto tcp from any to any modulate state
pass out on $ext_if proto udp from any to any keep state
Це робоча конфігурація PF. Це відносно просто, але є кілька примх, які потрібно пояснити.
По-перше, ми визначаємо нашу $ext_ifзмінну для нашого vtnet0пристрою для подальшого використання. Ми також визначаємо недійсні IP-адреси, які слід видалити на зовнішньому інтерфейсі.
Ми також визначаємо дві таблиці, spamdі spamd-white- ці дві таблиці створюються spamd у його конфігурації за замовчуванням. Крім того, ми визначаємо таблицю з іменем, webmailяку ми використовуватимемо, щоб дозволити деяким основним постачальникам веб-пошти доступ.
Щоб переглянути таблицю, ви можете скористатися командою pfctl -t tablename -T showдля перерахування елементів таблиці.
Ми встановили кілька правил PF: пропустити обробку на локальному інтерфейсі, включити статистику на зовнішньому інтерфейсі та очистити вхідні пакети.
Далі йде одна з найважливіших частин, де ми керуємо відправкою нашого трафіку через spamd або OpenSMTPd.
По-перше, це правило переспрямування (зверніть увагу на синтаксис тут, FreeBSD 11 використовує старіший синтаксис PF стилю (до OpenBSD 4.6), тому синтаксис може здатися дивним. Якщо ми отримуємо що-небудь на smtp від хоста, переліченого в spamdтаблиці або не зазначеного в spamd-whiteстіл, ми перенаправляти з'єднання через до spamd демона, який має справу з цими сполуками. наступні три правила є PASSTHROUGH правила , так що ми можемо реально отримувати пошту. ми проходимо через повідомлення з IP - адрес , перерахованих в spamd-whiteі webmailтаблицях прямо через OpenSMTPd Крім того, ми приймаємо повідомлення через порт подання ( 587).
Потім є кілька правил ведення господарства, щоб встановити нашу політику за замовчуванням і прийняти повідомлення SSH і ICMP.
Потім ми передаємо IMAP і POP3 через наш зовнішній інтерфейс, щоб отримати доступ до Dovecot.
Нарешті, ми дозволяємо весь вихідний трафік. Якщо ви хочете додати додатковий захист, ви можете обмежити порти, які ви передаєте, але для одноразового сервера не проблема передати все.
Початок PF:
sudo service pf start
Тепер, коли ми налаштували брандмауер, ми можемо перейти до конфігурації нашого поштового сервера.
OpenSMTPd
OpenSMTPd має дуже простий і легкий для читання синтаксис конфігурації. Повна робоча конфігурація може поміститися в 14 рядків, як ви можете побачити нижче:
#This is the smtpd server system-wide configuration file.
# See smtpd.conf(5) for more information.
ext_if=vtnet0
# If you edit the file, you have to run "smtpctl update table aliases"
table aliases   file:/etc/mail/aliases
table domains   file:/etc/mail/domains
# Keys
pki mail.example.com key "/usr/local/etc/letsencrypt/live/mail.example.com/privkey.pem"
pki mail.example.com certificate "/usr/local/etc/letsencrypt/live/mail.example.com/fullchain.pem"
# If you want to listen on multiple subdomains (e.g. mail.davidlenfesty) you have to add more lines
# of keys, and more lines of listeners
# Listen for local SMTP connections
listen on localhost hostname mail.example.com
# listen for filtered spamd connections
listen on lo0 port 10026
# Listen for submissions
listen on $ext_if port 587 tls-require auth pki mail.example.com tag SUBMITTED
# Accept mail from external sources.
accept from any for domain <domains> alias <aliases> deliver to maildir "~/mail"
accept for local alias <aliases> deliver to maildir "~/mail"
accept from local for any relay tls
accept tagged SUBMITTED for any relay tls
По-перше, ми знову визначаємо наш зовнішній інтерфейс, а також кілька таблиць, псевдонімів і доменів. Потім ми переходимо до ключа та сертифіката SSL для будь-яких доменів, під якими ми хочемо обробляти пошту.
In the next section, we define the interfaces and ports we want to listen on. Firstly, we listen on localhost for our mail.example.com domain, for any local connections. Then we listen for our spamd-filtered messages and submitted messages on the external interface. Lastly, we listen for submissions, these happen on port 587 and we are requiring them to authenticate, for security reasons.
Lastly are our accept settings. We accept any message for any of our domains defined in our domains table for aliases in our aliases table, to deliver to their home directory in the maildir format. Then we accept all local connections for local mailboxes and relay out our messages, so we can send email. Lastly, we accept our submitted messages to relay. If we didn't require authentication for our submissions port, this would be a big security hazard. This would let anyone use our server as a spam relay.
Aliases
FreeBSD ships with a default alias file /etc/mail/aliases in the following format:
vuser1:  user1
vuser2:  user1
vuser3:  user1
vuser4:  user2
This defines the different mail boxes, and where we want to forward messages sent to these defined mailboxes. We can either define our users as local system users or external mailboxes to forward to. The default FreeBSD file is quite descriptive so you can refer to that for reference.
Domains
FreeBSD does not supply a default domains file, but this is incredibly simple:
# Domains
example.com
mail.example.com
smtp.example.com
This is just a plain text file with each domain you want to listen to on a new line. You can make a comment using the # symbol. This file exists simply so that you can use fewer lines of configuration.
SSL Certificates
There are two ways to be able to secure your communications with your mail server, self-signed and signed certificates. It is certainly possible to self-sign your certificates, however services like Let's Encrypt provide free and incredibly easy to use signing.
First we have to install the certbot program.
sudo pkg install py-certbot
Alternatively, it can be installed with ports:
cd /usr/ports/security/py-certbot
make install
make clean
Then, to get your certificate, you need to make sure you have opened up port 80 on your external interface. Add the following lines somewhere in your filtering rules in /usr/local/etc/pf.conf: 
pass quick on $ext_if from any to any port http
Then run pfctl -f /usr/local/etc/pf.conf to reload the ruleset.
Then you can run the command for any domains you want to get a certificate for:
certbot certonly --standalone -d mail.example.com
It is recommended to set up a crontab entry to run certbot renew once every 6 months to ensure your certificates don't expire.
Then for every relevant domain, you can modify the lines to point to the correct key file:
pki mail.example.com key "/usr/local/etc/letsencrypt/live/mail.example.com/privkey.pem"
pki mail.example.com certificate "/usr/local/etc/letsencrypt/live/mail.example.com/fullchain.pem"
Edit the securities:
sudo chmod 700 /usr/local/etc/letsencrypt/archive/mail.example.com/*
Note: You will have to do this for each original keyfile or else OpenSMTPd won't open them.
Now we can start the service:
sudo service smtpd start
Configuring spamd
Here we are using OpenBSD's spamd daemon to reduce the amount of spam we get from the internet. Essentially, this filters out messages from IPs that are known as bad from various spam sources, as well as (by default) "greylisting" incoming connections. Spamd also tries to waste spammer's timme by "stuttering" blacklisted and greylisted connections, which means it spreads out it's response over several seconds which forces the client to stay open for longer than usual.
Greylisting a connection is done when any new IP address connects that isn't on any blacklist or whitelist. Once the new address connects, spamd drops the message with an inocuous error message, then it adds it to a temporary list. Because spammers get paid for delivered messages, they will not retry on an error, whereas a legitimate service will retry relatively soon.
You will have to run the following to mount fdescfs:
mount -t fdescfs null /dev/fd
Then you will have to add this line to /etc/fstab:
fdescfs     /dev/fd     fdescfs rw      0       0
The default config file (found in /usr/local/etc/spamd/spamd.conf.sample) will work fine. You can edit it to add new sources or change the sources you use:
sudo cp /usr/local/etc/spamd/spamd.conf.sample /usr/local/etc/spamd/spamd.conf
We can start the service with the following:
sudo service obspamd start
At this point spamd is set up.
Enabling Webmail Services
One problem with the greylisting approach is that large mail services will often send mail out through one of many different spools, and you aren't guaranteed to get the same server sending the message every time. One solution to this is to whitelist the IP ranges used by various webmail services. This is what the webmail table is used for in the PF configuration. This strategy can backfire if you include an IP address a spammer uses, but as long as you are careful with what ranges you put in the table you will be fine.
To add an email range to the webmail table, you can run the following command:
pfctl -t webmail -T add 192.0.2.0/24
Dovecot
If you want users to access their mail without logging in via SSH, you'll need an MDA that supports IMAP and/or POP3. A very popular program is Dovecot, with a fairly simple configuration and powerful features.
Ми можемо скопіювати конфігурацію за замовчуванням:
cd /usr/local/etc/dovecot
cp -R example-config/* ./
Конфігурація складається з кількох різних файлів. Щоб побачити відмінності між вашою конфігурацією та налаштуваннями голубятни за замовчуванням, виконайте команду нижче:
sudo doveconf -n
Нижче наведена проста робоча конфігурація:
# 2.3.2.1 (0719df592): /usr/local/etc/dovecot/dovecot.conf
# OS: FreeBSD 11.2-RELEASE amd64  
# Hostname: mail.example.com
hostname = mail.example.com
mail_location = maildir:~/mail
namespace inbox {
  inbox = yes
  location = 
  mailbox Archive {
    auto = create
    special_use = \Archive
  }
  mailbox Archives {
    auto = create
    special_use = \Archive
  }
  mailbox Drafts {
    auto = subscribe
    special_use = \Drafts
  }
  mailbox Junk {
    auto = create
    autoexpunge = 60 days
    special_use = \Junk
  }
  mailbox Sent {
    auto = subscribe
    special_use = \Sent
  }
  mailbox "Sent Mail" {
    auto = no
    special_use = \Sent
  }
  mailbox "Sent Messages" {
    auto = no
    special_use = \Sent
  }
  mailbox Spam {
    auto = no
    special_use = \Junk
  }
  mailbox Trash {
    auto = no
    autoexpunge = 90 days
    special_use = \Trash
  }
  prefix = 
  separator = /
}
passdb {
  args = imap
  driver = pam
}
ssl = required
ssl_cert = </usr/local/etc/letsencrypt/live/mail.example.com/fullchain.pem
ssl_dh = </usr/local/etc/dovecot/dh.pem
ssl_key = </usr/local/etc/letsencrypt/live/mail.example.com/privkey.pem
userdb {
  driver = passwd
}
Більшість файлів конфігурації буде в conf.d
Важливими з них є 10-auth.conf, 10-mail.conf, і 10-ssl.conf.
Ви можете налаштувати різні поштові скриньки, які ви використовуєте в 15-mailboxes.conf. Те, що ви бачите вище, є хорошою конфігурацією для багатьох систем, але ваш пробіг може відрізнятися. Рекомендується пограти з якомога більшою кількістю різних клієнтів.
Аутентифікація
Більшість налаштувань за замовчуванням буде правильним. Якщо ви хочете використовувати користувачів системи для аутентифікації, вам доведеться відредагувати 10-auth.conf.
Розкоментуйте наступний рядок:
!включити auth-system.conf.ext
Шифрування
Ми повинні згенерувати параметри Діффі-Хеллмана:
sudo nohup openssl dhparam -out /usr/local/etc/dovecot/dh.pem
Примітка.  Це займе багато часу. Набагато довше, ніж ви могли очікувати.
Тепер ми можемо запустити Dovecot:
sudo service dovecot start
Висновок
На даний момент ми маємо функціональний, безпечний і відносно вільний від спаму поштовий сервер.
Ще деякі речі, на які варто ознайомитися звідси, — це використання SpamAssassin для евристичного позбавлення від спаму, а також пошук додаткових чорних списків спаму, опублікованих джерелами, яким ви довіряєте.