iptables settings for outgoing FTP

Getting FTP to fully work with iptables can be a pain in the ass. Thinking of active and passive mode here. Even if you are familiar with iptables, its easier to copy/paste this rather than writing this down out of your head. (I am here refering to outgoing FTP connections, meaning you are acting as the client). So here are the rules you were looking for:

-A INPUT -p tcp --sport 21 -m state --state ESTABLISHED -j ACCEPT
-A INPUT -p tcp --sport 20 -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p tcp --sport 1024: --dport 1024: -m state --state ESTABLISHED -j ACCEPT

-A OUTPUT -p tcp --dport 21 -m state --state NEW,ESTABLISHED -j ACCEPT
-A OUTPUT -p tcp --dport 20 -m state --state ESTABLISHED -j ACCEPT
-A OUTPUT -p tcp --sport 1024: --dport 1024: -m state --state ESTABLISHED,RELATED,NEW -j ACCEPT

Basically what this does is tell iptables to open up FTP command port 21 and data port 20 for connection related to ones established on 21. It also allows the random ports >=1024 for related connections.
These rules apply for both active and passive connections.

    • Pierre
    • May 19th, 2014 6:53pm

    I’ve been looking like crazy for this. Thank you!

    • someone
    • May 17th, 2015 9:45am

    Instead:
    -A OUTPUT -p tcp –sport 1024: –dport 1024: -m state –state ESTABLISHED,RELATED,NEW -j ACCEPT

    You can use:
    -A OUTPUT -p tcp –sport 1024: –dport 1024: -m state –state ESTABLISHED,RELATED -j ACCEPT

    But first You have to load kernel modules ip_conntrack and ip_conntrack_ftp:
    modprobe ip_conntrack
    modprobe ip_conntrack_ftp

    However, my rules are:

    modprobe ip_conntrack
    modprobe ip_conntrack_ftp

    iptables -A OUTPUT -p tcp –sport 1024:65535 –dport 20 \
    -m state –state ESTABLISHED -j ACCEPT

    iptables -A OUTPUT -p tcp -m tcp –sport 1024:65535 \
    –dport 21 -m state –state NEW,ESTABLISHED -j ACCEPT

    iptables -A OUTPUT -p tcp –sport 1024:65535 \
    –dport 1024:65535 -m state –state ESTABLISHED,RELATED -j ACCEPT

    iptables -A INPUT -p tcp –sport 20 –dport 1024:65535 \
    -m state –state ESTABLISHED,RELATED -j ACCEPT

    iptables -A INPUT -p tcp -m tcp -m multiport –sports 21,1024:65535 \
    –dport 1024:65535 -m state –state ESTABLISHED -j ACCEPT

  1. April 24th, 2015