Iptables how to.


Updated today: Saturday, November 19, 2011
Reason: I’ve added (and updated) my

/etc/iptables.rules

and

/etc/ip6tables.rules

files to this post.

Today I am going to write about firewalls, the linux firewall aka netfilter/iptables to be precise.

So what is a firewall? To my understanding that would be like an imaginary ‘wall of fire’ which tends to keep the bad guys out and the good guys in (can be taken literally!) whatever it is the firewall was meant to protect.

In this sense a firewall may not be of use to you!?

Because:
Obviously, one wants to keep the bad guys out; while at the same time one wants to be able to traverse to and fro the firewall unencumbered. Which basically is what this script intends to give you. 😉 Another intent of this author is for you not to have to fiddle to much with your current router (except when the need arises to enable a service), whether this be the one at home or at your local wifi supplying bar. Or in somewhat more foul language (plain folk speak if you will): I want to be able to plug in my “lappie” in any slut sorry I meant {slot,socket} available 😆 and just go go go…

Strictly speaking: A firewall can’t protect you from a(ny) mis configured serv{ice,ices,er,ers} because to be able to make use of any service, one has to punch a (lot of) hole(s) in his/her firewall, hence there is no benefit gained by applying a firewall with holes. 😆

Since the reliance of any user on the ‘bulletproof‘ coding of any service is way beyond the scope of this tutorial. I advice you to either NOT run any service or that you look into subjects as ‘apparmor‘ing or (||) SeLinux‘ing your applications and (&&) make use of intrusion systems like snort or ossec-hids.

Another advice that I could give is to NOT simply download away all that is available (this although not self serving would include the usage of my own scripts amongst things) on the net but stick to the repositories made available to you by your distribution when a certain piece of software is needed. Also if the need exists to run a torrent client. 😉 One could consider to run this under another unprivileged account [think kde platform 😉 ] (e.g. ktorrent (this user is biased though :lol:)).

Now that I’ve taken care of these dependencies:

If one searches for intel, then one will find out that there is an abundance of information out there about precisely this subject.

The script I made (which for all purposes should be considered experimental) attempts to be a mix of the above three links. Regardless of the fact that I made a fairly benign script (it only echoes at ye for now) it is advisable/to be recommended that a ‘newbie‘ either turns his attention to the IptablesHowTo of the Ubuntu community or simply installs firestarter (http://www.fs-security.com/).

So do I really need one!
http://psychocats.net/ubuntu/security#firewallantivirus

“Why (should I try to) reinvent the wheel when someone else already has pointed out a similar stance on the matter.”

So, do I need a firewall, anti-virus, anti-spyware tools?

By default, Ubuntu ships with no open ports on public interfaces. In other words, a “port scan” would show all closed ports, nothing open. As a result, putting up a firewall would provide no more security than not putting one up. Remember that open ports provide services that hackers can connect to, and only if they can connect to these services can they be potentially abused and exploited.

A firewall, however, adds the benefit of peace-of-mind from accidentally installing a server program that opens up a port by default. Also, it satisfies curiousity by logging potential “hits.” Linux comes with a very strong, secure, and powerful firewall called iptables, but it is relatively difficult to use from a new user’s standpoint. As a result, there are many graphical tools that give you a simple user interface for configuring iptables, such as Firestarter for GNOME or Guarddog for KDE. There are many more in the repository, too. Remember—these all use iptables in the background, so find your favorite interface—they all offer the same great protection. [These last two paragraphs contributed by jdong from the Ubuntu Forums. Thanks, jdong!]

With all that out of the way let’s start describing this script.

The color codes used in the script below have the following purposes:
$RED= Error!
$BLUE= Tries to explain what is being done
$CYAN= The actual code that would be executed if this script were ‘live’.
$YELLOW= Warning, aka there’s something you need to do first before you can continue
$NC= ‘No Color’ nothing more to it. Think of it as the closing bracket to whatever line it has been implemented.

Now about those color definitions:
(These start around line 54)

## For these colors to work either uncomment the next 5 lines.
#RED="\033[0;31m"
#BLUE="\033[1;34m"
#CYAN="\033[1;36m"
#YELLOW="\033[1;33m"
#NC="\033[0m"              # No Color
#
## OR...
#
## Paste the following lines in your ~/.bashrc file for a more 'global feel'. ; - )
## (At the bottom is recommended.)
## Do uncomment those first before resourcing your ~/.bashrc file. ; - )
## http://tldp.org/LDP/abs/html/sample-bashrc.html
## Define some colors first:
#RED="\033[0;31m"
#export RED
#BLUE="\033[1;34m"
#export BLUE
#CYAN="\033[1;36m"
#export CYAN
#YELLOW="\033[1;33m"
#export YELLOW
#NC="\033[0m"              # No Color
#export NC
# --> Nice. Has the same effect as using "ansi.sys" in DOS.
## Don't forget to resource your bashrc file!

Aside from all that, I believe it really ‘cutsyfies’ the script. 😉

*The focus should be on the execution of commands and not the prompt.*

While true, I believe colorizing commands in this fashion actually helps explaining what is being done.

Anyway:
If for any reason you feel “obliged” to use this script (not recommended (yet)) or you feel adventurous (most likely :lol:). Then I recommend that you use this startup script! The only difference in between the one posted below and the one used here: Configuration on Startup for NetworkManager
is that I ALSO USE ip6tables to block, drop, reject anything that is not of use to me!

For now, I bid you adieu and “may you live long prosper” or “may the force be with you” 😆

Kindest regards,

Alex


The StartUp Script goes here:

if [ -x /usr/bin/logger ]; then
        LOGGER="/usr/bin/logger -s -p daemon.info -t FirewallHandler"
else
        LOGGER=echo
fi

case "$2" in
        up)
                if [ ! -r /etc/iptables.rules ]; then
                        ${LOGGER} "No iptables rules exist to restore."
                        return
                fi
                if [ ! -r /etc/ip6tables.rules ]; then
                        ${LOGGER} "No iptables rules exist to restore."
                        return
                fi
                if [ ! -x /sbin/iptables-restore ]; then
                        ${LOGGER} "No program exists to restore iptables rules."
                        return
                fi
                ${LOGGER} "Restoring iptables rules"
                /sbin/iptables-restore -c < /etc/iptables.rules
                /sbin/ip6tables-restore -c < /etc/ip6tables.rules                
                ;;
        down)
                if [ ! -x /sbin/iptables-save ]; then
                        ${LOGGER} "No program exists to save iptables rules."
                        return
                fi
                if [ ! -x /sbin/ip6tables-save ]; then
                        ${LOGGER} "No program exists to save iptables rules."
                        return
                fi
                ${LOGGER} "Saving iptables rules."
                /sbin/iptables-save -c > /etc/iptables.rules
                /sbin/ip6tables-save -c > /etc/ip6tables.rules                
                ;;
        *)
                ;;
esac

The HowTo Script goes here:
7 feb. 2011: Slowly but surely we’re getting nearer to the end. 😉
Also the astute {reader,viewer} will notice a minor mistake in both the script as well in the video. If you have {guessed,seen} it, then you most likely can determine that I am aware of it. 😉

I should for example include a line like: kill -USR1 “$PROCESS”. To gently kill processes (other than services that run from start up) that create open sockets while using this script.

For transparency’s sake I’m not going to remove my small mistake, besides what was about to be done was only echoed after all and I am here to learn from my own mistakes as well. 😉

#!/bin/bash
# http://en.support.wordpress.com/code/posting-source-code/
# Modified: Today by E.l.f
#
## http://www.gnu.org/copyleft/gpl.html
#
## Script-name - Conf.Iptables.sh
#
## Scripts executed by root should imo be written with capitals.
## Perhaps preceded with an 'S' to indicate sudo\?
## Which should provide the user a hint about the importance given to said script.
#
## This is a slightly modified version of my current iptables ruleset.
## I also tossed it about a bit for readability, think cascade.
# Sources and other related info.
## No endorsement or approval (from the respective authors) implied
## by linking to these sources.
# https://help.ubuntu.com/community/IptablesHowTo
# http://bodhizazen.net/Tutorials/iptables/#Using_iptables_for_Filtering
# http://www.novell.com/coolsolutions/feature/18139.html
#<----------------------------------------------------------------------------->
## eth0=the interface facing the internet in my case.
## Use at your own risk!
#
# Assumptions:
## A Gnu/linux (compliant) or clone thereof box.
## The client has a simple gateway at home, i.e. a router provided by his/her ISP.
## The interface used for both in and outbound traffic is named eth0
#
## There may be a wireless card on the user\'s computer (do you use one?)?
## In that case either substitute eth0 with the name of the wifi one,
## or make duplicates of the rules referring to eth0 to apply to both interfaces.
#
## NEVER EVER use this script on a remote machine!!!
## Instant lockout IS guaranteed if you do.
## Included a check to counter PRECISELY that.
#
## Script starts here.
# Define some colors first:
RED="\033[0;31m"
BLUE="\033[1;34m"
CYAN="\033[1;36m"
YELLOW="\033[1;33m"
NC="\033[0m"              # No Color
# --> Nice. Has the same effect as using "ansi.sys" in DOS.
echo -e ${YELLOW}"    What works for me:"${NC}
echo -e ${YELLOW}"    Neither has to apply to you nor does it have to imply"${NC}
echo -e ${YELLOW}"    that it will work for you!?"${NC}
echo -e ${YELLOW}"    Therefore your mileage may vary?"${NC}
echo
echo -e ${YELLOW}"    Since this script is far from being complete!"${NC}
echo -e ${YELLOW}"    And because it is part of my learning experience."${NC}
echo -e ${YELLOW}"    It will only echo (for now) what it is about to execute."${NC}
echo
#if [ $USER != root ]; then
#  echo -e ${RED}"    Only root can do this!"${NC}
#  echo -e ${CYAN}"    Error: In order to use this script, one must NOT be "$USER"!"${NC}
#  echo -e ${CYAN}"    Hint: Use 'sudo -s' and try again."${NC}
#  echo -e ${YELLOW}"    Exiting..."${NC}
#  exit 0
#else
#  echo ""
#  echo -e ${BLUE}"    "$USER" may proceed."${NC}
#  echo -e ${CYAN}"    May peace be with you."${NC}
#fi
clear
echo
echo -e ${BLUE}"    Because I can't determine (yet) if you're logged into a remote machine."${NC}
echo -e ${YELLOW}"    I'll ask you now:  Are you logged in remotely?"${NC}
echo
  echo -n "Enter either yes or no: "
  read ANSWER
    case "$ANSWER" in
    "YES" | "Yes" | "yes")
    echo -e ${RED}"    Not a smart move on your part!"${NC}
    echo -e ${YELLOW}"    Exiting now before you can hurt yourself..."${NC}
    exit 0
    ;;
    "NO" | "No" | "no")
    echo -e ${BLUE}"    Please continue... oh wise, great and powerful one."${NC}
    echo
    ;;
    *)
    echo -e ${RED}"    Wrong answer!!!"
    echo -e ${BLUE}"    Please rerun the script again?"
    echo -e ${BLUE}"    Then: Either enter yes or no."
    echo -e ${BLUE}"    \"UPPER\", \"lower\" and \"Capitalized\" spelling are supported"
    echo -e ${CYAN}"    Usage: Yes|No"${NC}
    echo
    exit 0
    ;;
    esac
## This appears to be a promising start.
## Kindly ripped from the torbrowser bundle start up script.
# if any relevant processes are running, inform the user and exit cleanly
## I need to find an alternative to shut down boinc-client?
# boinc: unrecognized service (=user boinc and not service boinc-client)
## Without editing the /etc/init.d/boinc-client script.
## The intent is to have NO SERVICE()S) running while editing the firewall!
## Please edit in your own services as needed.
for process in apache ktorrent polipo privoxy thttpd tor transmission vidalia
do pid=$(pidof $process)
if [ -n "$pid" ]
then
echo -e ${YELLOW}"\n$process is already running as PID $pid\n\n"${NC}
echo -e ${BLUE}"    To continue this script it is advisable to shut down $process."${NC}
echo -e ${YELLOW}"    Do you want me to shut those down for you?"${NC}
echo
  echo -n "Enter either yes or no: "
  read ANSWER
    case "$ANSWER" in
    "YES" | "Yes" | "yes")
    echo -e ${CYAN}"service \"$process\" stop"${NC}
    ;;
    "NO" | "No" | "no")
    echo -e ${BLUE}"    To continue this script it is advisable to shut down $process."${NC}
    exit 0
    ;;
    *)
    echo -e ${RED}"    Wrong answer!!!"
    echo -e ${BLUE}"    Please rerun the script again?"
    echo -e ${BLUE}"    Then: Either enter yes or no."
    echo -e ${BLUE}"    \"UPPER\", \"lower\" and \"Capitalized\" spelling are supported"
    echo -e ${CYAN}"    Usage: Yes|No"${NC}
    echo
    exit 0
    ;;
    esac
fi
done
echo -e ${YELLOW}"    Saving your current configuration (just in case)!"${NC} #If any!?
echo -e ${CYAN}"iptables-save > /etc/iptables.rules.jic"${NC}
echo -e ${CYAN}"iptables-save -c > /etc/iptables.save.jic"${NC}
echo
  echo -e ${YELLOW}"    This WILL flush your current iptables ruleset."${NC}
  echo -e ${YELLOW}"    Do you wish to continue?"${NC}
  echo -e ${BLUE}"    If unsure then either type \"no\" or simply hit \"enter\" to abort."${NC}
  echo -n "Enter either yes or no: "
  read Answer
    case "$Answer" in
    "YES" | "Yes" | "yes")
    echo -e ${RED}"   Executing..."${NC}
    echo -e ${YELLOW}"    Reset firewall..."${NC}
    echo -e ${CYAN}"iptables -F"${NC}
    echo -e ${CYAN}"iptables -X"${NC}
    echo -e ${CYAN}"iptables -t nat -F"${NC}
    echo -e ${CYAN}"iptables -t nat -X"${NC}
    echo -e ${CYAN}"iptables -t mangle -F"${NC}
    echo -e ${CYAN}"iptables -t mangle -X"${NC}
    echo -e ${YELLOW}"    All rules flushed!"${NC}
    ;;
    "NO" | "No" | "no")
     echo -e ${CYAN}"    Maybe later..."${NC}
     exit 0
    ;;
    *)
     echo -e ${RED}"    Wrong answer!!!"
     echo -e ${BLUE}"    Please rerun the script again?"
     echo -e ${BLUE}"    Then: Either enter yes or no."
     echo -e ${BLUE}"    \"UPPER\", \"lower\" and \"Capitalized\" spelling are supported"
     echo -e ${CYAN}"    Usage: Yes|No"${NC}
     echo
     exit 0
    ;;
    esac
  echo -e ${BLUE}"    I don't see any reason whatsoever, "${NC}
  echo -e ${BLUE}"    to allow any inbound traffic unless I choose to run a server. "${NC}
  echo -e ${BLUE}"    A torrent client IS of type server! "${NC}
  echo
  echo -e ${YELLOW}"    Do you wish to continue?"${NC}
  echo -e ${BLUE}"    If unsure then either type \"no\" for the default (ACCEPT) or simply hit \"enter\" to abort."${NC}
  echo -n "Enter either yes or no: "
  read Answer
    case "$Answer" in
    "YES" | "Yes" | "yes")
    echo -e ${CYAN}"iptables -P INPUT DROP"${NC}
    echo -e ${CYAN}"iptables -P FORWARD DROP"${NC}
    echo -e ${CYAN}"iptables -P OUTPUT DROP"${NC}
    echo -e ${YELLOW}"    Policy (DROP) is set and enabled!"${NC}
    ;;
    "NO" | "No" | "no")
    echo -e ${YELLOW}"   Maybe later..."${NC}
    echo -e ${CYAN}"iptables -P INPUT ACCEPT"${NC}
    echo -e ${CYAN}"iptables -P FORWARD ACCEPT"${NC}
    echo -e ${CYAN}"iptables -P OUTPUT ACCEPT"${NC}
    echo -e ${YELLOW}"    Policy (ACCEPT) \"default\" is set and enabled!"${NC}
    ;;
    *)
    echo -e ${RED}"    Wrong answer!!!"
    echo -e ${BLUE}"    Please rerun the script again?"
    echo -e ${BLUE}"    Then: Either enter yes or no."
    echo -e ${BLUE}"    \"UPPER\", \"lower\" and \"Capitalized\" spelling are supported"
    echo -e ${CYAN}"    Usage: Yes|No"${NC}
    echo
    exit 1
    ;;
    esac
echo -e ${BLUE}"    Setting some sane defaults (OUTPUT) here."${NC}
echo -e ${CYAN}"iptables -A OUTPUT -o lo -j ACCEPT"${NC}
echo -e ${CYAN}"iptables -A OUTPUT -o eth0 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT"${NC}
echo -e ${BLUE}"    You do want to be able to update/upgrade and install stuff."${NC}
echo -e ${CYAN}"iptables -A OUTPUT -o eth0 -m owner --uid-owner 0 -j ACCEPT"${NC} # root
## Granting a few other users access here.
## Which in my case refers to the following.
# cat /etc/group | grep <name of group>
# iptables -A OUTPUT -o eth0 -m owner --uid-owner debian-tor -j ACCEPT # debian-tor
# iptables -A OUTPUT -o eth0 -m owner --uid-owner boinc-client -j ACCEPT # boinc-client
echo -e ${BLUE}"    You also want to be able to surf the web, email friends and all that other good stuff."${NC}
echo -e ${CYAN}"iptables -A OUTPUT -o eth0 -m owner --uid-owner 1000 -j ACCEPT"${NC} # you
# iptables -A OUTPUT -o eth0 -m owner --uid-owner 1001 -j ACCEPT # another you
echo -e ${BLUE}"    We don't need to wait for connection time outs!"${NC}
echo -e ${CYAN}"iptables -A OUTPUT -p tcp -j REJECT --reject-with tcp-reset"${NC}
echo -e ${CYAN}"iptables -A OUTPUT -p udp -j REJECT --reject-with icmp-port-unreachable"${NC}
echo -e ${YELLOW}"    Outbound traffic enabled."${NC}
echo
echo -e ${BLUE}"    Next we are going to create some user defined chains, we will need them later."${NC}
echo -e ${CYAN}"iptables -N blacklist"${NC}
echo -e ${CYAN}"iptables -N icmp"${NC}
echo -e ${CYAN}"iptables -N tobesortedout"${NC}
echo -e ${CYAN}"iptables -N logndrop"${NC}
## Bozo check.
echo -e ${CYAN}"iptables -A INPUT -j blacklist"${NC}
  echo -e ${BLUE}"    The following ipadresses, I have collected over time, are known to scan for "${NC}
  echo -e ${BLUE}"    vulnerabilities in webapplications.  Not that I run any, duh..."${NC}
  echo -e ${BLUE}"    e.g."${NC}
  echo -e ${YELLOW}"    iptables -A blacklist -s <source-ip>(/32) -j REJECT --reject-with icmp-host-prohibited"${NC}
  echo -e ${YELLOW}"    iptables -A blacklist -s <source-net>(/24) -j REJECT --reject-with icmp-net-prohibited"${NC}
  echo -e ${BLUE}"    Placing an octothorpe --> # in front of the following lines,"${NC}
  echo -e ${BLUE}"    obviously will disable the referred to rule."${NC}
  echo -e ${BLUE}"    Deleting them is so much easier!  : - )"${NC}
  echo -e ${BLUE}"    When?"${NC}
  echo -e ${BLUE}"    You don't run or want to run (ever) some service."${NC}
  echo
  echo -e ${YELLOW}"    Do you wish to keep them (NOT mandatory)?"${NC}
  echo -e ${BLUE}"    If unsure then either type \"no\" or simply hit \"enter\" to abort."${NC}
  echo -n "Enter either yes or no: "
  read aNSWER
    case "$aNSWER" in
    "YES" | "Yes" | "yes")
    echo -e ${CYAN}"iptables -A blacklist -s 222.76.86.104/32 -j REJECT --reject-with icmp-host-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 218.249.107.12/32 -j REJECT --reject-with icmp-host-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 218.38.12.202/32 -j REJECT --reject-with icmp-host-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 218.14.146.200/32 -j REJECT --reject-with icmp-host-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 217.133.138.220/32 -j REJECT --reject-with icmp-host-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 216.245.217.242/32 -j REJECT --reject-with icmp-host-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 202.194.15.192/32 -j REJECT --reject-with icmp-host-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 202.108.181.80/32 -j REJECT --reject-with icmp-host-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 122.95.3.74/32 -j REJECT --reject-with icmp-host-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 92.243.84.187/32 -j REJECT --reject-with icmp-host-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 86.125.221.212/32 -j REJECT --reject-with icmp-host-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 85.17.187.145/32 -j REJECT --reject-with icmp-host-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 84.45.126.182/32 -j REJECT --reject-with icmp-host-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 84.153.229.140/32 -j REJECT --reject-with icmp-host-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 79.99.42.182/32 -j REJECT --reject-with icmp-host-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 212.26.193.0/24 -j REJECT --reject-with icmp-net-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 208.80.194.0/24 -j REJECT --reject-with icmp-net-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 208.80.193.0/24 -j REJECT --reject-with icmp-net-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 84.74.177.0/24 -j REJECT --reject-with icmp-net-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 84.74.176.0/24 -j REJECT --reject-with icmp-net-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 84.74.146.0/24 -j REJECT --reject-with icmp-net-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 84.74.144.0/24 -j REJECT --reject-with icmp-net-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 80.218.7.0/24 -j REJECT --reject-with icmp-net-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 80.218.6.0/24 -j REJECT --reject-with icmp-net-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 80.218.5.0/24 -j REJECT --reject-with icmp-net-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 80.218.4.0/24 -j REJECT --reject-with icmp-net-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 80.218.3.0/24 -j REJECT --reject-with icmp-net-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 80.218.2.0/24 -j REJECT --reject-with icmp-net-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 80.218.1.0/24 -j REJECT --reject-with icmp-net-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 80.218.0.0/24 -j REJECT --reject-with icmp-net-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 71.130.111.0/24 -j REJECT --reject-with icmp-net-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -j icmp"${NC}
    echo -e ${YELLOW}"    Known repeaters are blocked by default!"${NC}
    ;;
    "NO" | "No" | "no")
    echo -e ${BLUE}"    Don't delete this one!"${NC}
    echo -e ${CYAN}"iptables -A blacklist -j icmp"${NC}
    ;;
    *)
    echo -e ${BLUE}"    Please rerun the script again?"
    echo -e ${BLUE}"    Then: Either enter yes or no."
    echo -e ${BLUE}"    \"UPPER\", \"lower\" and \"Capitalized\" spelling are supported"
    echo -e ${CYAN}"    Usage: Yes|No"${NC}
    echo
    echo -e ${RED}"   Executing...(again)"${NC}
    echo -e ${YELLOW}"    Reset firewall..."${NC}
    echo -e ${CYAN}"iptables -F"${NC}
    echo -e ${CYAN}"iptables -X"${NC}
    echo -e ${CYAN}"iptables -t nat -F"${NC}
    echo -e ${CYAN}"iptables -t nat -X"${NC}
    echo -e ${CYAN}"iptables -t mangle -F"${NC}
    echo -e ${CYAN}"iptables -t mangle -X"${NC}
    echo -e ${YELLOW}"    All rules flushed!"${NC}
    echo -e ${YELLOW}"    So you can start fresh again."${NC}
    echo
    exit 0
    ;;
    esac
echo
echo -e ${BLUE}"    The ping utility is a must, whether you believe me or not."${NC}
echo -e ${BLUE}"    Sings *Black hole sun won't you come*"${NC}
echo -e ${CYAN}"iptables -A icmp -p icmp -m icmp --icmp-type 0 -j ACCEPT"${NC}
echo -e ${CYAN}"iptables -A icmp -p icmp -m icmp --icmp-type 3 -j ACCEPT"${NC}
echo -e ${CYAN}"iptables -A icmp -p icmp -m icmp --icmp-type 11 -j ACCEPT"${NC}
echo -e ${CYAN}"iptables -A icmp -p icmp -m icmp --icmp-type 8 -m limit --limit 1/sec -j ACCEPT"${NC}
echo -e ${CYAN}"iptables -A icmp -j tobesortedout"${NC}
echo -e ${YELLOW}"    Ping permissions set."${NC}
echo
echo -e ${BLUE}"    Setting some sane defaults (INPUT) here."${NC}
echo -e ${CYAN}"iptables -A tobesortedout -i lo -j ACCEPT"${NC}
echo -e ${CYAN}"iptables -A tobesortedout -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT"${NC}
echo -e ${BLUE}"    From here on out, it is up to you to allow inbound traffic or not."${NC}
echo -e ${BLUE}"    Don't forget to setup your router to set the port of your choice to open!"${NC}
echo
#echo -e ${BLUE}"    Despite the fact that thttpd (Tiny hyper text transfer protocol daemon) is well known for"${NC}
#echo -e ${BLUE}"    being able to serve up a surplus of 1000+ files "${NC}
#echo -e ${BLUE}"    and thus becomes better under pressure.  ; - )"${NC}
#echo -e ${BLUE}"    I've decided to \"rate limit\" the amount of simultaneous connections to this server!"${NC}
## webserver
#echo -e ${CYAN}"iptables -A tobesortedout -i eth0 -p tcp -m state --state NEW -m limit --limit 20/sec --limit-burst 40 -m tcp --dport 80 -j ACCEPT"${NC}
#echo -e ${BLUE}"    Please note that from my perspective: anything lower than 20 per second causes a noticeable lag while loading my own pages.  ; - )"${NC}
echo -e ${CYAN}"iptables -A tobesortedout -j logndrop"${NC}
echo -e ${YELLOW}"I've configured the minimum amount of incomming traffic for you."${NC}
echo
echo -e ${BLUE}"    Surely we want to know, who we've denied while trying to access this server?"${NC}
echo -e ${CYAN}"iptables -A logndrop -p tcp -m limit --limit 5/min -j LOG --log-prefix "Denied TCP: " --log-level 7"${NC}
echo -e ${CYAN}"iptables -A logndrop -p udp -m limit --limit 5/min -j LOG --log-prefix "Denied UDP: " --log-level 7"${NC}
echo -e ${CYAN}"iptables -A logndrop -p icmp -m limit --limit 5/min -j LOG --log-prefix "Denied ICMP: " --log-level 7"${NC}
echo -e ${BLUE}"    Be a good netizen, simply  because we don't like to wait for connections, "${NC}
echo -e ${BLUE}"    to time out on ourselves."${NC}
echo -e ${CYAN}"iptables -A logndrop -p tcp -j REJECT --reject-with tcp-reset"${NC}
echo -e ${CYAN}"iptables -A logndrop -p udp -j REJECT --reject-with icmp-port-unreachable"${NC}
echo -e ${YELLOW}"    Logging enabled"${NC}
echo
echo -e ${YELLOW}"    I've also turned back on any services you had running before using this script."${NC}
## Work in progress!
# sudo service $DAEMON start
## e.g.
echo -e ${CYAN}"service boinc-client start"${NC}
echo -e ${CYAN}"service polipo start"${NC}
echo -e ${CYAN}"service tor start"${NC}
echo -e ${CYAN}"service thttpd start"${NC}
echo
echo -e ${YELLOW}"    My job is done."${NC}
echo -e ${YELLOW}"    Have a nice day!"${NC}
echo
echo -e ${YELLOW}"    Don't forget to save your new rules!"${NC}
echo -e ${CYAN}"iptables-save > /etc/iptables.rules"${NC}
echo
echo -e ${BLUE}"    #<----------------------------------------------------------------------------->"${NC}
echo -e ${BLUE}"    ## How about ipv6!?  Well since I am not using it anyway."${NC}
echo -e ${BLUE}"    ## (I doubt my router even understands it?)"${NC}
echo -e ${BLUE}"    ## This part refers to the contents of (a future) /etc/ip6tables.rules, "${NC}
echo -e ${BLUE}"    ## if one follows the ubuntu community tutorial that is."${NC}
echo -e ${BLUE}"    #<----------------------------------------------------------------------------->"${NC}
echo -e ${CYAN}"#ip6tables -P INPUT DROP"${NC}
echo -e ${CYAN}"#ip6tables -P FORWARD DROP"${NC}
echo -e ${CYAN}"#ip6tables -P OUTPUT DROP"${NC}
echo -e ${CYAN}"#ip6tables -N logndropip6"${NC}
echo -e ${CYAN}"#ip6tables -A INPUT -p tcp -j REJECT --reject-with tcp-reset"${NC}
echo -e ${CYAN}"#ip6tables -A INPUT -p udp -j REJECT --reject-with icmp-port-unreachable"${NC}
echo -e ${CYAN}"#ip6tables -A OUTPUT -j logndropip6"${NC}
echo -e ${CYAN}"#ip6tables -A logndropip6 -p tcp -m limit --limit 5/min -j LOG --log-prefix "Denied ipv6 TCP: " --log-level 7"${NC}
echo -e ${CYAN}"#ip6tables -A logndropip6 -p udp -m limit --limit 5/min -j LOG --log-prefix "Denied ipv6 UDP: " --log-level 7"${NC}
echo -e ${CYAN}"#ip6tables -A logndropip6 -p icmp -m limit --limit 5/min -j LOG --log-prefix "Denied ipv6 ICMP: " --log-level 7"${NC}
echo -e ${CYAN}"#ip6tables -A logndropip6 -p tcp -j REJECT --reject-with tcp-reset"${NC}
echo -e ${CYAN}"#ip6tables -A logndropip6 -p udp -j REJECT --reject-with icmp-port-unreachable"${NC}
echo -e ${BLUE}"    #<----------------------------------------------------------------------------->"${NC}
echo -e ${CYAN}"#ip6tables-save > /etc/ip6tables.rules"${NC}
exit 0
# Generated by ip6tables-save v1.4.1.1 on Tue Sep 21 19:52:49 2010
#*filter
#:INPUT DROP [0:0]
#:FORWARD DROP [0:0]
#:OUTPUT DROP [0:0]
#:logndropip6 - [0:0]
#[0:0] -A INPUT -p tcp -j REJECT --reject-with tcp-reset
#[0:0] -A OUTPUT -j logndropip6
#[0:0] -A logndropip6 -p tcp -m limit --limit 5/min -j LOG --log-prefix "Denied ipv6 TCP: " --log-level 7
#[0:0] -A logndropip6 -p udp -m limit --limit 5/min -j LOG --log-prefix "Denied ipv6 UDP: " --log-level 7
#[0:0] -A logndropip6 -p icmp -m limit --limit 5/min -j LOG --log-prefix "Denied ipv6 ICMP: " --log-level 7
#[0:0] -A logndropip6 -p tcp -j REJECT --reject-with tcp-reset
#COMMIT
# Completed on Tue Sep 21 19:52:49 2010

A fully working example partially based on the script above can be found here:
Please note that I _ONLY_ use opendns’ nameservers to resolve hostnames now!!! If you do _NOT_ then make sure to change the following rules accordingly. 😉
Filename:

/etc/iptables.rules
# Generated by iptables-save v1.4.4 on Sat Nov 19 19:39:46 2011
*nat
## Remove the spaces in between the ":" and "P"!!!
## Or maybe I should simply turn off those wordpress smileys?
: PREROUTING ACCEPT [0:0]
: POSTROUTING ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
COMMIT
# Completed on Sat Nov 19 19:39:46 2011
# Generated by iptables-save v1.4.4 on Sat Nov 19 19:39:46 2011
*mangle
## Remove the spaces in between the ":" and "P"!!!
: PREROUTING ACCEPT [0:0]
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
: POSTROUTING ACCEPT [0:0]
COMMIT
# Completed on Sat Nov 19 19:39:46 2011
# Generated by iptables-save v1.4.4 on Sat Nov 19 19:39:46 2011
*filter
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT DROP [0:0]
:blacklist - [0:0]
:icmp - [0:0]
:logndrop - [0:0]
:tobesortedout - [0:0]
-A INPUT -j blacklist 
-A OUTPUT -o lo -j ACCEPT 
-A OUTPUT -o eth0 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT 
-A OUTPUT -o eth0 -p tcp -m tcp --dport 80 -m owner --uid-owner 0 -j ACCEPT 
## ^^ apt-get {update,upgrade,install,remove,purge} # <-- deb http://
-A OUTPUT -o eth0 -p tcp -m tcp --dport 443 -m owner --uid-owner 0 -j ACCEPT 
## ^^ apt-get {update,upgrade,install,remove,purge} # <-- deb https://
-A OUTPUT -o eth0 -p udp -m udp --dport 53 -m owner --uid-owner root -m iprange --dst-range 208.67.220.220-208.67.222.222 -j ACCEPT 
## ^^ Use opendns resolver only! If applicable? Then insert yours instead.
## E.g.: https://code.google.com/speed/public-dns/
-A OUTPUT -o eth0 -p tcp -m tcp -m owner --uid-owner 1000 -j ACCEPT
## ^^ Admin with sudo rights.
-A OUTPUT -o eth0 -p udp -m udp --dport 53 -m owner --uid-owner 1000 -m iprange --dst-range 208.67.220.220-208.67.222.222 -j ACCEPT 
## ^^ Use opendns resolver only!
#-A OUTPUT -o eth0 -p tcp -m tcp -m owner --uid-owner 1001 -j ACCEPT 
## ^^ A simple daily user.
#-A OUTPUT -o eth0 -p udp -m udp --dport 53 -m owner --uid-owner 1001 -m iprange --dst-range 208.67.220.220-208.67.222.222 -j ACCEPT 
## ^^ Use opendns resolver only!
#-A OUTPUT -o eth0 -p tcp -m tcp -m owner --uid-owner boinc -j ACCEPT 
#-A OUTPUT -o eth0 -p udp -m udp --dport 53 -m owner --uid-owner boinc -m iprange --dst-range 208.67.220.220-208.67.222.222 -j ACCEPT 
## ^^ Use opendns resolver only!
-A OUTPUT -p tcp -j REJECT --reject-with tcp-reset 
-A OUTPUT -p udp -j REJECT --reject-with icmp-port-unreachable 
# -A blacklist -s X.X.X.X/32 -j REJECT --reject-with icmp-host-prohibited 
# -A blacklist -s X.X.X.0/24 -j REJECT --reject-with icmp-net-prohibited 
-A blacklist -j icmp 
-A icmp -p icmp -m icmp --icmp-type 0 -j ACCEPT 
-A icmp -p icmp -m icmp --icmp-type 3 -j ACCEPT 
-A icmp -p icmp -m icmp --icmp-type 11 -j ACCEPT 
-A icmp -p icmp -m icmp --icmp-type 8 -m limit --limit 1/sec -j ACCEPT 
-A icmp -j tobesortedout 
-A logndrop -p tcp -m limit --limit 5/min -j LOG --log-prefix "Denied TCP: " --log-level 7 
-A logndrop -p udp -m limit --limit 5/min -j LOG --log-prefix "Denied UDP: " --log-level 7 
-A logndrop -p icmp -m limit --limit 5/min -j LOG --log-prefix "Denied ICMP: " --log-level 7 
-A logndrop -p tcp -j REJECT --reject-with tcp-reset 
-A logndrop -p udp -j REJECT --reject-with icmp-port-unreachable 
-A tobesortedout -i lo -j ACCEPT 
-A tobesortedout -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT 
#-A tobesortedout -i eth0 -p tcp -m tcp --dport (UpToYou) --tcp-flags FIN,SYN,RST,ACK SYN -m connlimit --connlimit-above 16 --connlimit-mask 24 -j REJECT --reject-with tcp-reset 
#-A tobesortedout -i eth0 -p tcp -m state --state NEW -m limit --limit 20/sec --limit-burst 20 -m tcp --dport (UpToYou) -j ACCEPT 
-A tobesortedout -j logndrop 
COMMIT
# Completed on Sat Nov 19 19:39:46 2011

How about ipv6? Of course, here you go!
Filename:

/etc/ip6tables.rules
# Generated by ip6tables-save v1.4.4 on Fri Oct  7 08:44:05 2011
*filter
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT DROP [0:0]
:logndropip6 - [0:0]
[0:0] -A INPUT -p tcp -j REJECT --reject-with tcp-reset 
[0:0] -A OUTPUT -j logndropip6 
[0:0] -A logndropip6 -p tcp -m limit --limit 5/min -j LOG --log-prefix "Denied ipv6 TCP: " --log-level 7 
[0:0] -A logndropip6 -p udp -m limit --limit 5/min -j LOG --log-prefix "Denied ipv6 UDP: " --log-level 7 
[0:0] -A logndropip6 -p icmp -m limit --limit 5/min -j LOG --log-prefix "Denied ipv6 ICMP: " --log-level 7 
[0:0] -A logndropip6 -p tcp -j REJECT --reject-with tcp-reset 
COMMIT
# Completed on Fri Oct  7 08:44:05 2011

Please note, there is no such thing as:

sudo service iptables

(iptables or better yet the netfilter module is an “add on” for the linux kernel and has nothing to do whatsoever with the startup of system services.)

“What the eyes see and the ears hear the mind believes…”

^^No doubt about that. Therefore a small video (sorry, no audio folks) of this script in action will be more explanatory!?

Or see the gallery below instead?


Is there any way to be 100% sure my computer will never be cracked into?

If you follow the instructions at the top of this page, you probably will not have your computer cracked. When you’re connected to the Internet, though, you are always vulnerable to security breaches of some kind. The only thing you can do is try to reduce your vulnerability. And I’ve read from a few security experts on the Ubuntu Forums that if someone is really determined to crack into your computer and capable, she pretty much will eventually it’s just a matter of time. The more obstacles you can put in the way of that happening, the more time it will take. Of course, disallowing remote logins is a big help.

What’s the most important part of OS security?
The user. It’s always the user. I’d rather have a smart user running as administrator on a Windows computer with no firewall, no anti-virus, and no antispyware than a dumb user running as limited user on a Ubuntu computer with a firewall, anti-virus, and a rootkit detector. Dumb users click on anything, somehow manage to install untrustworthy software even without administrative privileges, and use easy-to-guess passwords.

3 thoughts on “Iptables how to.

  1. If one were to opt-out of the ‘blacklisted’ ip’s I have provided? Then one could create a few aliases in his/her $HOME/.bash_aliases like these:
    alias BlIp=’sudo iptables -I blacklist 1 -j REJECT –reject-with icmp-host-prohibited -s’
    # E.g.: BlIp 1.2.3.4
    alias BlNet=’sudo iptables -I blacklist 1 -j REJECT –reject-with icmp-net-prohibited -s’
    # E.g.: BlNet 1.2.3.0/24
    To of course block repeat offenders (just take note of your server logs, if any?)

    Like

    • Similarly if one wants to enable a torrent client or any other type of service:
      sudo iptables -I tobesortedout 3 <rule spec>
      # E.g.: sudo iptables -I tobesortedout 3 -i eth0 -p tcp -m state –state NEW -m limit –limit 40/sec –limit-burst 80 -m tcp –dport 6881 -j ACCEPT
      Or:
      # If one doesn’t use a user defined chain like I have.
      sudo iptables -I INPUT 3 <rule spec>
      # E.g.: sudo iptables -I INPUT 3 -i eth0 -p tcp -m state –state NEW -m limit –limit 40/sec –limit-burst 80 -m tcp –dport 6881 -j ACCEPT

      This will ensure that your loopback ‘lo’ and the ctstate RELATED,ESTABLISHED rules won’t be affected!

      Like

  2. Pingback: how-to-tor « Bohemian Wildebeest's Blog

Comments are closed.