Перейти к содержимому

Mydestination postfix что это

  • автор:

Особенности работы Postfix

image

Добрый день, сообщество. В этой статье хочу поговорить о Postfix – о том, каковы принципы его работы, и о возможностях диагностики проблем. В силу специфики работы приходится с ним сталкиваться — либо для решения своих задач, либо для понимания того, как работает чужая инфраструктура. В интернете о Postfix много информации, однако в основной массе это готовые конфиги для развертывания почтового сервера с нуля. Здесь же я постараюсь охватить основные аспекты администрирования Postfix.

Известно, что Postfix разработан как альтернатива Sendmail. ПО повышало производительность, обеспечивало устойчивость, гибкость и безопасность решения. Все основные Linux-дистрибутивы включают Postfix, в Mac OS X, начиная с версии 10.3, программа также используется вместо Sendmail.

Главные особенности

  • Фокус Postfix в том, что можно начинать работу без приготовлений (базовые конфигурационные файлы включают в себя пару строк).
  • Для эффективной фильтрации писем применяются регулярные выражения PCRE (Perl compatible regular expression).
  • Программа Postfix совместима с Sendmail: файлы aliases и .forward имеют схожий формат и семантику.
  • Postfix общается по протоколу ESMTP, поддерживает виртуальные домены и фильтрацию спама.
  • Не используется язык подстановки адресов как в Sendmail. Вместо этого производится поиск в плоских файлах таблиц или базе данных MySQL.

Архитектура

Postfix состоит из нескольких небольших, совместно работающих программ, которые посылают сетевые сообщения, принимают сообщения, осуществляют локальную доставку почты и другие действия. Связь между программами обеспечивается с помощью сокетов Unix или алгоритмов FIFO. Архитектура отличается от Sendmail, где всю работу нужно выполнять одной большой программе.

Запуск и контроль всех процессов выполняет программа master. В ее конфиге — master.cf -перечислены вспомогательные программы и информация о том, как и когда их нужно запустить.

Самые важные программы показаны в блок-схеме:

image

За прием почты на порту SMTP отвечает smtpd. Он же проверяет, авторизован ли клиент для отправки почты. Если письмо отправляется локально, через совместимость с /usr/lib/sendmail, файл будет записан в каталог /var/spool/postfix/maildrop. Этот каталог сканируется программой pickup, которая обрабатывает найденные файлы. Входящая почта обрабатывается программой cleanup. Она добавляет отсутствующие заголовки и переписывает адреса в соответствии с картами canonical и virtual. Прежде чем поместить письмо в очередь, incoming программа cleanup передает письмо программе trivial-rewrite, которая также выполняет незначительные исправления в адресах, добавляя домен и частично заполненный адрес.

Электронные письма, ожидающие доставки, находятся под управлением qmgr – администратора очередей:

Incoming – входящая почта;

Active – доставляемая почта;

Deferred – письма, доставка которых не осуществилась ранее;

Hold – письма, заблокированные в очереди администратором;

Corrupt – письма, которые невозможно прочитать.

Анализатор очередей обычно выбирает сообщение для обработки на основе алгоритма FIFO.

Также он поддерживает и более сложный алгоритм — например, отбирает события только с определенных адресов.

Чтобы не перегружать хост приемки, после доставки писем Postfix использует алгоритм медленного запуска, который позволяет контролировать скорость доставки. Отсроченные письма получают метку с обозначением времени повторной отправки. Время увеличивается экспоненциально, благодаря этому вы можете избежать траты ресурсов на сообщения, которые не удается доставить. Состояние недосягаемых мест кешируется — во избежание новых попыток.

Отправка почты идет при поддержке trivial-rewrite, утилита qmgr принимает решение, куда должно быть отправлено сообщение. Решение о маршруте может быть аннулировано transport картой.

Доставка с помощью SMTP осуществляется, конечно, smtp-программой. Lmtp осуществляет локальную пересылку почты по протоколу LMTP, использующим семантику ESMTP (https://tools.ietf.org/html/rfc2033). LMTP изменен так, что для управления локальной очередью почтовый сервер не нужен.

Задача local – локальная доставка почты. Программа распознает в таблице aliases и выполняет инструкции из файла .forward получателя. Сообщения могут быть направлены по другому адресу, переданы внешней программе на обработку или сохраниться в почтовых папках пользователей.

Программа virtual доставляет письма в виртуальные почтовые ящики – ящики, представляющие собой адреса назначения. Наконец, программа pipe реализует доставку через внешние программы.

Взаимодействие между пользователем и системой обработки регулируется утилитами:

sendmail, mailq, newaliases — интерфейс совместимости postfix и sendmail.

]# sendmail user@example.com
from test@test.com
user@example.com
HI.
.

Поставьте «.» И нажмите Enter — sendmail попытается отправить письмо.

postfix – запускает и прекращает работу системы обработки почты;

]# postfix status
postfix/postfix-script: the Postfix mail system is running: PID: 16765

postalias — создает и модифицирует таблицы псевдонимов;

postmap – создает, модифицирует, запрашивает таблицы преобразований;

cat /etc/postfix/transport

onedomain.ru smtp:10.1.2.10
twodomain.ru smtp:10.1.3.10

Утилиты фактически создают индексированные карты файлов. Повторить запуск при изменениях в файлах aliases и transport;

Postcat –напечатает содержимое файла из очереди;

]# postcat -qv 96987C3CFB40
postcat: name_mask: all
postcat: inet_addr_local: configured 2 IPv4 addresses
postcat: inet_addr_local: configured 2 IPv6 addresses
*** ENVELOPE RECORDS deferred/9/96987C3CFB40 ***
…

Postsuper и postqueue – управляют почтовыми очередями. Первая используется для высокопривилегированных операций. Например, удаление очереди:

]# postqueue -p
-Queue ID- —Size— —-Arrival Time—- -Sender/Recipient——-
956FAC3CFB46 2311 Mon Jul 27 19:50:05 MAILER-DAEMON
(connect to 10.70.85.12[10.70.85.12]:25: No route to host)
user@domain.ru

Postconf – инструментальное средство, позволяющее конфигурировать postfix- конфиг main.cf. Без аргументов выводит все параметры в текущей конфигурации. Если передать значение параметра – выведет значение этого параметра. С ключом –d напечатает default-настройки, а не сконфигурированные.

]# postconf virtual_mailbox_limit
virtual_mailbox_limit = 51200000

С ключом –n напечатает только значения, отличные от типовых.

Главным файлом Postfix является main.cf. Он конфигурирует серверные программы и определяет таблицы преобразований, на которые содержит ссылки. Содержит более 300 параметров. Для запуска почтового сервера в средней организации достаточно лишь несколько из них. В документацию рекомендуется включать лишь параметры, содержащие нестандартные значения.

Базовая возможная настройка

Супер-простая конфигурация – пустой файл. Как ни странно, вполне приемлемая и приводит к тому, что создается почтовый сервер, осуществляющий локальную доставку почты в пределах домена локального хоста. Любые нелокальные сообщения посылаются дистанционным серверам.

Второй вариант – null клиент. Система не выполняет локальную доставку, а направляет исходящую почту на указанный почтовый сервер. При этом конфиге указывается несколько параметров: mydomain – определяющий домен компьютера; myorigin — определяющий почтовый домен, добавляемый к почтовым адресам. Третьим параметром будет mydestination, определяющий локальные почтовые домены (они же canonical домены). Если домен получателя соответствует mydestination, письмо доставит программа local (при условии что файла .forward не найдено). Если в mydestination несколько записей, они рассматриваются как псевдонимы одного домена. Null клиенту локальная доставка не нужна, поэтому параметр mydestination — пустой. Также программа local проведет поиск псевдонима адреса в таблицах alias_maps. Наконец, параметр relayhost оповещает Postfix о том, что нелокальные сообщения нужно посылать на указанный компьютер, а не адресатам. Квадратные скобки говорят о том, что указанная строка обрабатывается как имя компьютера, то есть A не MX запись DNS. Null клиент не должен получать почту с других систем – комментируем строчку smtpd в файле master.cf – программа smtpd не запустится.

Преобразования и виртуальные домены

Аспекты поведения Postfix определяются использованием таблиц поиска, отражающих ключи как значения тип: путь или просто как списки. Например, таблица alias_maps:dbm:/etc/mail/aliases.

Обратите внимание, синтаксис ключ: значение обеспечивает совместимость с Sendmail.

Помимо традиционного файла базы данных бинарного формата dbm, источником данных для таблицы преобразований может быть ldap, regexp выражения, postgres, Mysql и многое другое.

Если вам нужно обслуживать почтовый домен, то можно сделать это тремя путями:

— Указать домен в mydestination – доставка пойдет по схеме, описанной выше;

— Указать домен в параметре virtual_alias_domains. Домен получит собственное адресное пространство. Потребуется обеспечить возможность преобразования адресов в реальные (карта virtual_alias_maps);

— Указать домен в virtual_mailbox _domains. Здесь также будет собственное именное пространство. Но управление списком пользователей будет независимым от системных учеток. Потребуется указать параметр virtual_mailbox _maps c таблицей действительных пользователей в домене.

Защита и доступ

Postfix защищает себя на нескольких уровнях. Большинство серверных Postfix-программ могут выполняться в среде с измененным корневым каталогом (chroot). Они являются отдельными программами без связи Родитель-дочерний. Ни одна из них не имеет бита setuid. Каталог, в который направлена почта, открыт для записи группе postdrop, для нее — программа postdrop setgid.

Что касается доступа, почтовые домены ретранслируют почту на сторонние адреса только для надежных агентов. Открытая ретрансляция с неизвестных адресов, как известно, не сулит ничего хорошего. Postfix по умолчанию закрыт как ретранслятор. Стандартные настройки сильно ограничены, возможно вам придется ослаблять ограничения. Доступы конфигурируются списками ограничения доступа access restriction list. Важнейшим параметром будет smtpd_recipient_restrictions, так как адресом получателя куда проще управлять. По крайней мере, можно установить локальный ли он.

Вот список ограничений для проверки ретрансляции:

Check_client_address – проверяет адрес ПК клиента;

Check_recipient_access – проверяет почтовый адрес получателя;

Permit_mynetworks – предоставляет доступ к адресам в параметре mynetworks;

Reject_anauth_destination – отклоняет почту для нелокальных получателей – ретрансляция отсутствует.

Одна из мер защиты – строгая реализация протокола ESMTP. Легитимные почтовые сервера протокол принимают, а рассылки спама могут не принять и дискредитировать себя. Однако сейчас технология уже не столь надежна. Есть злоумышленники, способные обработать легитимную почту.

Черные списки основаны на информации из DNS – разрешаются директивой reject_rhsbl_sender – после указывается DNS-сервер, также reject_rbl_client , только проверяет имя PC, а не доменное имя.

Фильтрация – для проверки самого Body письма Postfix использует regexp выражения в реальном времени. А также может передавать сообщения другим программам. Postfix поддерживает SpamAssasin и фильтры подобного рода.

До сих пор в версиях Posfix удавались лишь DDOS атаки.

Отладка

Если возникла проблема с почтой, первым делом можно заглянуть в журнальные файлы Posfix. Каждая Postfix-программа регистрирует запись в журнале для обработанного сообщения.

Идентификатор письма 96987C3CFB40 — общий для каждой строки. Postfix присвоит его, как только сообщение попадает в систему и никогда не изменяет. Таким образом, при поиске в журнале можно сосредоточиться на поиске ID, затем с помощью grep отследить маршрут.

Jul 27 20:00:08 iwtm611 postfix/smtp[8576]: 96987C3CFB40: to=<user@domain.ru>, relay=none, delay=603, delays=600/0.06/3/0, dsn=4.4.1, status=deferred (connect to 10.70.85.12[10.70.85.12]:25: No route to host)

Jul 27 20:00:08 iwtm611 postfix/error[8585]: 98640C3CFB4D: to=<user@domain.ru>, relay=none, delay=603, delays=600/3.1/0/0, dsn=4.4.1, status=deferred (delivery temporarily suspended: connect to 10.70.85.12[10.70.85.12]:25: No route to host)

Jul 27 20:00:08 iwtm611 postfix/error[8585]: 98E5CC3CFB77: to=<user@domain.ru>, relay=none, delay=603, delays=600/3.1/0/0.01, dsn=4.4.1, status=deferred (delivery temporarily suspended: connect to 10.70.85.12[10.70.85.12]:25: No route to host)

Jul 27 20:00:08 iwtm611 postfix/error[8585]: 99C8DC3CFB62: to=<user@domain.ru>, relay=none, delay=603, delays=600/3.1/0/0, dsn=4.4.1, status=deferred (delivery temporarily suspended: connect to 10.70.85.12[10.70.85.12]:25: No route to host)

Другим местом поиска является сама очередь. Утилита postqueue –p (или аналогичный вывод mailq) печатает содержимое очереди.

-Queue ID- —Size— —-Arrival Time—- -Sender/Recipient——-

90190C3B9B9F 2242 Mon Jul 27 19:50:05 MAILER-DAEMON

(connect to 10.70.85.12[10.70.85.12]:25: No route to host)

95E96C3CFB5A 2307 Mon Jul 27 19:50:05 MAILER-DAEMON

(delivery temporarily suspended: connect to 10.70.85.12[10.70.85.12]:25: No route to host)

956FAC3CFB46 2311 Mon Jul 27 19:50:05 MAILER-DAEMON

(delivery temporarily suspended: connect to 10.70.85.12[10.70.85.12]:25: No route to host)

96987C3CFB40 2311 Mon Jul 27 19:50:05 MAILER-DAEMON

(delivery temporarily suspended: connect to 10.70.85.12[10.70.85.12]:25: No route to host)

97944C3CFB5E 2311 Mon Jul 27 19:50:05 MAILER-DAEMON

(delivery temporarily suspended: connect to 10.70.85.12[10.70.85.12]:25: No route to host)

postcat –qv 96987C3CFB40 Найдет письмо по ID, покажет заголовок и дополнительную информацию:
[root@iwtm611

]# postcat -qv 96987C3CFB40

postcat: name_mask: all

postcat: inet_addr_local: configured 2 IPv4 addresses

postcat: inet_addr_local: configured 2 IPv6 addresses

*** ENVELOPE RECORDS deferred/9/96987C3CFB40 ***

message_size: 2311 201 1 0 2311

message_arrival_time: Mon Jul 27 19:50:05 2020

create_time: Mon Jul 27 19:50:05 2020

regular_text: Return-Path: <user@domain.ru>

regular_text: Received: from Vvpc (unknown [10.254.1.250])

regular_text: by iwtm611.local (Postfix) with ESMTP id BCB42C3CFB62

regular_text: for <usr111@test.com>; Thu, 2 Jul 2020 12:48:45 +0300 (MSK)

regular_text: MIME-Version: 1.0

regular_text: From: user@domain.ru

regular_text: To: usr111@test.com

regular_text: Date: 2 Jul 2020 12:48:40 +0300

regular_text: Subject: test

regular_text: Content-Type: text/plain; charset=utf-8

regular_text: Content-Transfer-Encoding: base64

regular_text: Message-Id: <20200702094845.BCB42C3CFB62@iwtm611.local>

*** HEADER EXTRACTED deferred/9/96987C3CFB40 ***

*** MESSAGE FILE END deferred/9/96987C3CFB40 ***

qshape – новый инструмент свежих версий – показывает сводную статистику содержимого и подводит итог – количество минут, в течение которых сообщение отправляется. Например, для итога по домену отправителя запустите qshape –s, а отклоненные письма можно посмотреть через параметр qshape deferred.

image

В примере таблицы можно увидеть, что 4 сообщения на gmail висят в очереди более 120 минут.

Рикошет – вызывается параметром soft_bounce. Это конфигурационный параметр. Postfix будет отправлять временные сообщения при отправке сообщений об ошибках типа: user_unknown или relay_denied. Это эффективное средство, позволяющее отслеживать местонахождение сообщения после изменений конфигурации и не терять их. Все, что вы отклоните, в конечном итоге вернется отправителю. Не забудьте это отключить после завершения проверки.

Для проверки доступа в Postfix есть расширение xclient, имитирующее отправку сообщений из другого места. Включается в main.cf параметром smtpd_autorized_xclient_hosts.

Postfix можно легко установить и запустить. Но быстро разобраться и решить проблему его внедрения в незнакомой структуре, удастся лишь при понимании тонкостей его работы. Надеюсь, кому-то эта статья поможет сэкономить время и силы на выявление причин проблем. И понять, почему почтовая система работает таким образом, а не иначе.

Postfix Basic Configuration

Postfix has several hundred configuration parameters that are controlled via the main.cf file. Fortunately, all parameters have sensible default values. In many cases, you need to configure only two or three parameters before you can start to play with the mail system. Here’s a quick introduction to the syntax:

The text below assumes that you already have Postfix installed on the system, either by compiling the source code yourself (as described in the INSTALL file) or by installing an already compiled version.

This document covers basic Postfix configuration. Information about how to configure Postfix for specific applications such as mailhub, firewall or dial-up client can be found in the STANDARD_CONFIGURATION_README file. But don’t go there until you already have covered the material presented below.

The first parameters of interest specify the machine’s identity and role in the network.

The default values for many other configuration parameters are derived from just these.

The next parameter of interest controls the amount of mail sent to the local postmaster:

Be sure to set the following correctly if you’re behind a proxy or network address translator, and you are running a backup MX host for some other domain:

Postfix daemon processes run in the background, and log problems and normal activity to the syslog daemon. Here are a few things that you need to be aware of:

If your machine has unusual security requirements you may want to run Postfix daemon processes inside a chroot environment.

If you run Postfix on a virtual network interface, or if your machine runs other mailers on virtual interfaces, you’ll have to look at the other parameters listed here as well:

Postfix configuration files

By default, Postfix configuration files are in /etc/postfix. The two most important files are main.cf and master.cf; these files must be owned by root. Giving someone else write permission to main.cf or master.cf (or to their parent directories) means giving root privileges to that person.

In /etc/postfix/main.cf you will have to set up a minimal number of configuration parameters. Postfix configuration parameters resemble shell variables, with two important differences: the first one is that Postfix does not know about quotes like the UNIX shell does.

You specify a configuration parameter as:

and you use it by putting a «$» character in front of its name:

You can use $parameter before it is given a value (that is the second main difference with UNIX shell variables). The Postfix configuration language uses lazy evaluation, and does not look at a parameter value until it is needed at runtime.

Postfix uses database files for access control, address rewriting and other purposes. The DATABASE_README file gives an introduction to how Postfix works with Berkeley DB, LDAP or SQL and other types. Here is a common example of how Postfix invokes a database:

Whenever you make a change to the main.cf or master.cf file, execute the following command as root in order to refresh a running mail system:

What domain name to use in outbound mail

The myorigin parameter specifies the domain that appears in mail that is posted on this machine. The default is to use the local machine name, $myhostname, which defaults to the name of the machine. Unless you are running a really small site, you probably want to change that into $mydomain, which defaults to the parent domain of the machine name.

For the sake of consistency between sender and recipient addresses, myorigin also specifies the domain name that is appended to an unqualified recipient address.

Examples (specify only one of the following):

What domains to receive mail for

The mydestination parameter specifies what domains this machine will deliver locally, instead of forwarding to another machine. The default is to receive mail for the machine itself. See the VIRTUAL_README file for how to configure Postfix for hosted domains.

You can specify zero or more domain names, «/file/name» patterns and/or «type:table» lookup tables (such as hash:, btree:, nis:, ldap:, or mysql:), separated by whitespace and/or commas. A «/file/name» pattern is replaced by its contents; «type:table» requests that a table lookup is done and merely tests for existence: the lookup result is ignored.

IMPORTANT: If your machine is a mail server for its entire domain, you must list $mydomain as well.

Example 1: default setting.

Example 2: domain-wide mail server.

Example 3: host with multiple DNS A records.

Caution: in order to avoid mail delivery loops, you must list all hostnames of the machine, including $myhostname, and localhost.$mydomain.

What clients to relay mail from

By default, Postfix will forward mail from clients in authorized network blocks to any destination. Authorized networks are defined with the mynetworks configuration parameter. The current default is to authorize the local machine only. Prior to Postfix 3.0, the default was to authorize all clients in the IP subnetworks that the local machine is attached to.

Postfix can also be configured to relay mail from «mobile» clients that send mail from outside an authorized network block. This is explained in the SASL_README and TLS_README documents.

IMPORTANT: If your machine is connected to a wide area network then the «mynetworks_style = subnet» setting may be too friendly.

Examples (specify only one of the following):

Specify «mynetworks_style = host» (the default when compatibility_level ≥ 2) when Postfix should forward mail from only the local machine.

Specify «mynetworks_style = subnet» (the default when compatibility_level < 2) when Postfix should forward mail from SMTP clients in the same IP subnetworks as the local machine. On Linux, this works correctly only with interfaces specified with the «ifconfig» or «ip» command.

Specify «mynetworks_style = class» when Postfix should forward mail from SMTP clients in the same IP class A/B/C networks as the local machine. Don’t do this with a dialup site — it would cause Postfix to «trust» your entire provider’s network. Instead, specify an explicit mynetworks list by hand, as described below.

Alternatively, you can specify the mynetworks list by hand, in which case Postfix ignores the mynetworks_style setting. To specify the list of trusted networks by hand, specify network blocks in CIDR (network/mask) notation, for example:

You can also specify the absolute pathname of a pattern file instead of listing the patterns in the main.cf file.

What destinations to relay mail to

By default, Postfix will forward mail from strangers (clients outside authorized networks) to authorized remote destinations only. Authorized remote destinations are defined with the relay_domains configuration parameter. The default is to authorize all domains (and subdomains) of the domains listed with the mydestination parameter.

Examples (specify only one of the following):

What delivery method: direct or indirect

By default, Postfix tries to deliver mail directly to the Internet. Depending on your local conditions this may not be possible or desirable. For example, your system may be turned off outside office hours, it may be behind a firewall, or it may be connected via a provider who does not allow direct mail to the Internet. In those cases you need to configure Postfix to deliver mail indirectly via a relay host.

Examples (specify only one of the following):

The form enclosed with [] eliminates DNS MX lookups. Don’t worry if you don’t know what that means. Just be sure to specify the [] around the mailhub hostname that your ISP gave to you, otherwise mail may be mis-delivered.

The STANDARD_CONFIGURATION_README file has more hints and tips for firewalled and/or dial-up networks.

What trouble to report to the postmaster

You should set up a postmaster alias in the aliases(5) table that directs mail to a human person. The postmaster address is required to exist, so that people can report mail delivery problems. While you’re updating the aliases(5) table, be sure to direct mail for the super-user to a human person too.

Execute the command «newaliases» after changing the aliases file. Instead of /etc/aliases, your alias file may be located elsewhere. Use the command «postconf alias_maps» to find out.

The Postfix system reports problems to the postmaster alias. You may not be interested in all types of trouble reports, so this reporting mechanism is configurable. The default is to report only serious problems (resource, software) to postmaster:

The meaning of the classes is as follows:

Proxy/NAT external network addresses

Some mail servers are connected to the Internet via a network address translator (NAT) or proxy. This means that systems on the Internet connect to the address of the NAT or proxy, instead of connecting to the network address of the mail server. The NAT or proxy forwards the connection to the network address of the mail server, but Postfix does not know this.

If you run a Postfix server behind a proxy or NAT, you need to configure the proxy_interfaces parameter and specify all the external proxy or NAT addresses that Postfix receives mail on. You may specify symbolic hostnames instead of network addresses.

IMPORTANT: You must specify your proxy/NAT external addresses when your system is a backup MX host for other domains, otherwise mail delivery loops will happen when the primary MX host is down.

Example: host behind NAT box running a backup MX host.

What you need to know about Postfix logging

Postfix daemon processes run in the background, and log problems and normal activity to the syslog daemon. The syslogd process sorts events by class and severity, and appends them to logfiles. The logging classes, levels and logfile names are usually specified in /etc/syslog.conf. At the very least you need something like:

After changing the syslog.conf file, send a «HUP» signal to the syslogd process.

IMPORTANT: many syslogd implementations will not create files. You must create files before (re)starting syslogd.

IMPORTANT: on Linux you need to put a «-» character before the pathname, e.g., -/var/log/maillog, otherwise the syslogd process will use more system resources than Postfix.

Hopefully, the number of problems will be small, but it is a good idea to run every night before the syslog files are rotated:

The first line (postfix check) causes Postfix to report file permission/ownership discrepancies.

The second line looks for problem reports from the mail software, and reports how effective the relay and junk mail access blocks are. This may produce a lot of output. You will want to apply some postprocessing to eliminate uninteresting information.

The DEBUG_README document describes the meaning of the «warning» etc. labels in Postfix logging.

Running Postfix daemon processes chrooted

Postfix daemon processes can be configured (via the master.cf file) to run in a chroot jail. The processes run at a fixed low privilege and with file system access limited to the Postfix queue directories (/var/spool/postfix). This provides a significant barrier against intrusion. The barrier is not impenetrable (chroot limits file system access only), but every little bit helps.

With the exception of Postfix daemons that deliver mail locally and/or that execute non-Postfix commands, every Postfix daemon can run chrooted.

Sites with high security requirements should consider to chroot all daemons that talk to the network: the smtp(8) and smtpd(8) processes, and perhaps also the lmtp(8) client. The author’s own porcupine.org mail server runs all daemons chrooted that can be chrooted.

The default /etc/postfix/master.cf file specifies that no Postfix daemon runs chrooted. In order to enable chroot operation, edit the file /etc/postfix/master.cf, and follow instructions in the file. When you’re finished, execute «postfix reload» to make the change effective.

Note that a chrooted daemon resolves all filenames relative to the Postfix queue directory (/var/spool/postfix). For successful use of a chroot jail, most UNIX systems require you to bring in some files or device nodes. The examples/chroot-setup directory in the source code distribution has a collection of scripts that help you set up Postfix chroot environments on different operating systems.

Additionally, you almost certainly need to configure syslogd so that it listens on a socket inside the Postfix queue directory. Examples of syslogd command line options that achieve this for specific systems:

FreeBSD: syslogd -l /var/spool/postfix/var/run/log

Linux, OpenBSD: syslogd -a /var/spool/postfix/dev/log

My own hostname

The myhostname parameter specifies the fully-qualified domain name of the machine running the Postfix system. $myhostname appears as the default value in many other Postfix configuration parameters.

By default, myhostname is set to the local machine name. If your local machine name is not in fully-qualified domain name form, or if you run Postfix on a virtual interface, you will have to specify the fully-qualified domain name that the mail system should use.

Alternatively, if you specify mydomain in main.cf, then Postfix will use its value to generate a fully-qualified default value for the myhostname parameter.

Examples (specify only one of the following):

My own domain name

The mydomain parameter specifies the parent domain of $myhostname. By default, it is derived from $myhostname by stripping off the first part (unless the result would be a top-level domain).

Conversely, if you specify mydomain in main.cf, then Postfix will use its value to generate a fully-qualified default value for the myhostname parameter.

Examples (specify only one of the following):

My own network addresses

The inet_interfaces parameter specifies all network interface addresses that the Postfix system should listen on; mail addressed to «user@[network address]» will be delivered locally, as if it is addressed to a domain listed in $mydestination.

You can override the inet_interfaces setting in the Postfix master.cf file by prepending an IP address to a server name.

The default is to listen on all active interfaces. If you run mailers on virtual interfaces, you will have to specify what interfaces to listen on.

IMPORTANT: If you run MTAs on virtual interfaces you must specify explicit inet_interfaces values for the MTA that receives mail for the machine itself: this MTA should never listen on the virtual interfaces or you would have a mailer loop when a virtual MTA is down.

Example: default setting.

Example: host running one or more virtual mailers. For each Postfix instance, specify only one of the following.

Mydestination postfix что это

Authored by: Rackspace Support

After you have installed Postfix, you can work with settings in the main.cf file to further configure Postfix.

Note: This article assumes that you are using a single domain for your email needs.

Modular nature of Postfix

One of the key aspects of Postfix is that it is designed to be a modular package. The base installation itself is fairly small, and the vast majority of the “usual” mail administration, such as anti-spam and anti-virus, is actually conducted by third-party packages like SpamAssassin.

You can begin to see the modular nature of Postfix when you look at the main.cf file. Many settings refer to other files on the server. This setup can seem slightly confusing at first, and your initial reaction might be to hard code the data rather than reference another file with a single word in it. However, we recommend retaining the modularity of Postfix and editing multiple files for what might seem like simple settings. Such modularity will be useful when you start adding multiple domains, users, and aliases to your setup.

The main.cf file

To see the main.cf file, issue the following command:

The file consists of basically three sections. The first section includes several settings such as the smtpd_banner and biff parameters. The second section has settings for TLS parameters.

This article focuses on the last section, which looks as follows on the democloud server:

Note: Some of the settings already have the host name from the base Postfix installation.

Although some of the settings might be self-explanatory, the following sections describe them so that you can get a better understanding of Postfix and what you can do with it.

myhostname

The myhostname value was set during the Postfix installation when you entered the domain name that you want to use. This name also matches the cloud server host name.

aliases

Aliases provide a method for delivering mail to different users without having to set up dozens of different accounts. The default settings in the main.cf reference another file:

Open that file, as follows:

The file shows a list of names followed by root . Mail delivered to the first name is actually delivered to the second name. You do not need to set up the postmaster , news , webmaster , abuse , and other users for Postfix because mail delivered to those names is sent to root .

Using the same syntax, you can have all mail for root delivered to the admin user by adding the following line ( demo is the main admin user for the democloud server):

As a result, the delivery destination would change as follows:

  1. Mail sent to mailer-daemon is sent to postmaster .
  2. Mail to postmaster is sent to root .
  3. Mail sent to root is sent to the main admin user demo .

You can adjust the aliases as you see fit, but instead of changing all the root users in the file, it is easier to add the one line as shown. Adding that line also makes future migration and administration easier.

After you change the aliases file, you must refresh the aliases database for any changes to occur. Use the following command:

myorigin

Internal emails from packages such as cron jobs do not supply full mail credentials; they use the myorigin setting instead. As such, you need to set this parameter to the main host name of the server.

By default, the setting refers to the /etc/mailname file. To look at the contents, run the following command:

Example output for the democloud server is as follows:

However, you can also set myorigin by using $mydomain in the main.cf file, as follows:

Although you haven’t specifically set the $mydomain variable, Postfix gets the information from the myhostname setting, parsing the host name to gain the main domain name.

Setting the myorigin parameter this way allows for easier administration at a later date because only one setting ( myhostname ) needs to change. All the other parameters take the change from that.

mydestination

Although you have not yet set the server to receive mail, the mydestination parameter defines the domains from which the server will accept mail.

The default looks as follows:

The default is adequate when you are setting up mail for a single domain. However, like with the myorigin setting, you can reduce future administration by using the $mydomain variable as follows:

relayhosts

For the setup in this series of articles, you do not need this setting. You can leave it blank.

mynetworks

The mynetworks parameter defines the network to use. The default value includes IPv6 settings, which you can remove. The remaining value looks as follows:

The rest

You can use the default values for the remaining settings. They are relevant for more complex configurations.

Final settings

After the preceding changes, the last section in the example main.cf file looks as follows:

Test the settings

As with all packages, after you have made any changes to the configuration, you must restart, as follows:

After Postfix is restarted, you can conduct a quick test by sending an email to a working email address, as shown in the following example.

You should receive an email from the correct user and the correct domain. Check the headers to verify that they are correct.

Summary

Configuring Postfix can be a daunting task. This introduction helps with the basics and shows how using variables instead of hard coding domain names can save time and effort in any future administration.

Share this information:

©2020 Rackspace US, Inc.

Except where otherwise noted, content on this site is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License

Postfix: The Definitive Guide by Kyle D. Dent

Get full access to Postfix: The Definitive Guide and 60K+ other titles, with a free 10-day trial of O’Reilly.

There are also live events, courses curated by job role, and more.

Configuration Files

The directory /etc/postfix contains Postfix configuration files. The two most important files used in the configuration of Postfix are master.cf and main.cf. These files should be owned by, and only writable by, the root user. They should be readable by everyone. Whenever you make changes to these files, you have to reload Postfix for your changes to go into effect: [1]

The master daemon is the overall process that controls other Postfix daemons for mail handling. The master daemon uses the master.cf file for its configuration information. The master.cf file contains a line for each Postfix service or transport. Each line has columns that specify how each program should run as part of the overall Postfix system. See Chapter 3 for information on Postfix’s architecture and how various components interact with each other. In many installations, you will never have to change the default master.cf file. See Section 4.5 later in the chapter for information on when and how to make changes to master.cf.

The main.cf Configuration File

The main.cf file is the core of your Postfix configuration. Nearly all configuration changes occur in this file. The default main.cf file lists only a portion of the nearly 300 Postfix parameters. Most Postfix parameters do not need to be changed, but the flexibility is there when it’s required. All Postfix parameters are listed and described in the various sample configuration files. The sample files are located in the directory specified by the sample_directory parameter, which is usually the same directory as your main.cf file. Both the main.cf file and the sample files that come with the Postfix distribution contain comments that explain each of the parameters.

Throughout this book, when the text says to modify a parameter, it always refers to a parameter in your main.cf unless a different file is indicated.

You can edit main.cf with the postconf command, as you saw earlier in the chapter, or you can change the file directly with any text editor [2] (such as vi or emacs). The file contains blank lines, comment lines, and lines that assign values to parameters. Comment lines start with the # character and continue to the end of the line. Blank and comment lines are ignored by Postfix. Parameters can appear in any order within the file, and are written as you would expect:

A parameter definition must start in the first column of the line. The spaces around the equals sign are optional.

Here is an example parameter assignment with a comment:

You cannot have a comment on the same line as a parameter. The following example is incorrect and, with some parameters, could cause unexpected behavior that might be difficult to track down:

Do not use quotation marks around values. They have no significance in the Postfix configuration, so they would be considered part of the value, which is probably not what you want.

Line continuation

A line that starts with whitespace (tabs or spaces) is considered a continuation of the previous line. This allows you to continue long parameter values onto multiple lines. The parameter assignment:

Configuration variables

You can refer to the value of a defined parameter by putting a $ in front of the parameter name:

This causes the value of myorigin to be “example.com.”

You can reference a value in the file even before it has been set. The following example works as well as the previous one:

Multiple values

Many parameters can have more than one value. Multiple values can be separated by commas, spaces, tabs, or new lines. Remember that when you separate values with new lines there must be spaces or tabs in front of the values to indicate a continuation of the previous line:

These three assignments to mydestination are effectively the same.

Certain parameters allow you to place multiple values in a text file and then point the parameter to that file in main.cf . A value that starts with a forward slash is assumed to be a pointer to a file. If your system receives mail locally for many destinations, you may want to keep the list of destinations in a separate file. Then point the mydestination parameter to that file:

The parameters that can use external files to store values are those that accept lists where the order of the listed items is not significant, such as mynetworks , mydestination , and relay_domains . Check the documentation for a particular parameter to see if it supports this feature.

If you have thousands of items in a list, it can be more efficient to keep them in a lookup table instead. Lookup tables are described in the next section.

Whenever you make a change to main.cf , you must reload Postfix for your changes to go into effect:

See Section 4.4.2 later in the chapter for more information about stopping and starting Postfix.

Lookup Tables

Rather than using complicated rewriting or pattern transformation rules as Sendmail does, Postfix makes use of simple, yet flexible, lookup tables. Many parameters point to lookup tables to obtain important configuration information. One such parameter is canonical_maps . It’s used to rewrite email addresses in messages. Consider a site that uses account names internally for email addresses, but wants any publicly visible addresses to have the form firstname.lastname@example.com . For example, the address kdent@example.com should appear as kyle.dent@example.com . A canonical_maps lookup table provides the mapping from a key ( kdent@example.com ) to a value ( kyle.dent@example.com ).

There are many parameters that use lookup maps, but they all work on the same principle. An email message (or client) provides some kind of key used to look up a value. Based on the value, Postfix takes some action or makes some change.

Lookup table format

Postfix lookup tables are usually Unix database files, which are specially indexed files that provide faster access to the stored items. Lookup tables start as simple text files, with each key and value on the same line separated by spaces or tabs:

Each entry has a unique key. The keys are often referred to as the LHS, or lefthand side of an entry, and the values are referred to as the RHS, or righthand side of an entry. Keys in lookup tables are not case-sensitive. The files can contain comment and blank lines just like main.cf, and line continuation works by putting whitespace at the beginning of carry-over lines. Lookup tables also do not treat quotation marks with any special significance.

Once you have created a text file with all of your mappings, you have to execute the postmap command against it to create the actual indexed version of the file:

Whenever you change your text file you must execute postmap against it.

The postmap command can also be used to query lookup tables. Use the -q option to query a value:

Database formats

Different types of Unix database files have different internal formats. The format you use depends on the database libraries available on your system. Normally Postfix supports one or more of three types: btree , dbm , and hash . Depending on your system libraries, you may have fewer or more than these three types available. It’s important to know which map type you use. The postconf command with the -m option lists all of the map types supported by your installation of Postfix:

The output of this command lists all map types, some of which are used for access to other kinds of storage. But you should find at least one of the three database types ( btree , dbm , and hash ).

The default_database_type parameter tells you which database type Postfix uses by default:

All of the examples in this book use the hash type, but if your installation is using something different, be aware of that as you follow the examples.

If you don’t specify a database type with postmap, it automatically uses your default type. In general, you can just use the default type configured on your system, but you must know what it is when assigning lookup tables to mapping parameters.

When you assign a lookup table to a parameter, you must specify both the map type and the path to the lookup table. The format of lookup maps is:

where type is the storage access method and name is the resource containing keys and values. With indexed datafile lookups, name is the filename. The canonical example is assigned as follows:

You can assign multiple lookup tables to a parameter. Postfix searches the tables in the order listed, stopping as soon as it finds a match. Some table lookups are recursive, depending on the parameter. The canonical_maps parameter in these examples is one such parameter. With recursive lookups, once a value is found, Postfix tries to match it against all of the keys again until a key matches itself or is not found.

You may have noticed that when postmap indexes files, it creates additional files. postmap creates either one additional file with the extension .db, or two additional files with the extensions .dir and .pag, depending on your database format. When you assign the lookup table to its parameter, specify the path and filename without any extensions.

Search order

Since keys are often email addresses, Postfix automatically parses addresses, breaking them up into their parts. You can have keys that match a full address, just the domain portion, or just the local part. The way Postfix searches for addresses or portions of addresses depends on the type of mapping parameter. Certain maps might sensibly include the simple local part of an address, such as canonical_maps . Others would not expect a local part key, such as transport_maps . The order in which Postfix searches for a match differs slightly, depending on which type of parameter it’s working with. Check the lookup table’s manpage to see which search order it follows.

The search order where local parts are expected, such as with canonical_maps , relocated_maps , and virtual_alias_maps , is as follows:

The complete address. Example: kdent@example.com

The local part alone. Example: kdent

The domain portion only, specified with the @ character. Example: @example.com

For lookup tables where it doesn’t make sense to have a local part, such as with transport_maps , Postfix searches for matches in the following order:

The complete address. Example: kdent@example.com

The domain by itself. Example: example.com

The domain specified with an initial period, which matches any subdomain. Example: .example.com

If you always want domains to match themselves plus any subdomain, you can simplify your lookup tables somewhat by setting the parent_domain_matches_subdomains parameter. The parameter, by default, contains many lists. To add transport_maps to the list, append it as follows:

Now, a domain entry in the /etc/postfix/transport matches itself and all of its subdomains automatically. You no longer need any entries such as the third item, .example.com , from the preceding list.

Lookup tables and simple lists

Some parameters that normally take a simple list, such as mydestination , can also be specified with a lookup table. The LHS keys are the items in the list. You still have to provide a RHS value for each key, but the value is simply ignored. You can specify any text you want. It’s a good place to provide yourself a comment. Using a lookup table for a straight list is useful when you have thousands of items; otherwise, a simple text file is more than adequate and probably has better performance. If you use a lookup table for lists of network IP addresses, you cannot use the network/netmask notation to specify an entire subnet. You must list each address individually. Check the documentation to see if a list parameter supports the lookup table feature.

Regular expression tables

Postfix provides a special lookup table type using regular expressions that offers even more flexibility for matching keys in lookup tables. Regular expressions are used in many Unix utilities. They provide a powerful tool for specifying matching patterns. There are two types of regular expression libraries that you might use with Postfix, depending on which libraries are available on your system.

By default, Postfix uses POSIX extended regular expressions, which I’ll refer to as regexp. POSIX, which stands for Portable Operating System Interface, is a standard that encourages portability across different operating systems. It includes specifications for regular expressions. Postfix also supports Perl-compatible regular expressions, which I’ll refer to as pcre. If you’re used to regular expressions in Perl, you’ll find that regexp patterns are a bit different. If you want pcre support, be sure you have a pcre library to link with when building Postfix. With the pcre format, some features differ from regexp, and the performance is usually better. It’s possible that your Postfix distribution already includes pcre support. You can check by executing the postconf command with the -m option, as you did earlier in the chapter.

If pcre is listed among your map types, then you can use Perl-style regular expressions for your regular expression lookup tables. But don’t rush to add pcre support if you don’t have it; the default regexp is quite powerful and usually adequate for administrators who need regular expressions. Install pcre only if you know of particular Perl-style regular expression features you need.

Both Perl-style and POSIX regular expressions are very well-documented in many places. Any book on Perl should include information on its regular expressions, and if you have Perl installed on your system, you should find a manpage called perlre(1) . Documentation for regexp usually appears in a manpage called re_format(7) . If your system does not include the manpage, you should be able to find it on the Web. sed & awk by Dale Dougherty and Arnold Robbins (O’Reilly) contains information on POSIX regular expressions.

To use regular expression tables, specify either regexp or pcre as the map type when assigning tables to map parameters:

Entries in re_body_checks are conventionally specified—with the regular expression pattern between two forward slashes—as the key, followed by whitespace, followed by the mapped value:

The most common use of regular expression tables is with the header_checks and body_checks parameters for blocking spam. See Chapter 11 for more information.

Other Formats

Postfix can make use of other backend systems for its lookup tables. (Later chapters discuss using MySQL and LDAP lookup tables.) When you make use of these external sources for lookup values, you should start with one of the simple database formats, such as dbm or hash . Make sure your configuration works as expected. After setting up your external data source, verify that it returns the same results as your simple tables.

The postmap with the -q option is an important tool for testing any kind of lookup table. For example, the following two commands should return the same values when you test your MySQL database:

See Chapter 15 for more information on using Postfix with external data sources.

Alias Files

Alias files are a special case of Postfix lookup tables because they use a Sendmail-compatible format. The file has traditionally been called aliases, and its location depends on your platform, but it is normally within the /etc directory or a subdirectory below it. By default, Postfix is configured to point to your original aliases file, so if you are migrating from Sendmail, your existing aliases continue to work.

Locating aliases

Historically, email systems used a single alias database. Postfix lets you have as many as you want. Multiple alias files can help in organizing your configuration information. Typically, administrators configure multiple alias files for convenience when configuring separate mailing lists. The alias_maps parameter points to your alias files.

If your system supports NIS, which is a network database of users (including their aliases), then by default Postfix includes NIS among your alias maps. A typical default alias_maps looks like the following:

If your system includes support for NIS, but you’re not using it, you should change the parameter so that it points to your aliases file only:

You may want to locate your aliases file in your Postfix configuration directory for consistency. Some administrators prefer to have all of the email configuration files located together. Simply reassign alias_maps to point to the new location:

You should also reassign alias_database so that your newaliases command continues to work correctly (see the next section):

Building alias database files

Since the format of alias maps differs from that of Postfix lookup tables, you cannot use postmap to build the alias database from your text file. Instead, Postfix provides the postalias command. Its command-line syntax is the same as that of postmap, allowing you to create or query alias maps. To build an alias database from your aliases file, execute the following:

Another Sendmail compatibility command related to alias files is the newaliases command. It provides a convenient way to rebuild your alias databases. The Postfix installation includes a replacement version of the command that follows the same syntax as the original. It’s normally executed with no arguments and determines which alias files to rebuild from the alias_database parameter. The alias_database parameter differs from alias_maps in that it includes only standard Unix database-mapped files (those that should be indexed by newaliases), whereas alias_maps might also contain other map types such as nis . newaliases uses the default_database_type parameter discussed earlier to determine which database format to use.

Alias file format

The text file for alias databases is much like Postfix lookup tables, except for the alias definition itself. Alias files can have blank and comment lines that are ignored. Comments are marked by a # at the beginning of the line and cannot be on the same line as an alias definition. A single alias definition can be broken onto multiple lines by starting continuation lines with whitespace.

The form of an alias definition consists of the name being aliased, followed by a colon, followed by one or more targets for the aliased name. Aliases can be directed to different types of targets (discussed below). Multiple targets are separated by commas. Both aliases and targets should be quoted if they contain whitespace or any special characters such as a # , :, and @ :

The LHS aliases are always local addresses, so you cannot specify a domain name with an alias key. The target is often one or more addresses, but can be any of the following:

Any RFC 2822 address is allowed, meaning target addresses can be local or forwarded to another site for delivery. For example:

Specify the full path to a file. New messages are appended to the file specified. Delivery occurs to the file as it would to any local mailbox. See Chapter 7 for information on local delivery to mailboxes and on specifying different mailbox formats. For example:

Specify a pipe character and a command. See Chapter 14 for more information on delivery to commands. For example:

An included file contains a list of additional alias targets. The targets in the file can be any valid target type as described here, but by default filenames and commands are not allowed. The next section discusses configuration parameters to override these default restrictions. For example:

Normally, when Postfix makes a local delivery it assumes the identity of the recipient of the message. With aliases, Postfix uses the identity of the owner of the alias file, except when the file is owned by root . When a delivery would occur as root , Postfix uses the identity of the account configured with the default_privs parameter instead.

Alias restrictions

You can control which kinds of targets are allowed in your alias files with the parameters allow_mail_to_commands and allow_mail_to_files . Each of these parameters takes a list of the aliasing mechanism that permits its action. Aliasing mechanisms are “alias,” the alias file we’ve been discussing; “include,” the include target, and “forward,” which is the .forward file discussed in Chapter 7.

The default setting for the two parameters is to allow delivery to commands and files from both alias and .forward files, but not from include files, for security considerations. If you want to disallow delivery to commands and files from your aliases database entirely, set the parameters to blank:

If you would like to make delivery to commands and files available in all the alias mechanisms, set the parameters as follows:

This setting is equivalent to the default behavior for Sendmail. However, it could expose access to possibly vulnerable mailing-list managers that might be coerced into adding a filename or command as a destination address. If you don’t need the additional include option for files and commands, it’s best to accept the Postfix default.

Important aliases

There are several common aliases that are configured by default. By convention, these system aliases point to the root account. You want to make sure that root ’s mail is read regularly. This is normally accomplished by creating an alias for root to the normal login account of the person or persons responsible for system administration.

RFC 2142 defines several mailbox names that all domains should have, depending on which services they run on the Internet. At a minimum, you should have a postmaster alias, and you should review the RFC to see if there are other aliases you want to create.

[1] If you change the inet_interfaces parameter, you must stop and start Postfix.

[2] Postfix expects configuration files to contain normal Unix-style line endings. If you edit your configuration files from another platform, such as Windows or Mac, make sure that your editor uses the correct line endings for Unix.

Get Postfix: The Definitive Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *