Product SiteDocumentation Site

Глава 11. Сетевые сервисы: Postfix, Apache, NFS, Samba, Squid, LDAP, SIP, XMPP, TURN

11.1. Почтовый сервер
11.1.1. Установка почтового сервера Postfix
11.1.2. Настройка Виртуальных доменов
11.1.3. Restrictions for Receiving and Sending
11.1.4. Setting Up greylisting
11.1.5. Customizing Filters Based On the Recipient
11.1.6. Integrating an Antivirus Filter
11.1.7. Fighting Spam with SPF, DKIM and DMARC
11.1.8. Аутентифицированный SMTP
11.2. Web сервер (HTTP)
11.2.1. Установка Apache
11.2.2. Добавление поддержки SSL
11.2.3. Настройка виртуальных хостов
11.2.4. Общие директивы
11.2.5. Анализаторы журналов
11.3. FTP File Server
11.4. NFS File Server
11.4.1. Усиление безопасности NFS
11.4.2. NFS Server
11.4.3. NFS клиент
11.5. Настройка общих ресурсов Windows с помощью Samba
11.5.1. Samba Server
11.5.2. Samba клиент
11.6. HTTP/FTP Proxy
11.6.1. Установка
11.6.2. Настройка кэша
11.6.3. Настройка фильтра
11.7. LDAP каталог
11.7.1. Установка
11.7.2. Filling in the Directory
11.7.3. Управление учетными записями с помощью LDAP
11.8. Сервисы связи реального времени
11.8.1. Настройки DNS для служб RTC
11.8.2. TURN Сервер
11.8.3. SIP Proxy Сервер
11.8.4. XMPP Сервер
11.8.5. Запуск служб на порту 443
11.8.6. Добавление WebRTC
Сетевые сервисы — это программы, с которыми пользователи взаимодействуют непосредственно в своей повседневной работе. Это верхушка айсберга информационной системы, и данная глава посвящена им; скрытые части, на которые они полагаются, — это инфраструктура, которую мы уже описали. Обычно для них требуется технология шифрования, описанная в Раздел 10.2, «X.509 certificates».

11.1. Почтовый сервер

Администраторы Falcot Corp выбрали Postfix в качестве сервера электронной почты, благодаря его надежности и легкости в конфигурации. Действительно, он спроектирован так, что каждая задача реализована в процессе с минимальным набором требуемых разрешений, что является значительной мерой против влияния проблем безопасности.

11.1.1. Установка почтового сервера Postfix

Пакет postfix содержит основной демон SMTP . Другие пакеты (такие как postfix-ldap и postfix-pgsql) дополняют функциональность Postfix, включая доступ к отображаемым базам данных. Устанавливайте их только в том случае, если Вы знаете, что они Вам нужны.
Во время установки пакета утилита Debconf задаёт ряд вопросов, ответы на которые используются для генерации первоначальной версии конфигурационного файла /etc/postfix/main.cf.
Первый вопрос касается типа установки. В случае сервера, подключенного к сети Интернет, из предложенных ответов только два имеют отношение к делу – “Internet site” («сайт Интернет») и “Internet with smarthost” («Интернет с ретранслятором»). Первый вариант подходит для сервера, который совершает обмен почтой напрямую с сервером получателя и поэтому хорошо приспособлен для Falcot Corp. Другой вариант подходит для сервера, который получает входящую почту обычным образом, но исходящую почту отправляет через сторонний SMTP-сервер («ретранслятор»), а не напрямую на сервер получателя. Это главным образом нужно для пользователей с динамическими IP-адресами, поскольку множество почтовых серверов не принимает сообщения, исходящие напрямую от таких IP-адресов. В этом случае «ретранслятором» обычно является SMTP-сервер провайдера Интернета. Интернет-провайдеры обычно настраивают свои сервера так, что они принимают почту от их абонентов и соответственным образом пересылают её. Такой вид установки (с «ретранслятором») также подходит для серверов, которые не имеют постоянного подключения к Интернету, поскольку избавляет их от необходимости обслуживать очередь недоставляемых сообщений, требующих повторной отправки.
Второй вопрос касается полного имени машины, которое будет использовано для генерации почтовых адресов из имён локальных пользователей. Полное имя машины является частью адреса после символа «собачка» ("@"). В случае Falcot, ответ должен быть mail.falcot.com. Это единственный вопрос, задаваемый по-умолчанию, однако та конфигурация, которая с его помощью создаётся, не является достаточно полной для нужд Falcot, поэтому администраторы запускают команду dpkg-reconfigure postfix для того, чтобы настроить больше параметров.
Один из дополнительных вопросов касается все доменных имён, относящихся к машине. Список по умолчанию включает полное имя и несколько синонимов для localhost, но основной домен falcot.com нужно добавить вручную. В общем, это все доменные имена, для который машина является MX сервером, другими словами — все доменные имена, для которых в DNS указано, что эта машина принимает электронную почту. Эта информация завершается переменной mydestination в основном конфигурационном файле Postfix /etc/postfix/main.cf.
Роль DNS MX записи в процессе отсылки письма

Рисунок 11.1. Роль DNS MX записи в процессе отсылки письма

В некоторых случаях, при установке будет задан вопрос каким сетям позволено посылать электронную почту через машину. В настройках по умолчанию, Postfix принимает почту только с самой машины, обычно добавляется и локальная сеть. Администраторы корпорации Falcot добавили 192.168.0.0/16 для ответа по умолчанию. Если вопрос не задан, подходящая переменная в конфигурационном файле — mynetworks. Смотрите пример внизу.
Локальная почта может быть доставлена через procmail. Этот команда сортирует входящую почту в соответствии с правилами, хранящимися в файле ~/.procmailrc. И Postfix, и Exim4 предлагают procmail по умолчанию, но есть альтернативы, такие как maildrop или Sieve фильтры.
После этого первого шага администраторы получат следующий конфигурационный файл; он будет использоваться в качестве исходной точки для добавления некоторой дополнительной функциональности в следующих разделах.

Пример 11.1. Initial /etc/postfix/main.cf file

# See /usr/share/postfix/main.cf.dist for a commented, more complete version


# Debian specific:  Specifying a file name will cause the first
# line of that file to be used as the name.  The Debian default
# is /etc/mailname.
#myorigin = /etc/mailname

smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU)
biff = no

# appending .domain is the MUA's job.
append_dot_mydomain = no

# Uncomment the next line to generate "delayed mail" warnings
#delay_warning_time = 4h

readme_directory = no

# See http://www.postfix.org/COMPATIBILITY_README.html -- default to 2 on
# fresh installs.
compatibility_level = 2



# TLS parameters
smtpd_tls_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
smtpd_tls_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
smtpd_tls_security_level=may

smtp_tls_CApath=/etc/ssl/certs
smtp_tls_security_level=may
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache


smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
myhostname = mail.falcot.com
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
mydestination = mail.falcot.com, falcot.com, localhost.localdomain, localhost
relayhost = 
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 192.168.0.0/16
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
default_transport = smtp
relay_transport = smtp
inet_protocols = all
myorigin = /etc/mailname

11.1.2. Настройка Виртуальных доменов

The mail server can receive mails addressed to other domains besides the main domain; these are then known as “virtual“ domains. In most cases where this happens, the emails are not ultimately destined to local users. Postfix provides two interesting features for handling virtual domains.

11.1.2.1. Virtual Alias Domains

A virtual alias domain only contains aliases, i.e. addresses that only forward emails to other addresses.
Such a domain is enabled by adding its name to the virtual_alias_domains variable, and referencing an address mapping file in the virtual_alias_maps variable.
virtual_alias_domains = falcotsbrand.com
virtual_alias_maps = hash:/etc/postfix/virtual
The /etc/postfix/virtual file describes a mapping with a rather straightforward syntax: each line contains two fields separated by whitespace; the first field is the alias name, the second field is a list of email addresses where it redirects. The special @domain.com syntax covers all remaining aliases in a domain.
webmaster@falcotsbrand.com  jean@falcot.com
contact@falcotsbrand.com    laure@falcot.com, sophie@falcot.com
# The alias below is generic and covers all addresses within
# the falcotsbrand.com domain not otherwise covered by this file.
# These addresses forward email to the same user name in the
# falcot.com domain.
@falcotsbrand.com           @falcot.com
After changing /etc/postfix/virtual the postfix table /etc/postfix/virtual.db needs to be updated using sudo postmap /etc/postfix/virtual.

11.1.2.2. Virtual Mailbox Domains

Messages addressed to a virtual mailbox domain are stored in mailboxes not assigned to a local system user.
Enabling a virtual mailbox domain requires naming this domain in the virtual_mailbox_domains variable, and referencing a mailbox mapping file in virtual_mailbox_maps. The virtual_mailbox_base parameter contains the directory under which the mailboxes will be stored.
virtual_mailbox_domains = falcot.org
virtual_mailbox_maps = hash:/etc/postfix/vmailbox
virtual_mailbox_base = /var/mail/vhosts
The virtual_uid_maps parameter (respectively virtual_gid_maps) references the file containing the mapping between the email address and the system user (respectively group) that “owns” the corresponding mailbox. To get all mailboxes owned by the same owner/group, the static:5000 syntax assigns a fixed UID/GID (of value 5000 here).
Again, the syntax of the /etc/postfix/vmailbox file is quite straightforward: two fields separated with whitespace. The first field is an email address within one of the virtual domains, and the second field is the location of the associated mailbox (relative to the directory specified in virtual_mailbox_base). If the mailbox name ends with a slash (/), the emails will be stored in the maildir format; otherwise, the traditional mbox format will be used. The maildir format uses a whole directory to store a mailbox, each individual message being stored in a separate file. In the mbox format, on the other hand, the whole mailbox is stored in one file, and each line starting with “From ” (From followed by a space) signals the start of a new message.
# Jean's email is stored as maildir, with
# one file per email in a dedicated directory
jean@falcot.org falcot.org/jean/
# Sophie's email is stored in a traditional "mbox" file,
# with all mails concatenated into one single file
sophie@falcot.org falcot.org/sophie

11.1.3. Restrictions for Receiving and Sending

The growing number of unsolicited bulk emails (spam) requires being increasingly strict when deciding which emails a server should accept. This section presents some of the strategies included in Postfix.
If the reject-rules are too strict, it may happen that even legitimate email traffic gets locked out. It is therefor a good habit to test restrictions and prevent the permanent rejection of requests during this time using the soft_bounce = yes directive. By prepending a reject-type directive with warn_if_reject only a log message will be recorded instead of rejecting the request.

11.1.3.1. IP-Based Access Restrictions

The smtpd_client_restrictions directive controls which machines are allowed to communicate with the email server.
When a variable contains a list of rules, as in the example below, these rules are evaluated in order, from the first to the last. Each rule can accept the message, reject it, or leave the decision to a following rule. As a consequence, order matters, and simply switching two rules can lead to a widely different behavior.

Пример 11.2. Restrictions Based on Client Address

smtpd_client_restrictions =
    permit_mynetworks,
    warn_if_reject reject_unknown_client_hostname,
    check_client_access hash:/etc/postfix/access_clientip,
    reject_rhsbl_reverse_client dbl.spamhaus.org,
    reject_rhsbl_reverse_client rhsbl.sorbs.net,
    reject_rbl_client zen.spamhaus.org,
    reject_rbl_client dnsbl.sorbs.net
The permit_mynetworks directive, used as the first rule, accepts all emails coming from a machine in the local network (as defined by the mynetworks configuration variable).
The second directive would normally reject emails coming from machines without a completely valid DNS configuration. Such a valid configuration means that the IP address can be resolved to a name, and that this name, in turn, resolves to the IP address. This restriction is often too strict, since many email servers do not have a reverse DNS for their IP address. This explains why the Falcot administrators prepended the warn_if_reject modifier to the reject_unknown_client directive: this modifier turns the rejection into a simple warning recorded in the logs. The administrators can then keep an eye on the number of messages that would be rejected if the rule were actually enforced, and make an informed decision later if they wish to enable such enforcement.
The check_client_access directive allows the administrator to set up a blacklist and a whitelist of email servers, stored in the /etc/postfix/access_clientip file. Servers in the whitelist are considered as trusted, and the emails coming from there therefore do not go through the following filtering rules.
The last four rules reject any message coming from a server listed in one of the indicated blacklists. RBL is an acronym for Remote Black List, and RHSBL stands for Right-Hand Side Black List. The difference is that the former lists IP addresses, whereas the latter lists domain names. There are several such services. They list domains and IP addresses with poor reputation, badly configured servers that spammers use to relay their emails, as well as unexpected mail relays such as machines infected with worms or viruses.

11.1.3.2. Checking the Validity of the EHLO or HELO Commands

Each SMTP exchange starts with a HELO (or EHLO) command, followed by the name of the sending email server. Checking the validity of this name can be interesting. To fully enforce the restrictions listed in smtpd_helo_restrictions the smtpd_helo_required option needs to be enabled. Otherwise clients could skip the restrictions by not sending any HELO/EHLO command.

Пример 11.3. Restrictions on the name announced in EHLO

smtpd_helo_required = yes
smtpd_helo_restrictions =
    permit_mynetworks,
    reject_invalid_helo_hostname,
    reject_non_fqdn_helo_hostname,
    warn_if_reject reject_unknown_helo_hostname,
    check_helo_access hash:/etc/postfix/access_helo,
    reject_rhsbl_helo multi.surbl.org
The first permit_mynetworks directive allows all machines on the local network to introduce themselves freely. This is important, because some email programs do not respect this part of the SMTP protocol adequately enough, and they can introduce themselves with nonsensical names.
The reject_invalid_helo_hostname rule rejects emails when the EHLO announce lists a syntactically incorrect hostname. The reject_non_fqdn_helo_hostname rule rejects messages when the announced hostname is not a fully-qualified domain name (including a domain name as well as a host name). The reject_unknown_helo_hostname rule rejects messages if the announced name does not exist in the DNS. Since this last rule unfortunately leads to a lot of rejections, the administrators turned its effect to a simple warning with the warn_if_reject modifier as a first step; they may decide to remove this modifier at a later stage, after auditing the results of this rule.
The reject_rhsbl_helo allows to specify a black list to check the hostname against an RHSBL.
Using permit_mynetworks as the first rule has an interesting side effect: the following rules only apply to hosts outside the local network. This allows blacklisting all hosts that announce themselves as part of the falcot.com network, for instance by adding a falcot.com REJECT You are not in our network! line to the /etc/postfix/access_helo file.

11.1.3.3. Accepting or Refusing Mails Based on the Announced Sender

Every message has a sender, announced by the MAIL FROM command of the SMTP protocol; again, this information can be validated in several different ways.

Пример 11.4. Sender checks

smtpd_sender_restrictions =
    check_sender_access hash:/etc/postfix/access_sender,
    reject_unknown_sender_domain,
    reject_unlisted_sender,
    reject_non_fqdn_sender,
    reject_rhsbl_sender rhsbl.sorbs.net
The /etc/postfix/access_sender table maps some special treatment to some senders. This usually means listing some senders into a white list or a black list.
The reject_unknown_sender_domain rule requires a valid sender domain, since it is needed for a valid address. The reject_unlisted_sender rule rejects local senders if the address does not exist; this prevents emails being sent from an invalid address in the falcot.com domain, and messages emanating from joe.bloggs@falcot.com are only accepted if such an address really exists.
Finally, the reject_non_fqdn_sender rule rejects emails purporting to come from addresses without a fully-qualified domain name. In practice, this means rejecting emails coming from user@machine: the address must be announced as either user@machine.example.com or user@example.com.
The reject_rhsbl_sender rule reject senders based on a (domain-based) RHSBL service.

11.1.3.4. Accepting or Refusing Mails Based on the Recipient

Each email has at least one recipient, announced with the RCPT TO command in the SMTP protocol. These addresses also warrant validation, even if that may be less relevant than the checks made on the sender address.

Пример 11.5. Recipient checks

smtpd_recipient_restrictions =
    permit_mynetworks,
    reject_unauth_destination,
    reject_unlisted_recipient,
    reject_non_fqdn_recipient,
    permit
reject_unauth_destination is the basic rule that requires outside messages to be addressed to us; messages sent to an address not served by this server are rejected. Without this rule, a server becomes an open relay that allows spammers to send unsolicited emails; this rule is therefore mandatory, and it will be best included near the beginning of the list, so that no other rules may authorize the message before its destination has been checked.
The reject_unlisted_recipient rule rejects messages sent to non-existing local users, which makes sense. Finally, the reject_non_fqdn_recipient rule rejects non-fully-qualified addresses; this makes it impossible to send an email to jean or jean@machine, and requires using the full address instead, such as jean@machine.falcot.com or jean@falcot.com.
The permit directive at the end is not necessary. But it can be useful at the end of a restriction list to make the default policy explicit.

11.1.3.5. Restrictions Associated with the DATA Command

The DATA command of SMTP is emitted before the contents of the message. It doesn't provide any information per se, apart from announcing what comes next. It can still be subjected to checks.

Пример 11.6. DATA checks

smtpd_data_restrictions = reject_unauth_pipelining
The reject_unauth_pipelining directives causes the message to be rejected if the sending party sends a command before the reply to the previous command has been sent. This guards against a common optimization used by spammer robots, since they usually don't care a fig about replies and only focus on sending as many emails as possible in as short a time as possible.

11.1.3.6. Applying Restrictions

Although the above commands validate information at various stages of the SMTP exchange, Postfix sends the actual rejection as a reply to the RCPT TO command by default.
This means that even if the message is rejected due to an invalid EHLO command, Postfix knows the sender and the recipient when announcing the rejection. It can then log a more explicit message than it could if the transaction had been interrupted from the start. In addition, a number of SMTP clients do not expect failures on the early SMTP commands, and these clients will be less disturbed by this late rejection.
A final advantage to this choice is that the rules can accumulate information during the various stages of the SMTP exchange; this allows defining more fine-grained permissions, such as rejecting a non-local connection if it announces itself with a local sender.
The default behavior is controlled by the smtpd_delay_reject rule.

11.1.3.7. Filtering Based on the Message Contents

The validation and restriction system would not be complete without a way to apply checks to the message contents. Postfix differentiates the checks applying to the email headers from those applying to the email body.

Пример 11.7. Enabling content-based filters

header_checks = regexp:/etc/postfix/header_checks
body_checks = regexp:/etc/postfix/body_checks
Both files contain a list of regular expressions (commonly known as regexps or regexes) and associated actions to be triggered when the email headers (or body) match the expression.

Пример 11.8. Example /etc/postfix/header_checks file

/^X-Mailer: GOTO Sarbacane/ REJECT I fight spam (GOTO Sarbacane)
/^Subject: *Your email contains VIRUSES/ DISCARD virus notification
The first one checks the header mentioning the email software; if GOTO Sarbacane (a bulk email software) is found, the message is rejected. The second expression controls the message subject; if it mentions a virus notification, we can decide not to reject the message but to discard it immediately instead.
Using these filters is a double-edged sword, because it is easy to make the rules too generic and to lose legitimate emails as a consequence. In these cases, not only the messages will be lost, but their senders will get unwanted (and annoying) error messages.

11.1.4. Setting Up greylisting

“Greylisting” is a filtering technique according to which a message is initially rejected with a temporary error code, and only accepted after a further delivery attempt with some delay. This filtering is particularly efficient against spam sent by the many machines infected by worms and viruses, since this software rarely acts as a full SMTP agent (by checking the error code and retrying failed messages later), especially since many of the harvested addresses are really invalid and retrying would only mean losing time.
Postfix doesn't provide greylisting natively, but there is a feature by which the decision to accept or reject a given message can be delegated to an external program. The postgrey package contains just such a program, designed to interface with this access policy delegation service.
Once postgrey is installed, it runs as a daemon and listens on port 10023. Postfix can then be configured to use it, by adding the check_policy_service parameter as an extra restriction:
smtpd_recipient_restrictions =
    permit_mynetworks,
    [...]
    check_policy_service inet:127.0.0.1:10023
Each time Postfix reaches this rule in the rule set, it will connect to the postgrey daemon and send it information concerning the relevant message. On its side, Postgrey considers the IP address/sender/recipient triplet and checks in its database whether that same triplet has been seen recently. If so, Postgrey replies that the message should be accepted; if not, the reply indicates that the message should be temporarily rejected, and the triplet gets recorded in the database.
The main disadvantage of greylisting is that legitimate messages get delayed, which is not always acceptable. It also increases the burden on servers that send many legitimate emails.

11.1.5. Customizing Filters Based On the Recipient

Раздел 11.1.3, «Restrictions for Receiving and Sending» and Раздел 11.1.4, «Setting Up greylisting» reviewed many of the possible restrictions. They all have their use in limiting the amount of received spam, but they also all have their drawbacks. It is therefore more and more common to customize the set of filters depending on the recipient. At Falcot Corp, greylisting is interesting for most users, but it hinders the work of some users who need low latency in their emails (such as the technical support service). Similarly, the commercial service sometimes has problems receiving emails from some Asian providers who may be listed in blacklists; this service asked for a non-filtered address so as to be able to correspond.
Postfix provides such a customization of filters with a “restriction class” concept. The classes are declared in the smtpd_restriction_classes parameter, and defined the same way as smtpd_recipient_restrictions. The check_recipient_access directive then defines a table mapping a given recipient to the appropriate set of restrictions.

Пример 11.9. Defining restriction classes in main.cf

smtpd_restriction_classes = greylisting, aggressive, permissive

greylisting = check_policy_service inet:127.0.0.1:10023
aggressive =
        reject_rbl_client sbl-xbl.spamhaus.org,
        check_policy_service inet:127.0.0.1:10023
permissive = permit

smtpd_recipient_restrictions =
        permit_mynetworks,
        reject_unauth_destination,
        check_recipient_access hash:/etc/postfix/recipient_access

Пример 11.10. The /etc/postfix/recipient_access file

# Unfiltered addresses
postmaster@falcot.com  permissive
support@falcot.com     permissive
sales-asia@falcot.com  permissive

# Aggressive filtering for some privileged users
joe@falcot.com         aggressive

# Special rule for the mailing-list manager
sympa@falcot.com       reject_unverified_sender

# Greylisting by default
falcot.com             greylisting

11.1.6. Integrating an Antivirus Filter

The many viruses circulating as attachments to emails make it important to set up an antivirus solution at the entry point of the company network, since despite an awareness campaign, some users will still open attachments from obviously shady messages.
The Falcot administrators selected clamav from the homonymous package.
The task of interfacing between antivirus and the email server goes to clamav-milter. A milter (short for mail filter) is a filtering program specially designed to interface with email servers. A milter uses a standard application programming interface (API) that provides much better performance than filters external to the email servers. Milters were initially introduced by Sendmail, but Postfix soon followed suit.
Once the clamav-milter package is installed, the milter should be reconfigured to run on a TCP port rather than on the default named socket. This can be achieved with dpkg-reconfigure clamav-milter. When prompted for the “Communication interface with Sendmail”, answer “inet:10002@127.0.0.1”.
The standard ClamAV configuration fits most situations, but some important parameters can still be customized with dpkg-reconfigure clamav-base.
The last step involves telling Postfix to use the recently-configured filter. This is a simple matter of adding the following directive to /etc/postfix/main.cf:
# Virus check with clamav-milter
smtpd_milters = inet:[127.0.0.1]:10002
If the antivirus causes problems, this line can be commented out, and systemctl reload postfix should be run so that this change is taken into account.
All messages handled by Postfix now go through the antivirus filter.

11.1.7. Fighting Spam with SPF, DKIM and DMARC

The high number of unsolicited email sent every day led to the creation of several standards, which aim at validating that the sending host of an email is authorized and that the email has not been tampered with. The following systems are all DNS-based and require the administrators to not only have control over the mail server, but over the DNS for the domain in question too.

11.1.7.1. Integrating the Sender Policy Framework (SPF)

The Sender Policy Framework (SPF) is used to validate if a certain mail server is allowed to send emails for a given domain. It is mostly configured through DNS. The syntax for the entry to make is explained in detail at:
The following is a sample DNS entry which states that all the domain's Mail Exchange Resource Records (MX-RRs) are allowed to send email for the current domain, and all others are prohibited. The DNS entry does not need to be given a name. But to use the include directive it must have one.
Name: example.org
Type: TXT
TTL:  3600
Data: v=spf1 a mx -all
Давайте бегло взглянем на запись falcot.org.
# host -t TXT falcot.org
falcot.org descriptive text "v=spf1 ip4:199.127.61.96 +a +mx +ip4:206.221.184.234 +ip4:209.222.96.251 ~all"
В ней говорится, что IP-адрес отправителя должен соответствовать A-записи для отправляющего домена, или должен быть указан в качестве одной из MX-записей (Mail Exchange Resource Records) для текущего домена, или должен быть одним из трёх упомянутых адресов IP4. Все остальные хосты должны быть помечены как запрещённые для отправки электронной почты для домена отправителя. Последнее называется "soft fail" («мягкий сбой») и предназначено для соответствующей маркировки электронного письма, но при этом его принятия.
postfix почтовый сервер может проверять запись SPF на наличие входящих писем с помощью пакета postfix-policyd-spf-python, это - агент политики, написанный на Python. Файл /usr/share/doc/postfix-policyd-spf-python/README.Debian описывает необходимые шаги для интеграции агента в postfix, поэтому не будем здесь повторяться.
Конфигурация выполняется в файле /etc/postfix-policyd-spf-python/policyd-spf.conf, который полностью документирован в policyd-spf.conf(5) и /usr/share/doc/postfix-policyd-spf-python/policyd-spf.conf.commented.gz. Основные параметры конфигурации: HELO_reject и Mail_From_reject, которые настраивают, следует ли отклонять электронные письма (Fail) или принимать с добавлением заголовка (False), если проверки не пройдут. Последнее часто бывает полезно, когда сообщение дополнительно обрабатывается спам-фильтром.
Если результат предназначен для использования opendmarc (Раздел 11.1.7.3, «Интегрированная (Аутентификация сообщений на основе домена, отчетность и соответствие) Domain-based Message Authentication, Reporting and Conformance (DMARC)»), затем Header_Type должен быть установлен на AR.
Обратите внимание, что spamassassin содержит плагин для проверки записи SPF.

11.1.7.2. Integrating DomainKeys (DKIM) Подписание и проверка

Стандарт Domain Keys Identified Mail (DKIM) - это система аутентификации отправителя. MTA (агент транспорта почты), здесь, postfix добавляет цифровую подпись, связанную с именем домена, в заголовок исходящих писем. Получающая сторона может проверить текст сообщения и поля заголовка, проверив подпись по открытому ключу, который извлекается из DNS-записей отправителей.
Необходимые инструменты поставляются в комплекте пакетов opendkim и opendkim-tools.
Сначала необходимо создать закрытый ключ с помощью команды opendkim-genkey -s SELECTOR -d DOMAIN. SELECTOR должно быть уникальным именем ключа. Это может быть просто "mail" или дата создания, если вы планируете ротацию ключей.

Пример 11.11. Создать закрытый ключ для подписи электронных писем от falcot.com

# opendkim-genkey -s mail -d falcot.com -D /etc/dkimkeys
# chown opendkim.opendkim /etc/dkimkeys/mail.*
Это создаст файлы /etc/dkimkeys/mail.private и /etc/dkimkeys/mail.txt и установит для них соответствующие права владения. Первый файл содержит приватный (закрытый) ключ, а второй — публичный (открытый) ключ, который необходимо добавить в DNS:
Name: mail._domainkey
Type: TXT
TTL:  3600
Data: "v=DKIM1; h=sha256; k=rsa; s=email; p=[...]"
В пакете opendkim в Debian по умолчанию используется размер ключа 2048 бит. К сожалению, некоторые DNS-серверы могут обрабатывать только текстовые записи не длиннее 255 символов. В этом случае используйте опцию -b 1024 чтобы выбрать меньший размер ключа. Если opendkim-testkey возвращает результат успешно, то запись успешно настроена. Синтаксис записи объясняется здесь:
Чтобы сконфигурировать opendkim, SOCKET и RUNDIRдолжны быть выбраны в /etc/default/opendkim. Заметьте что SOCKET должен быть доступен из postfix в его chroot среде. Дальнейшая настройка осуществляется в /etc/opendkim.conf. Ниже приведен фрагмент конфигурации, который позволяет убедиться, что Domain "falcot.com" и его субдомены (SubDomain) подписаны Selector "mail" и единственным приватным ключом (KeyFile) /etc/dkimkeys/mail.private. "relaxed" Canonicalization как для заголовка, так и для тела письма допускает лёгкие модификации (например, с помощью программного обеспечения списка рассылки). Фильтр работает как при подписании ("s"), так и при проверке ("v") Mode. Если подпись не проходит проверку (On-BadSignature), почта должна быть помещена в карантин ("q").
[...]
Domain                  falcot.com
KeyFile                 /etc/dkimkeys/mail.private
Selector                mail

[...]
Canonicalization        relaxed/relaxed
Mode                    sv
On-BadSignature         q
SubDomains              yes

[...]
Socket                  inet:12345@localhost

[...]
UserID                  opendkim
Также возможно использовать несколько селекторов/ключей (KeyTable), доменов (SigningTable) и указать внутренние или доверенные хосты (InternalHosts, ExternalIgnoreList), которые могут отправлять почту через сервер как один из подписанных доменов без учётных данных.
Следующие директивы в /etc/postfix/main.cf созданы postfix используя это фильтр:
milter_default_action = accept
non_smtpd_milters = inet:localhost:12345
smtpd_milters = inet:localhost:12345
Чтобы разграничить подписание и проверку, иногда полезнее добавить директивы к службам в /etc/postfix/master.cf.
Более подробная информация доступна в каталоге /usr/share/doc/opendkim/ и страницах руководства opendkim(8) и opendkim.conf(5).
Заметьте что spamassassin содержит плагин для проверки записи DKIM.

11.1.7.3. Интегрированная (Аутентификация сообщений на основе домена, отчетность и соответствие) Domain-based Message Authentication, Reporting and Conformance (DMARC)

Стандарт Domain-based Message Authentication, Reporting and Conformance (DMARC) может использоваться для определения записи DNS TXT с именем _dmarc и действия, которое следует предпринять, если электронные письма, содержащие ваш домен в качестве отправляющего хоста, не проходят проверку с использованием DKIM и SPF.
Давайте посмотрим на записи двух крупных провайдеров:
# host -t TXT _dmarc.gmail.com
_dmarc.gmail.com descriptive text "v=DMARC1; p=none; sp=quarantine; rua=mailto:mailauth-reports@google.com"
# host -t TXT _dmarc.yahoo.com
_dmarc.yahoo.com descriptive text "v=DMARC1; p=reject; pct=100; rua=mailto:d@rua.agari.com; ruf=mailto:d@ruf.agari.com;"
У Yahoo строгая политика в отношении reject все электронных писем, которые якобы отправлены с учётной записи Yahoo, но с отсутствующими или непройденными проверками DKIM и SPF. Google Mail (Gmail) пропагандирует очень мягкую политику, согласно которой такие сообщения из основного домена по-прежнему должны приниматься (p=none). Для поддоменов они должны быть помечены как спам (sp=quarantine). Адреса, указанные в ключе rua могут использоваться для отправки агрегированных отчетов DMARC. Полный синтаксис описан здесь:
Почтовый сервер postfix также может использовать эту информацию. Пакет opendmarc содержит необходимый milter. Подобно opendkim SOCKET и RUNDIR должен быть выбран в /etc/default/opendmarc (для сокетов Unix вы должны убедиться, что они находятся внутри chroot postfix-а, чтобы их можно было найти). Конфигурационный файл /etc/opendmarc.conf содержит подробные комментарии и также объясняется в opendmarc.conf(5). По умолчанию электронные письма, не прошедшие проверку DMARC, не отклоняются, а помечаются путем добавления соответствующего поля заголовка. Чтобы изменить это, используйте RejectFailures true.
milter затем добавляется к smtpd_milters и non_smtpd_milters. Если мы настроили milters opendkim и opendmarc для работы на портах 12345 и 54321, запись в /etc/postfix/main.cf выглядит так:
non_smtpd_milters = inet:localhost:12345,inet:localhost:54321
smtpd_milters = inet:localhost:12345,inet:localhost:54321
milter также может выборочно применяться к сервису в /etc/postfix/master.cf.

11.1.8. Аутентифицированный SMTP

Для отправки электронной почты необходимо, чтобы SMTP-сервер был доступен; для отправки через него электронных писем также требуется указанный SMTP-сервер. Для роуминговых пользователей может потребоваться регулярное изменение конфигурации SMTP-клиента, поскольку SMTP-сервер Falcot отклоняет сообщения, поступающие с IP-адресов, по-видимому, не принадлежащих компании. Существует два решения: либо роуминговый пользователь устанавливает SMTP-сервер на свой компьютер, либо он использует сервер компании с аутентификацией в качестве сотрудника. Первое решение не рекомендуется, поскольку компьютер не будет постоянно подключен и не сможет повторить отправку сообщений в случае возникновения проблем; сосредоточимся на втором решении.
SMTP аутентификация в Postfix полагается на SASL (Simple Authentication and Security Layer). Для этого требуется установка пакетов libsasl2-modules и sasl2-bin, затем регистрация пароля в базе данных SASL для каждого пользователя, которому требуется аутентификация на SMTP-сервере. Это делается с помощью команды saslpasswd2, которая принимает несколько параметров. Опция -u определяет домен аутентификации, который должен соответствовать параметру smtpd_sasl_local_domain в конфигурации Postfix. Опция -c позволяет создать пользователя и -f позволяет указать файл, который будет использоваться, если базу данных SASL необходимо хранить не в умолчальном расположении (/etc/sasldb2).
# saslpasswd2 -u `postconf -h myhostname` -f /var/spool/postfix/etc/sasldb2 -c jean
[... type jean's password twice ...]
Обратите внимание, что база данных SASL была создана в каталоге Postfix. Чтобы обеспечить согласованность, мы также превращаем /etc/sasldb2 в символическую ссылку, указывающую на базу данных, используемую Postfix, командой ln -sf /var/spool/postfix/etc/sasldb2 /etc/sasldb2.
Теперь нам нужно настроить Postfix для использования SASL. Сначала необходимо добавить пользователя postfix в группу sasl, чтобы он мог получить доступ к базе данных учетных записей SASL. Для включения SASL также необходимо несколько новых параметров, а параметр smtpd_recipient_restrictions необходимо настроить, чтобы клиенты, прошедшие проверку подлинности SASL, могли свободно отправлять электронные письма.

Пример 11.12. Включение SASL в /etc/postfix/main.cf

# Включить аутентификацию SASL
smtpd_sasl_auth_enable = yes
# Определить SASL домент аутентификации для использования
smtpd_sasl_local_domain = $myhostname
[...]
# Добавить permit_sasl_authenticated перед reject_unauth_destination
# разрешить ретранслировать почту, отправляемую SASL-аутентифицированными пользователями
smtpd_recipient_restrictions =
    permit_sasl_authenticated,
    permit_mynetworks,
    reject_unauth_destination,
[...]
Обычно не рекомендуется отправлять пароли по незашифрованному соединению. Postfix позволяет использовать разные конфигурации для каждого порта (службы), на котором он работает. Всё это можно настроить с помощью различных правил и директив в файле /etc/postfix/master.cf. Чтобы вообще отключить аутентификацию для порта 25 (smtpd service), добавьте следующую директиву:
smtp      inet  n       -       y       -       -       smtpd
    [..]
    -o smtpd_sasl_auth_enable=no
    [..]
Если по какой-то причине клиенты используют устаревшую команду AUTH (так делают некоторые очень старые почтовые клиенты), совместимость с ними можно включить с помощью директивы broken_sasl_auth_clients.