Before setting ftp rules through iptables, you must first understand the two modes in which ftp works: Active mode and passive mode. If you are not clear about the ftp principles, refer to the following articles.
FTP overview
1. Differences between active and passive FTP modes
2. Active FTP vs. Passive FTP, a Definitive Explanation
In short, the active mode initiates a connection from the server to the client, and the passive mode initiates a connection from the client to the server. Both use PORT 21 for user authentication and management. The difference is that the data transmission method is different, and the PORT of the FTP server is fixed at PORT 20, PASV mode is random between 1025-65535.
After learning about ftp principles, set iptables rules. On my own server, the default INPUT rule is DROP and OUTPUT is ACCEPT.
Command
1. Open ports 21 and 20
# Iptables-a input-p tcp -- dport 20-j ACCEPT
# Iptables-a input-p tcp -- dport 21-j ACCEPT
If the OUTPUT is also DROP by default, you need to add a rule.
# Iptables-a output-p tcp -- sport 20-j ACCEPT
2. Accept all connections in the status of ESTABLISHED and RELATED.
# Iptables-a input-m state -- state ESTABLISHED, RELATED-j ACCEPT
Related status description:
The RELATED status may appear in a dual-channel service. For example, the control channel and data channel of the ftp service. The client sends a syn request to port 21 of the server, and the linux system in the middle changes to the NEW state. The server replies the syn + ack response packet to the client, and the linux in the middle changes to the ESTABLISHED status. After the ftp control channel is ESTABLISHED, a data channel is ESTABLISHED. The first package of the data channel is in the RELATED state, and the subsequent package changes to the ESTABLISHED state.
3. Configure iptables
# Vi/etc/sysconfig/iptables-config
Find IPTABLES_MODULES, uncomment, add the ip_conntrack_ftp module, and save. The ip_conntrack_ftp module allows iptables to support ftp connections in passive mode.
IPTABLES_MODULES = "ip_conntrack_ftp"
4. Save and restart iptables rules.
[Root @ iZ94myad6wkZ ~] # Service iptables save
Iptables: Saving firewall rules to/etc/sysconfig/iptables: [OK]
[Root @ iZ94myad6wkZ ~] # Service iptables restart
Iptables: Setting chains to policy ACCEPT: filter nat [OK]
Iptables: Flushing firewall rules: [OK]
Iptables: Unloading modules: [OK]
Iptables: Applying firewall rules: [OK]
Iptables: Loading additional modules: ip_conntrack_ftp [OK]
Restarting iptables is the address of an additional loading module. OK is normal.