Назад | Перейти на главную страницу

Разрешить только Postfix отправлять почту через порт 25 - путаница в правилах iptables

Я знаю, что уже есть ветка, в которой упоминается, как разрешить только postfix отправлять почту через порт 25. Правило брандмауэра разрешает Postfix отправлять электронную почту только через SMTP на порт 25.

Моя проблема в том, что если я укажу правило iptables, упомянутое в связанном потоке, я больше не смогу отправлять электронные письма.

iptables -I OUTPUT -m owner ! --uid-owner postfix -m tcp -p tcp --dport 25 -j REJECT --reject-with icmp-admin-prohibited

ip6tables -I OUTPUT -m owner ! --uid-owner postfix -m tcp -p tcp --dport 25 -j REJECT --reject-with icmp6-adm-prohibited

Если я, однако, укажу root для --uid-owner он снова работает. Итак, я посмотрел, под каким постфиксом пользователя работает ps aux | grep postfix:

postfix   8508  0.0  0.0  67476  4524 ?        S    13:35   0:00 pickup -l -t fifo -u -c
postfix  13069  0.0  0.0  67472  4404 ?        S    14:47   0:00 anvil -l -t unix -u -c
postfix  13266  0.0  0.0 105164 10444 ?        S    14:55   0:00 smtpd -n smtp -t inet -u -c -o stress= -s 2
postfix  13267  0.0  0.0  67476  4452 ?        S    14:55   0:00 proxymap -t unix -u
postfix  13274  0.0  0.0  35584  4200 ?        S    14:55   0:00 plesk_saslauthd -l -t unix -u -c status=5 listen=6 dbpath=/plesk/passwd.db
root     13335  0.0  0.0  16976   988 pts/0    S+   14:55   0:00 grep --color=auto postfix
root     14608  0.0  0.0  65408  4564 ?        Ss   Apr19   0:17 /usr/lib/postfix/sbin/master
postfix  25855  0.0  0.0  67648  4640 ?        S    10:17   0:01 qmgr -l -t fifo -u
postfix  25908  0.0  0.0  80836  6772 ?        S    10:18   0:00 tlsmgr -l -t unix -u -c
postfix  26156  0.0  0.0 398972  3484 ?        Ssl  Apr18   0:05 /usr/lib/plesk-9.0/psa-pc-remote -p inet:12768@127.0.0.1 -t 7210   -P /run/psa-pc-remote.pid -u postfix -g popuser -n

Я знаю, что у postfix есть главный процесс, который нужно запускать как root потому что в противном случае привязка к порту 25 была бы невозможна. Однако я думал, что postfix действительно порождает подпроцессы под пользователем postfix для фактической доставки писем (через smtp). Есть идеи, почему правило iptables не работает? Имеет ли пользователь postfix не отправлять электронные письма (доставляются ли они вместо этого через пользователя root)? Что мне здесь не хватает?

РЕДАКТИРОВАТЬ: конфигурация постфикса - main.cf

# 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 (Ubuntu)
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

# TLS parameters
smtpd_tls_cert_file = /etc/postfix/postfix.pem
smtpd_tls_key_file = $smtpd_tls_cert_file
smtpd_use_tls = yes
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache

# See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for
# information on enabling SSL in the smtp client.

smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
myhostname = zeus.lotsearch.de
alias_maps = hash:/etc/aliases, hash:/var/spool/postfix/plesk/aliases
alias_database = hash:/etc/aliases
#myorigin = /etc/mailname
mydestination = localhost.lotsearch.de, localhost, localhost.localdomain
relayhost =
mynetworks = , 127.0.0.0/8, [::1]/128
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
inet_protocols = all
mailman_destination_recipient_limit = 1
virtual_mailbox_domains = $virtual_mailbox_maps, hash:/var/spool/postfix/plesk/virtual_domains
virtual_alias_maps = $virtual_maps, hash:/var/spool/postfix/plesk/virtual
virtual_mailbox_maps = , hash:/var/spool/postfix/plesk/vmailbox
transport_maps = , hash:/var/spool/postfix/plesk/transport
smtpd_tls_security_level = may
smtp_tls_security_level = may
smtp_use_tls = no
smtpd_timeout = 3600s
smtpd_proxy_timeout = 3600s
disable_vrfy_command = yes
smtpd_sender_restrictions = check_sender_access hash:/var/spool/postfix/plesk/blacklists, permit_sasl_authenticated
smtpd_client_restrictions = permit_mynetworks, permit_sasl_authenticated
smtp_send_xforward_command = yes
smtpd_authorized_xforward_hosts = 127.0.0.0/8 [::1]/128
smtpd_sasl_auth_enable = yes
smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination
virtual_mailbox_base = /var/qmail/mailnames
virtual_uid_maps = static:30
virtual_gid_maps = static:31
smtpd_milters = , inet:127.0.0.1:12768
sender_dependent_default_transport_maps = hash:/var/spool/postfix/plesk/sdd_transport_maps
virtual_transport = plesk_virtual
plesk_virtual_destination_recipient_limit = 1
virtual_mailbox_limit = 0
smtpd_tls_ciphers = medium
smtpd_tls_mandatory_ciphers = medium
tls_medium_cipherlist = HIGH:!aNULL:!MD5
smtpd_tls_mandatory_protocols = TLSv1 TLSv1.1 TLSv1.2
smtpd_tls_protocols = TLSv1 TLSv1.1 TLSv1.2
message_size_limit = 0

master.cf

#
# Postfix master process configuration file.  For details on the format
# of the file, see the master(5) manual page (command: "man 5 master" or
# on-line: http://www.postfix.org/master.5.html).
#
# Do not forget to execute "postfix reload" after editing this file.
#
# ==========================================================================
# service type  private unpriv  chroot  wakeup  maxproc command + args
#               (yes)   (yes)   (no)    (never) (100)
# ==========================================================================
smtp      inet  n       -       y       -       -       smtpd
#smtp      inet  n       -       y       -       1       postscreen
#smtpd     pass  -       -       y       -       -       smtpd
#dnsblog   unix  -       -       y       -       0       dnsblog
#tlsproxy  unix  -       -       y       -       0       tlsproxy
#submission inet n       -       y       -       -       smtpd
#  -o syslog_name=postfix/submission
#  -o smtpd_tls_security_level=encrypt
#  -o smtpd_sasl_auth_enable=yes
#  -o smtpd_reject_unlisted_recipient=no
#  -o smtpd_client_restrictions=$mua_client_restrictions
#  -o smtpd_helo_restrictions=$mua_helo_restrictions
#  -o smtpd_sender_restrictions=$mua_sender_restrictions
#  -o smtpd_recipient_restrictions=
#  -o smtpd_relay_restrictions=permit_sasl_authenticated,reject
#  -o milter_macro_daemon_name=ORIGINATING
#smtps     inet  n       -       y       -       -       smtpd
#  -o syslog_name=postfix/smtps
#  -o smtpd_tls_wrappermode=yes
#  -o smtpd_sasl_auth_enable=yes
#  -o smtpd_reject_unlisted_recipient=no
#  -o smtpd_client_restrictions=$mua_client_restrictions
#  -o smtpd_helo_restrictions=$mua_helo_restrictions
#  -o smtpd_sender_restrictions=$mua_sender_restrictions
#  -o smtpd_recipient_restrictions=
#  -o smtpd_relay_restrictions=permit_sasl_authenticated,reject
#  -o milter_macro_daemon_name=ORIGINATING
#628       inet  n       -       y       -       -       qmqpd
cleanup   unix  n       -       y       -       0       cleanup
#qmgr     unix  n       -       n       300     1       oqmgr
tlsmgr    unix  -       -       y       1000?   1       tlsmgr
rewrite   unix  -       -       y       -       -       trivial-rewrite
bounce    unix  -       -       y       -       0       bounce
defer     unix  -       -       y       -       0       bounce
trace     unix  -       -       y       -       0       bounce
verify    unix  -       -       y       -       1       verify
flush     unix  n       -       y       1000?   0       flush
proxymap  unix  -       -       n       -       -       proxymap
proxywrite unix -       -       n       -       1       proxymap
smtp      unix  -       -       y       -       -       smtp
relay     unix  -       -       y       -       -       smtp
#       -o smtp_helo_timeout=5 -o smtp_connect_timeout=5
showq     unix  n       -       y       -       -       showq
error     unix  -       -       y       -       -       error
retry     unix  -       -       y       -       -       error
discard   unix  -       -       y       -       -       discard
local     unix  -       n       n       -       -       local
virtual   unix  -       n       n       -       -       virtual
lmtp      unix  -       -       y       -       -       lmtp
anvil     unix  -       -       y       -       1       anvil
scache    unix  -       -       y       -       1       scache
#
# ====================================================================
# Interfaces to non-Postfix software. Be sure to examine the manual
# pages of the non-Postfix software to find out what options it wants.
#
# Many of the following services use the Postfix pipe(8) delivery
# agent.  See the pipe(8) man page for information about ${recipient}
# and other message envelope options.
# ====================================================================
#
# maildrop. See the Postfix MAILDROP_README file for details.
# Also specify in main.cf: maildrop_destination_recipient_limit=1
#
maildrop  unix  -       n       n       -       -       pipe
  flags=DRhu user=vmail argv=/usr/bin/maildrop -d ${recipient}
#
# ====================================================================
#
# Recent Cyrus versions can use the existing "lmtp" master.cf entry.
#
# Specify in cyrus.conf:
#   lmtp    cmd="lmtpd -a" listen="localhost:lmtp" proto=tcp4
#
# Specify in main.cf one or more of the following:
#  mailbox_transport = lmtp:inet:localhost
#  virtual_transport = lmtp:inet:localhost
#
# ====================================================================
#
# Cyrus 2.1.5 (Amos Gouaux)
# Also specify in main.cf: cyrus_destination_recipient_limit=1
#
#cyrus     unix  -       n       n       -       -       pipe
#  user=cyrus argv=/cyrus/bin/deliver -e -r ${sender} -m ${extension} ${user}
#
# ====================================================================
# Old example of delivery via Cyrus.
#
#old-cyrus unix  -       n       n       -       -       pipe
#  flags=R user=cyrus argv=/cyrus/bin/deliver -e -m ${extension} ${user}
#
# ====================================================================
#
# See the Postfix UUCP_README file for configuration details.
#
uucp      unix  -       n       n       -       -       pipe
  flags=Fqhu user=uucp argv=uux -r -n -z -a$sender - $nexthop!rmail ($recipient)
#
# Other external delivery methods.
#
ifmail    unix  -       n       n       -       -       pipe
  flags=F user=ftn argv=/usr/lib/ifmail/ifmail -r $nexthop ($recipient)
bsmtp     unix  -       n       n       -       -       pipe
  flags=Fq. user=bsmtp argv=/usr/lib/bsmtp/bsmtp -t$nexthop -f$sender $recipient
scalemail-backend unix  -   n   n   -   2   pipe
  flags=R user=scalemail argv=/usr/lib/scalemail/bin/scalemail-store ${nexthop} ${user} ${extension}
mailman unix - n n - - pipe flags=R user=list:list argv=/usr/lib/plesk-9.0/postfix-mailman ${nexthop} ${user} ${recipient}


plesk_virtual unix - n n - - pipe flags=DORhu user=popuser:popuser argv=/usr/lib/plesk-9.0/postfix-local -f ${sender} -d ${recipient} -p /var/qmail/mailnames
pickup fifo n - - 60 1 pickup
qmgr fifo n - n 1 1 qmgr
smtps inet n - - - - smtpd -o smtpd_tls_wrappermode=yes

plesk_saslauthd unix y y y - 1 plesk_saslauthd status=5 listen=6 dbpath=/plesk/passwd.db

plesk-94.130.34.42-2a01-4f8-10b-1f55--2 unix - n n - - smtp -o smtp_bind_address=94.130.34.42 -o smtp_bind_address6=2a01:4f8:10b:1f55::2 -o smtp_address_preference=ipv4

plesk-94.130.34.42- unix - n n - - smtp -o smtp_bind_address=94.130.34.42 -o smtp_bind_address6= -o smtp_address_preference=ipv4

submission inet n - - - - smtpd -o smtpd_enforce_tls=yes -o smtpd_tls_security_level=encrypt -o smtpd_sasl_auth_enable=yes -o smtpd_client_restrictions=permit_sasl_authenticated,reject -o smtpd_sender_restrictions= -o smtpd_recipient_restrictions=permit_mynetworks,permit_sasl_authenticated,reject_unauth_destination

Правила:

iptables -A OUTPUT -m owner --gid-owner postfix -p tcp -m tcp --dport 25 -j ACCEPT
iptables -A OUTPUT -m owner --uid-owner root -p tcp -m tcp --dport 25 -j ACCEPT
iptables -A OUTPUT -p tcp -m tcp --dport 25 -j REJECT --reject-with icmp-port-unreachable

позволяет отправлять электронные письма только пользователям postfix и root. Если у кого-то есть root-доступ, игра окончена. И мы не запускаем службы от имени root, верно?

Я думаю, это потому, что вам нужно правило INPUT для вашего почтового трафика. Это также работает для постфикса GitLab.

iptables -A OUTPUT -p tcp --dport 25 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -p tcp -m multiport --sport 25,110,143 -m state --state NEW,ESTABLISHED -j ACCEPT

Возможно, вам понадобятся другие правила исходящей почты, но я обнаружил, что почтовые серверы, похоже, возвращаются к серверу при отправке через порт 25.

Вам не обязательно использовать мультипорт, он здесь для примера. Если бы вы хотели только 25 по этому правилу, это выглядело бы так:

iptables -A INPUT -p tcp --sport 25 -m state --state NEW,ESTABLISHED -j ACCEPT

Похоже, вы отправляете исходящую почту через smtp-клиент, работающий с unpriv=n, который является языком postfix master.cf для эта служба работает как root. Опубликованные вами конфигурации не доказывают этого, но я предполагаю, что это то, что ваша транспортная карта настроена для использования.

name      type   private  unpriv chroot wakeup  maxproc command
plesk-..  unix   -        n      n      -       -       smtp -o ..

Что нужно сделать: внимательно изучите, кто и почему добавил эту строчку (имя plesk выглядит как подсказка), какая часть службы действительно нуждается в привилегиях root, а затем отделяет эти задачи от клиента smtp. Практическое правило: Доставка писем обычно не является задачей, требующей особых привилегий. Запуск клиента smtp от имени root обычно безумие.

Возможно, что привилегии root для вашего smtp-клиента совершенно не нужны, и вы можете просто изменить службу из unpriv=n к unpriv=y.

Я настоятельно рекомендую, избавившись от Plesk, начать с нового набора конфигураций из вашего любимого дистрибутива и добавлять только те модификации, которые вам нужны. Plesk печально известен тем, что вносит изменения в конфигурации, которые нелегко защитить и поддерживать за пределами plesk. Если это вообще возможно, вы должны написать свои собственные, а не копировать изменения plesk.