Log with iptables which user is delivering email to port 25

5,876

It would probably be better to have the policy for the OUTPUT table set to DROP and then to explicitly open the relevant ports etc but this will be quite specific to your environment so is an exercise for the OP.

You can use -m multiport to match up to 15 ports e.g.

iptables -A OUTPUT -p tcp -m multiport --dports 25,587 -m owner --gid-owner mail -j ACCEPT

to allow the group mail to send on both ports or

You can log new outbound connections like this

iptables -A OUTPUT -p tcp -m multiport --dports 25,587 -m state --state NEW -j LOG --log-uid --log-prefix  "LOCAL_DROPPED_SPAM "

and you get a message like this

Nov 11 12:52:26 hostname kernel: LOCAL_DROPPED_SPAM IN= OUT=eth0 SRC=192.168.254.181 DST=192.168.254.187 LEN=60 TOS=0x10 PREC=0x00 TTL=64 ID=53476 DF PROTO=TCP SPT=49893 DPT=25 WINDOW=14600 RES=0x00 SYN URGP=0 UID=1000 GID=1000

iptables -A OUTPUT -p tcp -m multiport --dports 25,587 -j DROP

to finally drop all outbound connections on both ports.

Remember that iptables actions rules in the order they are in the table and first match wins so

  • Place your ALLOW rules first
  • Follow this with the LOG rules
  • Then DROP
Share:
5,876
Maus
Author by

Maus

Updated on September 18, 2022

Comments

  • Maus
    Maus almost 2 years

    Because we got blacklisted on CBL I set up the following firewall rules with iptables:

    #!/bin/bash
    iptables -A OUTPUT -d 127.0.0.1 -p tcp -m tcp --dport 25 -j ACCEPT
    iptables -A OUTPUT -p tcp -m tcp --dport 25 -m owner --gid-owner mail -j ACCEPT
    iptables -A OUTPUT -p tcp -m tcp --dport 25 -m owner --uid-owner root -j ACCEPT
    iptables -A OUTPUT -p tcp -m tcp --dport 25 -m owner --uid-owner Debian-exim -j ACCEPT
    iptables -A OUTPUT -p tcp -m limit --limit 15/minute -m tcp --dport 25 -j LOG --log-prefix "LOCAL_DROPPED_SPAM"
    iptables -A OUTPUT -p tcp -m tcp --dport 25 -j REJECT --reject-with icmp-port-unreachable
    

    I'm not able to connect to port 25 from localhost with another user than root or a mail group member -> So it seems to work.

    Still some questions remain:

    • How effective do you rate this rule-set to prevent spam coming from bad PHP-Scripts hosted on the server?
    • Is there a way to block port 25 and 587 within the same statement?
    • Is the usage of /usr/sbin/sendmail also limited or blocked by this rule-set?
    • Is there a way to log the username of all other attempts which try to deliver stuff to port 25?