User Tools

Site Tools


ubuntuiptableshowto

Ubuntu IPtables How-To

Basic iptables howto

<span id“line-4”> </span> Iptables is a firewall, installed by default on all official Ubuntu distributions (Ubuntu, Kubuntu, Xubuntu). When you install Ubuntu, iptables is there, but it allows all traffic by default. Ubuntu 8.04 Comes with <a href“/community/UFW”>ufw</a> - a program for managing the iptables firewall easily. <span id“line-5”> </span><span id“line-6”> </span>

There is a wealth of information available about iptables, but much of it is fairly complex, and if you want to do a few basic things, this How To is for you. <span id“line-7”> </span><span id“line-8”> </span>

Basic Commands

<span id“line-9”> </span> Typing <span id“line-10”> </span><span id“line-11”> </span><span id“line-12”> </span>

# iptables -L

<span id“line-13”> </span> lists your current rules in iptables. If you have just set up your server, you will have no rules, and you should see <span id“line-14”> </span><span id“line-15”> </span><span id“line-16”> </span><span id“line-17”> </span><span id“line-18”> </span><span id“line-19”> </span><span id“line-20”> </span><span id“line-21”> </span><span id“line-22”> </span><span id“line-23”> </span> <code>Chain INPUT (policy ACCEPT) target prot opt source destination Chain FORWARD (policy ACCEPT) target prot opt source destination Chain OUTPUT (policy ACCEPT) target prot opt source destination</code> <span id“line-24”> </span><span id“line-25”> </span> ===== Basic Iptables Options ===== <span id“line-26”> </span>

Here are explanations for some of the iptables options you will see in this tutorial. Don't worry about understanding everything here now, but remember to come back and look at this list as you encounter new options later on. <span id“line-27”> </span> * <p> -A - Append this rule to a rule chain. Valid chains for what we're doing are INPUT, FORWARD and OUTPUT, but we mostly deal with INPUT in this tutorial, which affects only incoming traffic. <span id“line-28” class“anchor”> </span></p> * <p> -L - List the current filter rules. <span id“line-29” class“anchor”> </span></p> * <p> -m conntrack - Allow filter rules to match based on connection state. Permits the use of the –ctstate option. <span id“line-30” class“anchor”> </span></p> * <p> –ctstate - Define the list of states for the rule to match on. Valid states are: <span id“line-31” class“anchor”> </span></p> * NEW - The connection has not yet been seen. <span id“line-32” class“anchor”> </span> * RELATED - The connection is new, but is related to another connection already permitted. <span id“line-33” class“anchor”> </span> * ESTABLISHED - The connection is already established. <span id“line-34” class“anchor”> </span> * INVALID - The traffic couldn't be identified for some reason. <span id“line-35” class“anchor”> </span> * <p> -m limit - Require the rule to match only a limited number of times. Allows the use of the –limit option. Useful for limiting logging rules. <span id“line-36” class“anchor”> </span></p> * <p> –limit - The maximum matching rate, given as a number followed by “/second”, “/minute”, “/hour”, or “/day” depending on how often you want the rule to match. If this option is not used and -m limit is used, the default is “3/hour”. <span id“line-37” class“anchor”> </span></p> * <p> -p - The connection protocol used. <span id“line-38” class“anchor”> </span></p> * <p> –dport - The destination port(s) required for this rule. A single port may be given, or a range may be given as start:end, which will match all ports from start to end, inclusive. <span id“line-39” class“anchor”> </span></p> * <p> -j - Jump to the specified target. By default, iptables allows four targets: <span id“line-40” class“anchor”> </span></p> * <p> ACCEPT - Accept the packet and stop processing rules in this chain. <span id“line-41” class“anchor”> </span></p> * <p> REJECT - Reject the packet and notify the sender that we did so, and stop processing rules in this chain. <span id“line-42” class“anchor”> </span></p> * <p> DROP - Silently ignore the packet, and stop processing rules in this chain. <span id“line-43” class“anchor”> </span></p> * <p> LOG - Log the packet, and continue processing more rules in this chain. Allows the use of the –log-prefix and –log-level options. <span id“line-44” class“anchor”> </span></p> * <p> –log-prefix - When logging, put this text before the log message. Use double quotes around the text to use. <span id“line-45” class“anchor”> </span></p> * <p> –log-level - Log using the specified syslog level. 7 is a good choice unless you specifically need something else. <span id“line-46” class“anchor”> </span></p> * <p> -i - Only match if the packet is coming in on the specified interface. <span id“line-47” class“anchor”> </span></p> * <p> -I - Inserts a rule. Takes two options, the chain to insert the rule into, and the rule number it should be. <span id“line-48” class“anchor”> </span></p> * <p> -I INPUT 5 would insert the rule into the INPUT chain and make it the 5th rule in the list. <span id“line-49” class“anchor”> </span></p> * <p> -v - Display more information in the output. Useful for if you have rules that look similar without using -v.</p> * <p> -s –source - address[/mask] source specification</p> * <p> -d –destination - address[/mask] destination specification</p> * <p> -o –out-interface - output name[+] network interface name ([+] for wildcard)</p> ===== Allowing Established Sessions ===== We can allow established sessions to receive traffic: <code># iptables -A INPUT -m conntrack –ctstate ESTABLISHED,RELATED -j ACCEPT</code> * The above rule has no spaces either side of the comma in ESTABLISHED,RELATED If the line above doesn't work, you may be on a VPS that uses OpenVZ or doesn't have some kernel extensions installed. In that case, try this line instead: <code># iptables -A INPUT -m state –state ESTABLISHED,RELATED -j ACCEPT</code> ===== Allowing Incoming Traffic on Specific Ports ===== You could start by blocking traffic, but you might be working over SSH, where you would need to allow SSH before blocking everything else. To allow incoming traffic on the default SSH port (22), you could tell iptables to allow all TCP traffic on that port to come in. <code># iptables -A INPUT -p tcp –dport ssh -j ACCEPT</code> Referring back to the list above, you can see that this tells iptables: * append this rule to the input chain (-A INPUT) so we look at incoming traffic * check to see if it is TCP (-p tcp). * if so, check to see if the input goes to the SSH port (–dport ssh). * if so, accept the input (-j ACCEPT). Lets check the rules: (only the first few lines shown, you will see more) <code># iptables -L Chain INPUT (policy ACCEPT) target prot opt source destination ACCEPT all – anywhere anywhere state RELATED,ESTABLISHED ACCEPT tcp – anywhere anywhere tcp dpt:ssh</code> Now, let's allow all incoming web traffic <code># iptables -A INPUT -p tcp –dport 80 -j ACCEPT</code> Checking our rules, we have <code># iptables -L Chain INPUT (policy ACCEPT) target prot opt source destination ACCEPT all – anywhere anywhere state RELATED,ESTABLISHED ACCEPT tcp – anywhere anywhere tcp dpt:ssh ACCEPT tcp – anywhere anywhere tcp dpt:www</code> We have specifically allowed tcp traffic to the ssh and web ports, but as we have not blocked anything, all traffic can still come in. ===== Blocking Traffic ===== Once a decision is made to accept a packet, no more rules affect it. As our rules allowing ssh and web traffic come first, as long as our rule to block all traffic comes after them, we can still accept the traffic we want. All we need to do is put the rule to block all traffic at the end. <code># iptables -A INPUT -j DROP # iptables -L Chain INPUT (policy ACCEPT) target prot opt source destination ACCEPT all – anywhere anywhere state RELATED,ESTABLISHED ACCEPT tcp – anywhere anywhere tcp dpt:ssh ACCEPT tcp – anywhere anywhere tcp dpt:www DROP all – anywhere anywhere</code> Because we didn't specify an interface or a protocol, any traffic for any port on any interface is blocked, except for web and ssh. ===== Editing iptables ===== The only problem with our setup so far is that even the loopback port is blocked. We could have written the drop rule for just eth0 by specifying -i eth0, but we could also add a rule for the loopback. If we append this rule, it will come too late - after all the traffic has been dropped. We need to insert this rule before that. Since this is a lot of traffic, we'll insert it as the first rule so it's processed first. <code># iptables -I INPUT 1 -i lo -j ACCEPT # iptables -L Chain INPUT (policy ACCEPT) target prot opt source destination ACCEPT all – anywhere anywhere ACCEPT all – anywhere anywhere state RELATED,ESTABLISHED ACCEPT tcp – anywhere anywhere tcp dpt:ssh ACCEPT tcp – anywhere anywhere tcp dpt:www DROP all – anywhere anywhere</code> The first and last lines look nearly the same, so we will list iptables in greater detail. <code># iptables -L -v</code> <code>Chain INPUT (policy ALLOW 0 packets, 0 bytes) pkts bytes target prot opt in out source destination 0 0 ACCEPT all – lo any anywhere anywhere 0 0 ACCEPT all – any any anywhere anywhere state RELATED,ESTABLISHED 0 0 ACCEPT tcp – any any anywhere anywhere tcp dpt:ssh 0 0 ACCEPT tcp – any any anywhere anywhere tcp dpt:www 0 0 DROP all – any any anywhere anywhere</code> You can now see a lot more information. This rule is actually very important, since many programs use the loopback interface to communicate with each other. If you don't allow them to talk, you could break those programs! ===== Logging ===== In the above examples none of the traffic will be logged. If you would like to log dropped packets to syslog, this would be the quickest way: <code># iptables -I INPUT 5 -m limit –limit 5/min -j LOG –log-prefix “iptables denied: ” –log-level 7</code> See Tips section for more ideas on logging. ===== Saving iptables ===== If you were to reboot your machine right now, your iptables configuration would disappear. Rather than type this each time you reboot, however, you can save the configuration, and have it start up automatically. To save the configuration, you can use iptables-save and iptables-restore. ===== Configuration on startup ===== WARNING: Iptables and <a class“interwiki” hrefhttps://wiki.ubuntu.com/NetworkManager” title“Ubuntu”>NetworkManager</a> seem to have a conflict. However <a href“/community/NetworkManager”>NetworkManager</a> is still in Beta. If you are concerned enough about security to install a firewall you might not want to trust <a href“/community/NetworkManager”>NetworkManager</a> to manage it yet. Also note <a href“/community/NetworkManager”>NetworkManager</a> and iptables have opposite aims. Iptables aims to keep any questionable network traffice out. <a href“/community/NetworkManager”>NetworkManager</a> aims to keep you connected at all times. Therefore if you want security all the time, run iptables at boot time. If you want security some of the time then <a href“/community/NetworkManager”>NetworkManager</a> might be the right choice. WARNING: If you use <a class“interwiki” hrefhttps://wiki.ubuntu.com/NetworkManager” title“Ubuntu”>NetworkManager</a> (installed by default on Feisty and later) these steps will leave you unable to use <a class“interwiki” hrefhttps://wiki.ubuntu.com/NetworkManager” title“Ubuntu”>NetworkManager</a> for the interfaces you modify. Please follow the steps in the next section instead. NOTE: It appears on Hardy, <a class“interwiki” hrefhttps://wiki.ubuntu.com/NetworkManager” title“Ubuntu”>NetworkManager</a> has an issue with properly on saving and restoring the iptable rules when using the method in the next section. Using this first method appears to work. If you find otherwise, please update this note.

Save your firewall rules to a file

# sudo bash -c "iptables-save &gt; /etc/iptables.rules"

Then modify the _/etc/network/interfacesconfiguration file to apply the rules automatically. You will need to know the interface that you are using in order to apply the rules - if you do not know, you are probably using the interface eth0, although you should check with the following command first to see if there are any wireless cards: <code>$ iwconfig</code> If you get output similiar to the following, then you do not have any wireless cards at all and your best bet is probably eth0. <code>$ iwconfig lo no wireless extensions. eth0 no wireless extensions. $</code> When you have found out the interface you are using, please open your /etc/network/interfaces file depending on what editor you want and/or what distribution you have: Command line: <code># nano /etc/network/interfaces</code> For Ubuntu and Xubuntu: type ALT+F2, then in the window that pops up, type: <code>gksudo gedit /etc/network/interfaces</code> and press Enter. For Kubuntu: type ALT+F2, then in the window that pops up, type: <code>kdesu kate /etc/network/interfaces</code> and press enter. When in the file, search for the interface you found, and at the end of the network related lines for that interface, add the line: <code>pre-up iptables-restore &lt; /etc/iptables.rules</code> You can also prepare a set of down rules, save them into second file /etc/iptables.downrules and apply it automatically using the above steps: <code>post-down iptables-restore &lt; /etc/iptables.downrules</code> A fully working example using both from above: <code>auto eth0 iface eth0 inet dhcp pre-up iptables-restore &lt; /etc/iptables.rules post-down iptables-restore &lt; /etc/iptables.downrules</code> You may also want to keep information from byte and packet counters. <code>iptables-save -c &gt; /etc/iptables.save </code> The above command will in other words save the whole rule-set to a file called /etc/iptables.save with byte and packet counters still intact. Alternatively you could add the iptables-restore and iptables-save to the if-pre-up.d and if-post-down.d directories in the /etc/network directory instead of modifying /etc/network/interface directly. The script /etc/network/if-pre-up.d/iptaload will contain: <code>#!/bin/sh iptables-restore &lt; /etc/iptables.rules exit 0</code> and/etc/network/if-post-down.d/iptasave will contain: <code>#!/bin/sh if [ -f /etc/iptables.downrules ]; then iptables-restore &lt; /etc/iptables.downrules fi iptables-save -c &gt; /etc/iptables.save exit 0</code> Then be sure to give both scripts execute permissions: <code># chmod +x /etc/network/if-post-down.d/iptasave # chmod +x /etc/network/if-pre-up.d/iptaload</code> ===== Configuration on Startup for NetworkManager ===== <a class“interwiki” hrefhttps://wiki.ubuntu.com/NetworkManager” title“Ubuntu”>NetworkManager</a> includes the ability to run scripts when it activates or deactivates an interface. To save iptables rules on shutdown, and to restore them on startup, we are going to create such a script. To begin, press Alt+F2 and enter this command: For Ubuntu: <code>$ gksudo gedit /etc/NetworkManager/dispatcher.d/01firewall</code> For Kubuntu: <code>kdesu kate /etc/NetworkManager/dispatcher.d/01firewall</code> Then, paste this script into your editor, save, and exit the editor. <code>if [ -x /usr/bin/logger ]; then LOGGER“/usr/bin/logger -s -p daemon.info -t FirewallHandler” else LOGGERecho fi case “$2” in up) if [ ! -r /etc/iptables.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 &lt; /etc/iptables.rules ;; down) if [ ! -x /sbin/iptables-save ]; then ${LOGGER} “No program exists to save iptables rules.” return fi ${LOGGER} “Saving iptables rules.” /sbin/iptables-save -c &gt; /etc/iptables.rules ;; *) ;; esac</code> Finally, we need to make sure <a class“interwiki” hrefhttps://wiki.ubuntu.com/NetworkManager” title“Ubuntu”>NetworkManager</a> can execute this script. In a terminal window, enter this command: <code># chmod +x /etc/NetworkManager/dispatcher.d/01firewall</code> ===== Tips ===== <h3 id“If you manually edit iptables on a regular basis”>If you manually edit iptables on a regular basis</h3> The above steps go over how to setup your firewall rules and presume they will be relatively static (and for most people they should be). But if you do a lot of development work, you may want to have your iptables saved everytime you reboot. You could add a line like this one in /etc/network/interfaces: <code> pre-up iptables-restore &lt; /etc/iptables.rules post-down iptables-save &gt; /etc/iptables.rules</code> The line “post-down iptables-save &gt; /etc/iptables.rules” will save the rules to be used on the next boot. <h3 id“Using iptables-save/restore to test rules”>Using iptables-save/restore to test rules</h3> If you edit your iptables beyond this tutorial, you may want to use the iptables-save and iptables-restore feature to edit and test your rules. To do this open the rules file in your favorite text editor (in this example gedit). <code>$ sudo iptables-save &gt; /etc/iptables.rules $ gksudo gedit /etc/iptables.rules</code> You will have a file that appears similiar to (following the example above): <code># Generated by iptables-save v1.3.1 on Sun Apr 23 06:19:53 2006 filter :INPUT ACCEPT [368:102354] :FORWARD ACCEPT [0:0] :OUTPUT ACCEPT [92952:20764374] -A INPUT -i lo -j ACCEPT -A INPUT -m conntrack –ctstate RELATED,ESTABLISHED -j ACCEPT -A INPUT -i eth0 -p tcp -m tcp –dport 22 -j ACCEPT -A INPUT -i eth0 -p tcp -m tcp –dport 80 -j ACCEPT -A INPUT -m limit –limit 5/min -j LOG –log-prefix “iptables denied: ” –log-level 7 -A INPUT -j DROP COMMIT # Completed on Sun Apr 23 06:19:53 2006</code> Notice that these are iptables commands minus the iptable command. Feel free to edit this to file and save when complete. Then to test simply: <code># iptables-restore &lt; /etc/iptables.rules</code> After testing, if you have not added the iptables-save command above to your /etc/network/interfaces remember not to lose your changes: <code># iptables-save &gt; /etc/iptables.rules</code> <h3 id“More detailed Logging”>More detailed Logging</h3> For further detail in your syslog you may want create an additional Chain. This will be a very brief example of my /etc/iptables.rules showing how I setup my iptables to log to syslog: <code># Generated by iptables-save v1.3.1 on Sun Apr 23 05:32:09 2006 **filter :INPUT ACCEPT [273:55355] :FORWARD ACCEPT [0:0] :LOGNDROP - [0:0] :OUTPUT ACCEPT [92376:20668252] -A INPUT -m conntrack –ctstate RELATED,ESTABLISHED -j ACCEPT -A INPUT -i eth0 -p tcp -m tcp –dport 22 -j ACCEPT -A INPUT -i eth0 -p tcp -m tcp –dport 80 -j ACCEPT -A INPUT -i lo -j ACCEPT -A INPUT -j LOGNDROP -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 -j DROP COMMIT # Completed on Sun Apr 23 05:32:09 2006</code> Note a new CHAIN called LOGNDROP at the top of the file. Also, the standard DROP at the bottom of the INPUT chain is replaced with LOGNDROP and add protocol descriptions so it makes sense looking at the log. Lastly we drop the traffic at the end of the LOGNDROP chain. The following gives some idea of what is happening: * <p> –limit sets the number of times to log the same rule to syslog</p> * <p> –log-prefix “Denied…” adds a prefix to make finding in the syslog easier</p> * <p> –log-level 7 sets the syslog level to informational (see man syslog for more detail, but you can probably leave this)</p> <h3 id“Disabling the firewall”>Disabling the firewall</h3> If you need to disable the firewall temporarily, you can flush all the rules using <code># iptables -F</code> or create a script using text editor such as nano <code># nano -w /root/fw.stop</code> <code>echo “Stopping firewall and allowing everyone…” iptables -F iptables -X iptables -t nat -F iptables -t nat -X iptables -t mangle -F iptables -t mangle -X iptables -P INPUT ACCEPT iptables -P FORWARD ACCEPT iptables -P OUTPUT ACCEPT</code> Make sure you can execute the script <code>$ chmod +x /root/fw.stop</code> You can run the script <code>$ /root/fw.stop</code> ===== Easy configuration via GUI ===== <a class“https” hrefhttps://help.ubuntu.com/community/Gufw”>GUFW</a> - Gufw is a graphical frontend to UFW (Uncomplicated Firewall). A new user can use Firestarter (a gui), available in repositories (Synaptic or apt-get) to configure her/his iptable rules, without needing the command line knowledge. Please see the tutorial though… Configuration is easy, but may not be enough for the advanced user. However, it should be enough for the most home users… The (read:my) suggested outbound configuration is “restrictive”, with whitelisting each connection type whenever you need it (port 80 for http, 443 for secure http -https-, 1863 for msn chat etc) from the “policy” tab within firestarter. You can also use it to see active connections from and to your computer… The firewall stays up once it is configured using the wizard. Dial-up users will have to specify it to start automatically on dial up in the wizard. Homepage for firestarter: <a class“http” hrefhttp://www.fs-security.com/”>http://www.fs-security.com/</a> (again, available in repositories, no compiling required) Tutorial: <a class“http” hrefhttp://www.fs-security.com/docs/tutorial.php”>http://www.fs-security.com/docs/tutorial.php</a> <img alt“IconsPage/IconNote.png” src“/community/IconsPage?actionAttachFile&doget&targetIconNote.png” title“IconsPage/IconNote.png” /> Please note that it conflicts with ufw. ===== Further Information ===== * <a class“http” hrefhttp://www.frozentux.net/iptables-tutorial/iptables-tutorial.html”>Iptables Tutorial</a> * <a class“http” hrefhttp://www.netfilter.org/documentation/HOWTO/packet-filtering-HOWTO.html”>Iptables How To</a> * <a class“http” hrefhttp://www.netfilter.org/documentation/”>Netfilter and Iptables Multilingual Documentation</a> * <a class“http” hrefhttp://easyfwgen.morizot.net/gen/”>Easy Firewall Generator for IPTables</a> * <a class“http” hrefhttp://wiki.kartbuilding.net/index.php/Iptables_Firewall”>Iptables Info on Kartbuilding.net</a> For some reason the Ubuntu wiki page on Firestarter does not come up on searches, so here is a link : * <a class“https” hrefhttps://help.ubuntu.com/community/Firestarter”>Ubuntu Wiki Firestarter</a> Firestarter is a gui tool to help configure IP Tables. Please note that it conflicts with ufw. ===== Credits ===== Mirrored from: https://help.ubuntu.com/community/IptablesHowTo Thanks to Rusty Russell and his How-To, as much of this is based off that. – Main.FredPettis - 16 Mar 2010

ubuntuiptableshowto.txt · Last modified: 2013/01/28 04:29 by 127.0.0.1