On This Page

  1. See Also

Configure iptables on Linux based machines

Iptables is a firewall, installed by default on most of official Linux distributions. There are lots of wrappers around iptables that helps to work with it (for example, iptables-persitent), but this article will describe how quickly configure persitent rules working only with iptables:

  1. Make default file with iptables rules
    sudo sh -c "iptables-save > /etc/iptables.up.rules"
  2. Open iptables file in an editor. Below examples of default rules and filter INPUT as well as OUTPUT traffic on the server. Please, make sure that you understand each line in the file.
    *filter
    :INPUT DROP [547:54997]
    :FORWARD DROP [0:0]
    :OUTPUT DROP [414:39310]
    
    # INPUT RULES
    -A INPUT -i lo -m comment --comment "Allow all from localhost" -j ACCEPT
    -A INPUT -p icmp -m icmp --icmp-type 8 -m comment --comment "Allow pings" -j ACCEPT
    -A INPUT -m state --state RELATED,ESTABLISHED -m comment --comment "Accept already established connections" -j ACCEPT
    
    # SSH Acccess, specify your current Ip address, check it here https://whoer.net/
    -A INPUT -p tcp --dport 22 -s <ip1>,<ip2> -m comment --comment "SSH Access" -j ACCEPT
    
    -A INPUT -p tcp -m multiport --dports 80,443 -m state --state NEW -m comment --comment "HTTP(s) Access to web sites" -j ACCEPT
    
    # OUTPUT RULES
    -A OUTPUT -o lo  -m comment --comment "Allow all to localhsot" -j ACCEPT
    -A OUTPUT -m state --state ESTABLISHED,RELATED -m comment --comment "Allow already established connections" -j ACCEPT
    -A OUTPUT -p udp --dport 123 -m comment --comment "To ntp services" -j ACCEPT
    
    # List of DNS servers, use cat /etc/resolv.conf command to detect the current DNS Server, below only an example
    -A OUTPUT -p udp --dport 53 -d 8.8.8.8,8.8.4.4 -m comment --comment "To DNS Servers" -j ACCEPT
    -A OUTPUT -p tcp --dport 53 -d 8.8.8.8,8.8.4.4 -m comment --comment "To DNS Servers" -j ACCEPT
    
    # Dhound configuration. allow access to dhound gate, ping gate.dhound.io
    -A OUTPUT -d 88.99.62.145 -p tcp --dport 443 -m comment --comment "Access to gate.dhound.io" -j ACCEPT
    
    # example to allow all traffic to another server,
    # -A OUTPUT -d 10.50.0.2 -j ACCEPT
    
    COMMIT
    
  3. Save file and upload rules into iptables
    sudo iptables-restore < /etc/iptables.up.rules
  4. Check current list of loaded rules into
    sudo iptables --list
  5. If everything is ok, time to add it into boot load:
    sudo nano /etc/network/interfaces
    Add the following line for a particular interface:
    pre-up iptables-restore < /etc/iptables.up.rules
    A fully working example:
    auto eth0
    iface eth0 inet dhcp
      pre-up iptables-restore < /etc/iptables.up.rules

See Also

Published on May 15, 2017