Results 1 to 10 of 10
  1. #1
    Joined
    Jul 2001
    Location
    UK
    Age
    49
    Posts
    20,230

    Linux Firewall (iptables) Tutorial

    A few people have expressed an interest in learning more about iptables, the Linux firewall, so we're going to do a tutorial style thread - and this is it.

    Contents:

    1. Introduction
    2. Getting Started
    3. Alowing incoming connections (IP addresss)
    4. Opening common ports
    Last edited by Ned Slider; 09-09-2007 at 03:08 PM.

    ~ Want to try Linux - check out the PC Perspective Linux FAQ ~
    ~ Please take some time to read the Forum Rules ~
    ~ Feed the spamb0tz, don't mail me here: B7Trz4568254@nirvana.admins.ws ~


  2. #2
    Joined
    Jul 2001
    Location
    UK
    Age
    49
    Posts
    20,230

    Re: Linux Firewall (iptables) Tutorial Thread

    A few words before we begin

    I'm hoping this will be a tutorial style thread - therefore I'd like to strongly encourage people to work along with the examples and participate. Post as much as you like, and at the end we can strip out the relevant posts and turn in into a guide or something if we want. The idea is to learn as we go. I was thinking of doing weekly installments so everyone has a chance to try out and keep up with what we cover each week, as well as sort out any issues before we move on to the next installment. The first installment is merely an introduction that may hopefully encourage you to read up on a few of the general concepts involved before we begin to get our hands dirty next week.

    Introduction

    Linux has an extremely powerful firewall built in, commonly referred to as iptables, but more accurately is iptables/netfilter. Iptables is the userspace module, the bit that you, the user, interact with at the commandline to enter firewall rules into predefined tables. Netfilter is a kernel module, built into the kernel, that actually does the filtering. There are many gui front ends for iptables that allow users to add or define rules based on a point and click user interface, but these often lack the flexability of using the commandline interface and limit the users understanding of what's really happening. We're going to learn the commandline interface of iptables.

    Before we can really get to grips with iptables, we need to have at least a basic understanding of the way it works. Iptables uses the concept of ip addresses, protocols (tcp, udp icmp) and ports. We don't need to be experts in these to get started (as we can look up any of the information we need), but it helps to have a general understanding.

    Iptables places rules into predefined tables (INPUT, OUTPUT and FORWARD) that are checked against any network traffic (IP packets) relevant to those tables and a decision is made about what to do with each packet based upon the outcome of those rules, ie accepting or dropping the packet. These actions are referred to as targets, of which the two most common predefined targets are DROP to drop a packet or ACCEPT to accept a packet.

    Tables

    These are 3 predefined tables in use by iptables to which we can add rules for processing IP packets passing through those tables. These tables are:

    INPUT - All packets destined for the host computer.

    OUTPUT - All packets originating from the host computer.

    FORWARD - All packets neither destined for or originating from the host computer, but passing through (routed by) the host computer. This table is used if using your computer as a router.

    For the most part, we are going to be dealing with the INPUT table to filter packets entering our machine - that is, keeping the bad guys out.

    Rules are added in a list to each table. A packet is checked against each rule in turn, starting at the top, and if it maches that rule, then an action is taken such as accepting (ACCEPT) or dropping (DROP) the packet. Once a rule has been matched and an action taken, then the packet is processed according to that outcome of the rule and isn't processed by further rules in the table. If a packet passes down through all the rules in the table and reaches the bottom without being matched against any rule, then the default action for that table is taken. This is referred to as the default policy and may be to either ACCEPT or DROP the packet.

    The concept of default policies within tables raises two fundamental possibilities that we must first consider before we decide how we are going to organise our firewall.

    1. We can set a default policy to DROP all packets and then add rules to specifically allow (ACCEPT) packets that may be from trusted IP addresses, or for certain ports on which we have services running such as bittorrent, FTP server, Web Server, Samba file server etc.

    or alternatively,

    2. We can set a default policy to ACCEPT all packets and then add rules to specifically block (DROP) packets that may be from specific nusiance IP addresses or ranges, or for certain ports on which we have private services or no services running.

    Generally, option 1 above is used for the INPUT table where we want to control what is allowed to access our machine and option 2 would be used for the OUTPUT table where we pretty much trust the traffic that is leaving (originating from) our machine.

    The Next Installment

    In the next installment, we will learn how to find out if we have iptables running on our machine, how to start it, stop it, and examine what rules are currently in place. Then we will just jump straight in with a very simple set of rules for a basic stateful packet inspection (spi) firewall configuration and look at the syntax used to set it up.

    Homework for this week is to see if you can establish if you:

    1. have iptables installed
    2. have iptables running
    3. can start and stop iptables (turn it on and off)

    ..

    ~ Want to try Linux - check out the PC Perspective Linux FAQ ~
    ~ Please take some time to read the Forum Rules ~
    ~ Feed the spamb0tz, don't mail me here: B7Trz4568254@nirvana.admins.ws ~


  3. #3
    Joined
    Jul 2001
    Location
    UK
    Age
    49
    Posts
    20,230

    Re: Linux Firewall (iptables) Tutorial Thread

    Getting Started

    Working with iptables from the commandline requires root priviledges, so you will need to become root for most things we will be doing.

    Note: We will be turning off iptables and resetting your firewall rules, so if you are reliant on your linux firewall as your primary line of defense you should be aware of this.

    Unfortunately, different Linux distros use different comands for starting, stopping and saving firewall rules, so you may need to check your documentation to find out how to do this on your Linux distro. I'm using Red Hat (or Fedora) for the purposes of this tutorial and I'll try to indicate where there may be differences.

    First up, we need to establish we have iptables installed. It should be installed on most, if not all modern linux distros. Simply typing iptables --help at the shell should establish iptables is installed on your system:

    Code:
    # iptables --help
    iptables v1.2.9
    
    Usage: iptables -[AD] chain rule-specification [options]
           iptables -[RI] chain rulenum rule-specification [options]
           iptables -D chain rulenum [options]
           iptables -[LFZ] [chain] [options]
           iptables -[NX] chain
           iptables -E old-chain-name new-chain-name
           iptables -P chain target [options]
           iptables -h (print this help information)
    
    <snip>
    And to see if iptables is actually running, we can use the -L switch to inspect the currently loaded rules:

    Code:
    # iptables -L
    Chain INPUT (policy DROP)
    target     prot opt source               destination
    ACCEPT     all  --  anywhere             anywhere
    ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED
    ACCEPT     all  --  barney               anywhere            MAC 00:50:8D:6D:EF:23
    DROP       all  --  wilma                anywhere
    ACCEPT     all  --  bart                 anywhere            MAC 00:50:8D:FD:D6:32
    ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:ftp
    ACCEPT     tcp  --  ict                  anywhere            state NEW tcp dpt:ssh
    
    Chain FORWARD (policy DROP)
    target     prot opt source               destination
    
    Chain OUTPUT (policy ACCEPT)
    target     prot opt source               destination
    If iptables is running you should see some rules similar to those above. If iptables doesn't appear to be running, you can check to see if any iptables modules are loaded:

    Code:
    # lsmod |grep ip
    ipt_mac                 2113  2
    ipt_state               2113  2
    ip_conntrack           40949  1 ipt_state
    iptable_filter          3777  1
    ip_tables              16577  3 ipt_mac,ipt_state,iptable_filter
    OK, assuming you have worked out how to get iptables started, if it's not already, let's begin with a very simple set of rules to set up an spi firewall that will allow all outgoing connections but block all unwanted incoming connections. At the command prompt we could type the following commands:

    Code:
    iptables -F
    iptables -P INPUT DROP
    iptables -P FORWARD DROP
    iptables -P OUTPUT ACCEPT
    iptables -A INPUT -i lo -j ACCEPT
    iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
    iptables -L -v
    and the final command gives us the following output:

    Code:
    Chain INPUT (policy DROP 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
    
    Chain FORWARD (policy DROP 0 packets, 0 bytes)
     pkts bytes target     prot opt in     out     source               destination
    
    Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
     pkts bytes target     prot opt in     out     source               destination
    There - that was easy wasn't it! We now have a fully featured spi firewall running that will allow all outgoing connections but block all unauthorized incoming connections as well as any forwarded packets. So, lets look at each of the 7 commands in turn and understand exactly what we've just done:

    1. (iptables -F) First of all we've used the -F switch to flush all existing rules so we start with a clean state from which to add new rules.

    2. (iptables -P INPUT DROP) The -P switch sets the default policy on the specified chain. So here we've set the default policy on the INPUT table to DROP. This means that if an incoming packet does not match one of the following rules it will be dropped.

    3. (iptables -P FORWARD DROP) Similarly, here we've set the default policy on the FORWARD chain to DROP as we're not using our computer as a router so there should not be any packets passing through our computer.

    4. (iptables -P OUTPUT ACCEPT) and finally, we've set the default policy on the OUTPUT chain to ACCEPT as we want to allow all outgoing traffic (as we trust our users).

    5. (iptables -A INPUT -i lo -j ACCEPT) Now it's time to start adding some rules. We use the -A switch to append (or add) a rule to a specific chain, the INPUT chain in this instance. Then we use the -i switch (for interface) to specify packets matching or destined for the lo (or localhost, 127.0.0.1) interface and finally -j (jump) to the target action for packets matching the rule - in this case ACCEPT. So this rule will allow all incoming packets destined for the localhost interface to be accepted. This is generally required as many software apps expect to be able to communicate with the localhost adaptor.

    6. (iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT). This is the rule that does most of the work, and again we are adding (-A) it to the INPUT chain. Here we're using the -m switch to load a module (state). The state module is able to examine the state of a packet and determine if it is NEW, ESTABLISED or RELATED. NEW refers to incoming packets that are new incoming connections that weren't initiated by the host system. ESTABLISED and RELATED refers to incoming packets that are part of an already established connection or related to and already established connection.

    7. (iptables -L -v) Finally, we can list (-L) the rules we've just added to check they've been loaded correctly.

    Finally, the last thing we need to do is save our rules so that next time we reboot our computer our rules are automatically reloaded. Unfortunately, the command to do this is different on different distros. On RH/Fedora systems, do:

    Code:
    /sbin/service iptables save
    I'm not sure on other distro's so perhaps users can confirm, but for debian-based systems, try:

    Code:
    /etc/init.d/iptables save_active
    and for Suse, try editing /etc/sysconfig/SuSEfirewall2 and restarting the firewall by running:

    Code:
    /sbin/SuSEfirewall2 restart
    Obviously typing all these commands at the shell can become tedious, so by far the easiest way to work with iptables is to create a simple script to do it all for you. The above (for RH/Fedora) may be entered into your favourite text editor, saved (as myfirewall for example) and made executable:

    Code:
    #!/bin/bash
    # iptables configuration file
    # Ned Slider, 2006
    
    # Flush all current rules from iptables
     iptables -F
    
    # Set default policies for INPUT, FORWARD and OUTPUT chains
     iptables -P INPUT DROP
     iptables -P FORWARD DROP
     iptables -P OUTPUT ACCEPT
    
    # Set access for localhost
     iptables -A INPUT -i lo -j ACCEPT
    
    # Accept packets belonging to established and related connections
     iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
    
    # Save settings with /sbin/service iptables save
    # List iptables chains with 'iptables -L -v'
    /sbin/service iptables save
    iptables -L -v
    Note we can also comment our script to remind us what were doing. Now we can simply edit our script and run it from the shell with the following command:

    Code:
    ./myfirewall
    If you can't work out how to save your firewall rules in your distro, you could simply run the above script each time at startup.

    OK, that's it for this week. Probably the hardest part for most users will be establishing you have iptables installed and running, and working out how to save your new firewall configuration at the end, as these are not the same on all distros. Everything else when working with iptables is identical so should work without issue. Post if you have any problems, and when everyone has successfully got this far, we'll continue with the next installment and look at how to safely open up our firewall for some common incoming connections.

    Ned

    ~ Want to try Linux - check out the PC Perspective Linux FAQ ~
    ~ Please take some time to read the Forum Rules ~
    ~ Feed the spamb0tz, don't mail me here: B7Trz4568254@nirvana.admins.ws ~


  4. #4
    Joined
    Jul 2001
    Location
    UK
    Age
    49
    Posts
    20,230

    Re: Linux Firewall (iptables) Tutorial Thread

    In the last installment we wrote a very simple script to set up a basic spi firewall to block all new incoming connections but allow outgoing packets:

    Code:
    #!/bin/bash
    # iptables configuration file
    # Ned Slider, 2006
    
    # Flush all current rules from iptables
     iptables -F
    
    # Set default policies for INPUT, FORWARD and OUTPUT chains
     iptables -P INPUT DROP
     iptables -P FORWARD DROP
     iptables -P OUTPUT ACCEPT
    
    # Set access for localhost
     iptables -A INPUT -i lo -j ACCEPT
    
    # Accept packets belonging to established and related connections
     iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
    
    # Save settings with /sbin/service iptables save
    # List iptables chains with 'iptables -L -v'
    /sbin/service iptables save
    iptables -L -v
    In this installment we are going to learn how to safely open up some holes in our firewall to allow some wanted incoming connections. Do to this, there are 4 main parameters we can filter against:

    • Interface - eth0, eth1, ppp0 etc
    • IP Addresses - single IP address or address range
    • Protocols - tcp, udp, icmp, all
    • Ports - single port or a range of ports


    Interface

    In our previous example, we saw how to accept all packets incoming on a particular interface, in this case the localhost interface:

    Code:
     iptables -A INPUT -i lo -j ACCEPT
    Suppose we have 2 seperate interfaces, eth0 which is our internal LAN connection and ppp0 dialup modem (or maybe eth1 for a nic) which is our external internet connection. We may want to allow all incoming packets on our internal LAN but still filter incoming packets on our external internet connection. We could do this as follows:

    Code:
     iptables -A INPUT -i lo -j ACCEPT
     iptables -A INPUT -i eth0 -j ACCEPT
    But be very careful - if we were to allow all packets for our external internet interface (for example, ppp0 dialup modem):

    Code:
     iptables -A INPUT -i lo -j ACCEPT
     iptables -A INPUT -i ppp0 -j ACCEPT
    we would have effectively just disabled our firewall.

    IP Addresses

    Opening up a whole interface to incoming packets may not be restrictive enough and you may want more control as to what to allow and what to reject. Lets suppose we have a small network of computers that use the 192.168.0.x private subnet. We can open up our firewall to incoming packets from a single trusted IP address (for example, 192.168.0.4):

    Code:
    # Accept packets from trusted IP addresses
     iptables -A INPUT -s 192.168.0.4 -j ACCEPT # change the IP address as appropriate
    Breaking this command down, we first append (-A) a rule to the INPUT chain for the source (-s) IP address 192.168.0.4 to ACCEPT all packets (also note how we can use the # symbol to add comments inline to document our script with anything after the # being ignored and treated as a comment).

    Obviously if we want to allow incoming packets from a range of IP addresses, we could simply add a rule for each trusted IP address and that would work fine. But if we have a lot of them, it may be easier to add a range of IP addresses in one go.

    To do this, we can use a netmask or standard slash notation to specify a range of IP address. For example, if we wanted to open our firewall to all incoming packets from the complete 192.168.0.x (where x=1 to 254) range, we could use either of the following methods:

    Code:
    # Accept packets from trusted IP addresses
     iptables -A INPUT -s 192.168.0.0/24 -j ACCEPT  # using standard slash notation
     iptables -A INPUT -s 192.168.0.0/255.255.255.0 -j ACCEPT # using a subnet mask
    Finally, as well as filtering against a single IP address, we can also match against the MAC address for the given device. To do this, we need to load a module (the mac module) that allows filtering against mac addresses. Earlier we saw another example of using modules to extend the functionality of iptables when we used the state module to match for ESTABLISHED and RELATED packets. Here we use the mac module to check the mac address of the source of the packet in addition to it's IP address:

    Code:
    # Accept packets from trusted IP addresses
     iptables -A INPUT -s 192.168.0.4 -m mac --mac-source 00:50:8D:FD:E6:32 -j ACCEPT
    First we use -m mac to load the mac module and then we use --mac-source to specify the mac address of the source IP address (192.168.0.4). You will need to find out the mac address of each ethernet device you wish to filter against. Running ifconfig (or iwconfig for wireless devices) as root will provide you with the mac address.

    This may be useful for preventing spoofing of the source IP address as it will allow any packets that genuinely originate from 192.168.0.4 (having the mac address 00:50:8D:FD:E6:32) but will block any packets that are spoofed to have come from that address. Note I'm unsure whether mac address filtering works across the internet but it certainly works fine on a LAN.

    To try out any of the above examples, simple add the appropriate line to your firewall script we made in the last installment, save and rerun it. Then test to make sure the rule is working as you would expect.

    To summarize, in this installment we have seen how we can add rules to our firewall to filter against packets matching a particular interface or a source IP address. This allows full access through our firewall to certain trusted sources (machines). In the next installment we'll look at how we can filter against protocols and ports to further refine what incoming packets we allow and what we block.

    .

    ~ Want to try Linux - check out the PC Perspective Linux FAQ ~
    ~ Please take some time to read the Forum Rules ~
    ~ Feed the spamb0tz, don't mail me here: B7Trz4568254@nirvana.admins.ws ~


  5. #5
    Joined
    Jul 2001
    Location
    UK
    Age
    49
    Posts
    20,230

    Re: Linux Firewall (iptables) Tutorial Thread

    Ports and Protocols

    In this installment we're going to look at filtering against ports and protocols to allow certain services using the ACCEPT target.

    Before you can start, you really need to know what protocol and port number the given service uses. For a simple example, lets look at bittorrent. Bittorrent uses tcp on port 6881, so we would need to allow all tcp packets on destination port (the port on which they arrive at our machine) 6881:

    Code:
    iptables -A INPUT -p tcp --dport 6881 -j ACCEPT
    This simple rule accepts all tcp packets entering our machine on port 6881.

    Note: In order to use matches such as destination or source ports (--dport or --sport), you must first specify the protocol (tcp, udp, icmp, all).

    We can also extend the above to include a port range, for example, allowing all tcp packets on the range 6881 to 6890:

    Code:
    iptables -A INPUT -p tcp --dport 6881:6890 -j ACCEPT
    Now we've seen the basics, we can start combining these with some of the functionality we looked at earlier.

    We don't need our bittorrent rule to examine every packet, only the first packet, as our stateful packet inspection rule will allow subsequent established and related packets to pass. We only need to have our rule allow NEW connections on the given port to be accepted, so using the spi module, we would now only need to filter against NEW tcp connections on port 6881:

    Code:
    iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
    iptables -A INPUT -p tcp --dport 6881 -m state --state NEW -j ACCEPT
    Another popular *nix service is the secure shell (SSH) service. SSH uses port 22 and again uses the tcp protocol. So if we want to allow remote logins, we would need to open up tcp on port 22:

    Code:
    iptables -A INPUT -p tcp --dport 22 -j ACCEPT
    This will open up port 22 (SSH) to all incoming connections which poses a security threat as hackers would be free to try brute force cracking on accounts with weak passwords. However, if we know the IP addresses of trusted remote machines that will be used to log on using SSH, we can limit access to only these source IP addresses. For example, if I just wanted to open up SSH access on my private lan (192.168.0.x), I can limit access to just this source IP address range:

    Code:
    iptables -A INPUT -p tcp -s 192.168.0.0/24 --dport 22 -j ACCEPT
    Using source IP filtering allows us to securely open up SSH access on port 22 to only trusted IP addresses. For example, we could use this method to allow remote logins between work and home machines. To all other IP addresses, the port (and service) would appear closed as if the service were disabled. In order to hack the system, a hacker would need to know the trusted IP addresses and spoof packets to be from those addresses.

    Again, we don't need to filter all packets, only new connections, so our final rule may look like:

    Code:
    iptables -A INPUT -p tcp -s 192.168.0.0/24 --dport 22 -m state --state NEW -j ACCEPT
    You are now armed with the basics of iptables and should be able to construct rules comprising the constituent parts to filter packets for most common services. However, this is only really scraping the surface of what iptables is truely capable of. Iptables can also do packet limiting (to prevent DDoS attacks), packet logging, network address tanslation (NAT) to allow network connection sharing. If you master the basics, you'll then have a solid base on which to build should you wish to tackle more ambitious projects.

    .

    ~ Want to try Linux - check out the PC Perspective Linux FAQ ~
    ~ Please take some time to read the Forum Rules ~
    ~ Feed the spamb0tz, don't mail me here: B7Trz4568254@nirvana.admins.ws ~


  6. #6
    Joined
    Jul 2001
    Location
    UK
    Age
    49
    Posts
    20,230

    Re: Linux Firewall (iptables) Tutorial

    An updated version of this guide is now also available on the CentOS Wiki:

    http://wiki.centos.org/HowTos/Network/IPTables

    ~ Want to try Linux - check out the PC Perspective Linux FAQ ~
    ~ Please take some time to read the Forum Rules ~
    ~ Feed the spamb0tz, don't mail me here: B7Trz4568254@nirvana.admins.ws ~


  7. #7
    Joined
    Nov 2006
    Posts
    38

    Re: Linux Firewall (iptables) Tutorial

    Thanks Ned, great to have it in the wiki.

  8. #8
    Joined
    Jun 2003
    Location
    Arizona's White Mountains
    Age
    71
    Posts
    3,610

    Thumbs up Re: Linux Firewall (iptables) Tutorial

    I think this should be made into a "sticky" or preserved some other way.
    FRH
    If more sane people were armed the crazy ones would get off fewer shots.

    Win 7 Premium SP1 / MX 15 KDE / MEPIS 11

  9. #9
    Joined
    Jul 2001
    Location
    UK
    Age
    49
    Posts
    20,230

    Re: Linux Firewall (iptables) Tutorial

    Quote Originally Posted by Frank1946 View Post
    I think this should be made into a "sticky" or preserved some other way.
    I linked it in one of the Sticky threads here:

    http://forums.pcper.com/showthread.p...24&postcount=3

    ~ Want to try Linux - check out the PC Perspective Linux FAQ ~
    ~ Please take some time to read the Forum Rules ~
    ~ Feed the spamb0tz, don't mail me here: B7Trz4568254@nirvana.admins.ws ~


  10. #10
    Joined
    Aug 2003
    Location
    Sequim, WA
    Posts
    1,430

    Re: Linux Firewall (iptables) Tutorial

    Heh, at first glance I thought the title of this thread said " Linux Farewell", I was like " Noooooooooo, Ned'o"....lol. then I realized it was Neds firewall thread, whew!!
    Biostar TA 770/ X2 7850 BE
    AC Freezer 64 Pro
    OCZ Gold 4x1024
    EVGA 9800GTX
    Coolermaster CM-690
    Coolermaster RPP RS-650
    Win7Pro

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •