iptables commands


linux firewall hugo

Linux Router

  1. If you need to set up your Slackware Linux machine as a router for other systems, you’ll want to set up the interfaces in /etc/rc.d/rc.inet1.conf, and set up NAT support with something like this in /etc/rc.d/rc.firewall, and then make rc.firewall executable.
    # Delete and flush.  Default table is "filter".
    # Others like "nat" must be explicitly stated.
    iptables --flush
    # Flush all the rules in filter and nat tables
    iptables --table nat --flush
    # Delete all chains that are not in default filter and nat table
    iptables --delete-chain
    iptables --table nat --delete-chain
    # Set up IP FORWARDing and Masquerading
    iptables --table nat --append POSTROUTING --out-interface eth0 -j MASQUERADE
    iptables --append FORWARD --in-interface eth1 -j ACCEPT
    echo "Enabling ip_forwarding..."
    echo 1 > /proc/sys/net/ipv4/ip_forward
  1. Save & Restore rules
iptables-save > /etc/iptables.rules

Put in /etc/rc.d/rc.local

iptables-restore /etc/iptables.rules
  1. Blocking with iptables

Following iptable rule will drop incoming connection from host/IP 202.54.20.22:

iptables -A INPUT -s 202.54.20.22 -j DROP
iptables -A OUTPUT -d 202.54.20.22 -j DROP

A simple shell script to block lots of IP address If you have lots of IP address use the following shell script:

Create a text file: ( vi /root/ip.blocked ). Now append IP address:

    # Ip address block  file
    202.54.20.22
    202.54.20.1/24
    65.66.36.87

Create a script as follows or add following script line to existing iptables shell script:

    BLOCKDB='/root/ip.blocked'
    IPS=$(grep -Ev "^#" $BLOCKDB)
    for i in $IPS
    do
    iptables -A INPUT -s $i -j DROP
    iptables -A OUTPUT -d $i -j DROP
    done

Save & close the file. Execute the file.

iptables basic rules

iptables tutorial on digital ocean for centos.

iptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP
iptables -A INPUT -p tcp ! --syn -m state --state NEW -j DROP
iptables -A INPUT -p tcp --tcp-flags ALL ALL -j DROP
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -p tcp -m tcp --dport 81 -j ACCEPT
iptables -A INPUT -p tcp -m tcp --dport 443 -j ACCEPT
iptables -A INPUT -p tcp -m tcp --dport 1891 -j ACCEPT    (custom ssh 1891)
iptables -A INPUT -p tcp -s YOUR_IP_ADDRESS -m tcp --dport 1891 -j ACCEPT (ssh only from one ip)
iptables -I INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -P OUTPUT ACCEPT
iptables -P INPUT DROP

iptables -L -n
iptables-save | sudo tee /etc/sysconfig/iptables
chkconfig --level 35 iptables on
service iptables restart