Firewall rule to only allow Postfix to send email through SMTP on port 25

Solution 1:

Do two things:

  1. Run Postfix under its own user account. It should already be doing so, on any sane system.

  2. Set an iptables rule with a uid match for that account, which blocks outgoing traffic to destination port 25 not from that user.

    For example: Here we assume the username is postfix, though it may be something different on your system.

    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
    

    Note that when you save the rule, the user name will be converted to a numeric uid.