Iptables: Open and Close Port in Linux

Valic —  January 27, 2011 — 1 Comment

For more secure server, we have to close some ports to users.

If need access to this ports, we can give permission to our IP address.  Please dont forget, “iptables” can be block all IP address but when you restart the server it will be clean all of this commands.

Examples:

1. Closing FTP port except xxx.xxx.xxx.xxx

iptables -t filter -I INPUT 1 -p tcp -s ! xxx.xxx.xxx.xxx –dport 21 -j REJECT –reject-with icmp-host-prohibited

2. Closing SSH port except xxx.xxx.xxx.xxx

iptables -t filter -I INPUT 1 -p tcp -s ! xxx.xxx.xxx.xxx –dport ssh -j REJECT –reject-with icmp-host-prohibited

3. Closing MySQL port except localhost

iptables -A INPUT -i eth0 -s 192.168.1.0/24 -p tcp –destination-port 3306 -j ACCEPT

4. Listing iptables list

iptables -L

5. Removing iptables data (Removing first one in list, type 2 for second one)

iptables -D INPUT 1

Valic

Posts Twitter Facebook

Editor in Chief at Debian-Tutorials, Linux enthusiast.

One response to Iptables: Open and Close Port in Linux

  1. Looks good. Tried to block the NTP port, but failed :(

    # iptables -t filter -I INPUT 1 -p udp -s ! 127.0.0.1 –dport ntp -j REJECT –reject-with icmp-host-prohibited
    Using intrapositioned negation (`–option ! this`) is deprecated in favor of extrapositioned (`! –option this`).
    Bad argument `–dport’
    Try `iptables -h’ or ‘iptables –help’ for more information.

    ( Of course I tried with ntp.conf, but this did not work either:-
    restrict -4 default kod nomodify notrap nopeer
    restrict -6 default kod nomodify notrap nopeer
    restrict -4 127.0.0.1
    restrict -6 ::1)

    lsof -i udp:123
    COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
    ntpd 11011 ntp 16u IPv4 478025 0t0 UDP *:ntp
    ntpd 11011 ntp 17u IPv6 478026 0t0 UDP *:ntp
    ntpd 11011 ntp 18u IPv4 478032 0t0 UDP localhost:ntp
    ntpd 11011 ntp 19u IPv4 478033 0t0 UDP logout:ntp
    ntpd 11011 ntp 20u IPv6 478034 0t0 UDP ip6-localhost:ntp
    ntpd 11011 ntp 21u IPv6 478035 0t0 UDP [0::aaaa:aaaa:aaaa:aaaa]:ntp

    I have stopped using NTP and now run ntpdate every min from cron.

    Oh well.

Leave a Reply