Linux User Group of Gaia's Tip, Tricks, How-tos, and FAQs

IPtables (starter Guide to free secure firewalls)

A firewall is a software which is used to control the movement of network traffic according to a set of rules. Linux ships with an excellent GPLed firewall called iptables. Here I will explain the rudimentary concepts in using iptables.

Iptables is a packet filter which supersedes the erstwhile ipchains. It forms the first point of contact for packets that flow into or out of your network. In fact the packets are checked in the following order when it reaches your computer.

As you can see in the above diagram, iptables works in the kernel space.

Here I will give a simple introduction to this very useful and powerful but cryptic form of securing ones network. If you are using kernel 2.4 and above, you will be using iptables. Iptables functionality is directly compiled into the Linux kernel as a module (netfilter). The policies are checked at the layers 2, 3 and 4 of the OSI Reference Model. That is 'Datalink', 'Network' and 'Transport' layer. It is very fast because only the packet headers are inspected. There is a wonderful tutorial on configuring firewalls using iptables at Netfilter.org. But if you are lazy (like me :) ) to plod through over 130 pages of the tutorial, then read on ...

Netfilter tables :

There are three inbuilt tables. They are as follows:

  1. filter - This is the default table if no table name is specified in the rule. The main packet filtering is performed in this table.
  2. nat - This is where Network Address Translation is performed. For example, if you are using your machine as a router or sharing your internet connection with other machines on your network, you might use the NAT table in your rule.
  3. mangle - This is where a limited number of 'special effects' can happen. This table is rarely used.

Netfilter chains :

I said above that each table has a number of inbuilt chains. These are as follows: For filter table

  1. INPUT - Handles packets destined for the local system, after the routing decision.
  2. OUTPUT - This chain handles packets after they have left their sending process and before being processed by POSTROUTING (applicable to nat and mangle) chain.
  3. FORWARD - This chain handles packets routed through the system but which are actually destined for another system on your LAN.
For the nat table
  1. OUTPUT - see explanation above.
  2. PREROUTING - This is the entry point of packets on their arrival. All packets first pass through this chain before even passing through the routing decision.
  3. POSTROUTING - If PREROUTING is the first chain that a packet encounters, POSTROUTING is the final point of contact for any packet before it leaves the system.
For mangle table
  • The mangle table contains a union of all the chains in the filter and nat tables.

Note: Over and above the builtin chains, you can also have custom user defined chains too. Usually you use a custom chain to group a series of actions together before passing it to one of the inbuilt chains.

Rule targets :

As I said above, each chain can have different targets. They are broadly classified into builtin and extension targets. The target names must be preceded by the option -j . -j as in jump. These are the targets:

Builtin targets

  • DROP - As the name indicates, discards the packet. No message is relayed back to the sender of the packet.
  • ACCEPT - Allows the packet to pass through the firewall.
  • RETURN - This is a built in target which is created for convenience. Because most targets do not return. That is if a packet matches a rule, the checking of that packet ceases and the chain is exited.

Extension targets

  • LOG - This is used to log messages to your system of offending or blocked packets. Usually, control is passed to the syslog facility which logs the message to the file /var/log/messages and then returns the control back to the iptables.
  • REJECT - If this target is used, a notice is sent back to the sender. Like for example "you are denied access to this service" message.
  • DNAT - Used for destination NAT ie rewriting the destination IP address of the packet.
  • MASQUERADE - This is used to do either SNAT or DNAT. Basically this target is used to set up internet connection sharing in your network.
Note: All extension targets are usually implemented in special-purpose kernel modules. To know which all modules are loaded on your system, execute the command:

These are the modules that are loaded on my system. As you can see, all modules that start with the name 'ipt_' are extension modules. So in the above listing, iptable_nat module uses a extension module called ipt_MASQUERADE . And to use the LOG extension target, you should have loaded the ipt_LOG extension module. So on and so forth :) .

A few examples to whet your appetite

The above rule can be read as follows. In the filter table (-t), append (-A) to the INPUT chain the rule that, all packets using the protocol (-p) tcp and originating (-s) from the remote machine with IP address 192.168.0.5 should be dropped (-j DROP).

This rule reads as follows: Append (-A) to the FORWARD chain, the rule that all packets coming from anywhere (-s 0/0) using the protocol (-p) TCP and using unreserved ports (--sport 1024:65535), incoming (-i) through the interface eth0 , and destined (--dport) for port 80 on address (-d) 192.168.5.5 and outgoing (-o) through the interface eth1 should be accepted.

List (-L) all the rules in the iptables.
Flush (-F) all the rules from iptables. Now you can start afresh.>
Log all incoming and outgoing rules in the filter table to the file /var/log/messages.

I hope you have got the drift ;) . Iptables is a very powerful and flexible tool and can be used to block anything or everything that comes into or goes out of your computer.

Wait there is one more thing ...

Usually the commands that you executed above will reside in memory but will not persist across rebooting. Which means, once you reboot, all your rules are lost and you have to start all over. So to avoid this, you save your rules into a file which is read by the OS when you reboot your machine. (should be something like /etc/sysconfig/iptables)
You save it using the programs iptables-save as follows:

or

There is another script called iptables-restore which can be used to load the rules from a file into memory.

Go Back



Designing a firewall for home use

The fact that you are reading this means that you eather read the above secton on iptables, or know of iptables already and just need some pointers on how to set up a firewall using it. Eather way you are going to get what you are looking for, so get your coffiee ready because your going to need it. This how to focus on a home environment with a single computer connected to the internet using a wired connection, this is just to help with the basics there is a lot more that you can do (and will need to do in order to set up a strong firewall) what I have here can be used in pretty much any case with enough work and understanding.

Here I will explain how you can make your home machine which is connected to the internet , which I am giving the name 'my_machine', more secure. First let us see what are the services that are running on the home machine (my_machine). Usually when you install Linux on your machine, you will be having some default services. They are as follows:

  • sshd - Secure Shell server
  • portmap - Which is used by file services like NFS
  • httpd - Apache web server
  • ftp server - File Transfer Protocol server. This is not usually running on a home machine but just make sure about it by checking. In RedHat based Distros, you can check by running the command:
If you have nmap installed on your machine you can run the following command:
To find and list any open ports on your machine. The output of mine is this:

For the sake of this how to we are going to pretend that nmap returned the following (This as a lot more for us to work with here):
As seen above, I have apache webserver (http) , ssh, mysql server, X Server and rpcbind open to the outside world. rpcbind is used by NFS for mounting a remote drive. Usually a stand alone machine in our case my_machine need not open these services to the internet - except maybe ssh server which you might need to say - connect to your machine from a remote location - that too only if you have a static IP address, which is quite rare.

Now that we know what ports we have open to everyone and their grandmother lets see about fixing our firewall to close them. You may want to use a pen and paper, or a text editer to plan out what you want your new firewall to block and allow. Here is what we are going to go with for this HOWTO:

  1. I want full access to my_machine locally. That is all the services should be available for the localhost or IP address 127.0.0.1 .
  2. New connections originating from a remote machine to Portmap, ssh, webserver and X server has to be blocked.
  3. Established and related connections to my_machine has to be allowed. Here I would like to deviate from the topic to explain the terms 'new','established' and 'related'.For that you have to look at how TCP works. TCP is a connection-oriented protocol. Connection-oriented means that it makes sure all the packets reach the destination without any packet loss in transit. If a packet is lost, it re-sends the lost packet. This it achieves by using a set of flags. The flags are called SYN (Synchronize) and ACK (Acknowledge). When you click on a link in your web browser, your machine sends a SYN packet to the remote server which hosts the link. This process is called initiating a connection and is represented as NEW connection. When the remote server receives your request which has the flag SYN set, it sends a acknowledgment back to your machine by setting the SYN-ACK flag. And this is called a related connection. Once your machine receives the SYN-ACK packet, it responds with a final ACK packet which tells the remote machine that we have indeed received the packet. Then the connection is said to be established. This is called the three way handshake.
  4. Restrict anyone initiating a new connection to my_machine from a remote location.
  5. Allow all outgoing connections originating from my_machine.
  6. Restrict all other incoming connections.

With all that said and done lets make some firewall rules!

Note: all allow rules must precede the deny rules.

Iptables Rules:

Allow all related and established tcp connections to my_machine.
Allow all outgoing connections from my_machine.
Deny all new tcp connections from remote machines. And log the same.
Block the apache port on my_machine. See the nmap command listing above. Also log the traffic.
Block ssh to my_machine. Also log the traffic.
Now for everything else:

Go Back



TCP Wrappers in Linux

TCP Wrappers can be used to GRANT or DENY access to various services on your machine to the outside network or other machines on the same network. It does this by using simple Access List Rules which are included in the two files /etc/hosts.allow and /etc/hosts.deny.

Let us consider this scenario: A remote machine remote_mc trying to connect to your local machine local_mc using ssh. When the request from the remote_mc is received by the tcp wrapped service (SSH in this case), it takes the following basic steps:

  1. It checks the /etc/hosts.allow file and applies the first rule specified for that service. If it finds a matching rule , it allows the connection. If no rule is found, it moves on to step 2.
  2. It checks the /etc/hosts.deny file and if a matching rule is found, it deny's the connection.

Points to remember

  • Rules in hosts.allow takes precedence over rules in hosts.deny . Which means if a matching rule is found in hosts.allow file, the remote_mc is allowed access to the service even if there is a matching deny rule in hosts.deny file.
  • You can have only one rule per service in hosts.allow and hosts.deny file.
  • If there are no matching rules in either of the files or if the files don't exist, then the remote_mc is allowed access to the service.
  • Any changes to hosts.allow and hosts.deny file takes immediate effect.

Rule Syntax

The syntax for both hosts.allow and hosts.deny file takes the following form:

Where daemon can be a combination of ssh daemon, ftp daemon, portmap daemon and so on. Basically any service which has support for libwrap.a library compiled into it is a good candidate for utilizing the services of TCP Wrappers.

client is a comma separated list of hostnames, host IP addresses, special patterns or special wildcards which identify the hosts effected by that rule.

options is an optional action like say sending mail to the administrator when this rule is matched, log to a particular file and so on. It can be a colon separated list of actions too.

Examples of using TCP Wrappers

I want to allow SSH access to hosts in a particular domain say xyz.com and deny access to all the others. I enter the following rule in the hosts.allow file.

... and in the hosts.deny file I include the rule:
The next rule denys FTP access to all the hosts in the abc.co.in domain as well as hosts in the 192.168.1.0 network.
The backslash (\) in the above rule is used to break the line and prevents the failure of the rule due to length.
spawn and deny are options. Spawn launches a shell command as a child process. In the above rule, spawn logs a message to the vsftpd log file each time the rule matches. deny is optional if you are including this rule in the hosts.deny file.

Note: The last line in the files hosts.allow and hosts.deny must be a new line character. Or else the rule will fail. For example, you can use spawn option to send mail to the admin when ever a deny rule is matched.

Wildcards

You can use wildcards in the client section of the rule to broadly classify a set of hosts. These are the valid wildcards that can be used.

  • ALL - Matches everything
  • LOCAL - Matches any host that does not contain a dot (.) like localhost.
  • KNOWN - Matches any host where the hostname and host addresses are known or where the user is known.
  • UNKNOWN - Matches any host where the hostname or host address are unknown or where the user is unknown.
  • PARANOID - Matches any host where the hostname does not match the host address.

Patterns

You can also use patterns in the client section of the rule . Some examples are as follows:

Matches all hosts in the xyz.com domain . Note the dot (.) at the beginning.
Matches all the hosts in the 123.12.0.0 network. Note the dot (.) in the end of the rule.
IP address/Netmask can be used in the rule.
Asterisk * matches entire groups of hostnames or IP addresses.
If the client list begins with a slash (/), it is treated as a filename. In the above rule, TCP wrappers looks up the file sshd.deny for all SSH connections.
If the above rule is included in the /etc/hosts.deny file, then it will allow ssh connection for only the machine with the IP address 192.168.0.15 and block all other connections. Here EXCEPT is an operator.

Note: If you want to restrict use of NFS and NIS then you may include a rule for portmap . Because NFS and NIS depend on portmap for their successful working. In addition, changes to portmap rules may not take effect immediately.

Suppose I want to log all connections made to SSH with a priority of emergency. I could do the following:

Note: You can use the options allow or deny to allow or restrict on a per client basis in either of the files hosts.allow and hosts.deny

Shell Commands

As mentioned above, you can couple the rules to certain shell commands by using the following two options. spawn - This option launches a shell command as a child process. For example, look at the following rule:

Each time the rule is satisfied, the current date and the clients hostname %h is appended to the ssh.log file. twist - This is an option which replaces the request with the specified command. For example, if you want to send to the client trying to connect using ssh to your machine, that they are prohibited from accessing SSH, you can use this option.
When using spawn and twist, you can use a set of expressions. They are as follows :
  • %a — The client's IP address.
  • %A — The server's IP address.
  • %c — Supplies a variety of client information, such as the username and hostname, or the username and IP address.
  • %d — The daemon process name.
  • %h — The client's hostname (or IP address, if the hostname is unavailable)
  • %H — The server's hostname (or IP address, if the hostname is unavailable).
  • %n — The client's hostname. If unavailable, unknown is printed. If the client's hostname and host address do not match, paranoid is printed.
  • %N — The server's hostname. If unavailable, unknown is printed. If the server's hostname and host address do not match, paranoid is printed.
  • %p — The daemon process ID.
  • %s — Various types of server information, such as the daemon process and the host or IP address of the server.
  • %u — The client's username. If unavailable, unknown is printed.

Go Back



Configuring Apache webserver to restrict access to your website

Apache Webserver is the most popular web server and has a market share of around 60%. Here I will explain a small but very useful feature of the apache web server - which is restricting access to (a part of) your website to only the privileged few by implementing username and passwords.

There are two ways of restricting access to documents.

  1. Either by the hostname of the browser being used
  2. By asking a username and password

The first method can be used to, for example, restricting documents being used within a company. But if the people who are accessing documents are widely dispersed, then the second method is more suitable.

Here I will explain the second method - ie, assigning username and passwords to users who are authorized to access the documents. This is known as user authentication. Setting up user authentication takes two steps : Create a file containing username and passwords - Apache webserver has a utility called htpasswd to create the file containing username and passwords. Here I am creating a file called 'users' in the /usr/local/etc/ directory.

Note: For security reasons, the above file should NOT be under the document root. It can be anywhere BUT the document root.

The first time you run the htpasswd utility, you run it using the -c flag as follows:

The -c argument tells htpasswd to create a new users file. When you run the above command, you will be prompted to enter a password for the user gopinath, and confirm it by entering it again. Other users can be added to the existing file in the same way, except that the -c argument is not needed. The same command can also be used to modify the password of an existing user.

After adding a few users, the /usr/local/etc/users file might look like this :

The first field is the username and the second field is the encrypted password. Now comes the Apache server's configuration part. Open the apache server's configuration file /etc/httpd/conf/httpd.conf (your configuration file will be in different location depending on the distribution you are using) and look for the line :
And change it to
If you want to protect the document root itself, create a file '.htaccess' in the top directory path and include the following lines to it:
AuthName - directive specifies a realm name for this protection. Once a user has entered a valid username and password, any other resource within the same realm name can be accessed with the same username and password. AuthType - directive tells the server what protocol is to be used for authentication. At the moment, 'Basic' is the only method available. However, a new method, 'Digest' is about to be standardized, and once browsers start to implement it, Digest authentication will provide more security than Basic authentication. AuthUserFile - tells the server the location of the user file created by htpasswd utility. A similar directive, AuthGroupFile, can be used to tell the server the location of a group's file.

Lastly don't forget to restart the web server which rereads the changed configuration files :

From here on when you try to access your protected site or the directory via the web browser, you will be asked for authentication first. And only those users whose name has been entered in the file pointed to by the AuthUserFile directive will be allowed access to your site.

Go Back

Table Of Contents
- About this Site - Auto Config Xorg
- How to burn and run an ISO file
- How to Install Ubuntu
- Downloading openSUSE
- How to Install Ubuntu on a Mac G3
- Duel Booting with Windows Vista
- Editing a bash command
- Bash Completion
- Special Shell variables
- Bash shell shortcuts
- Configuring Xterm in Linux
- A short guide to bash shell scripting
- Enhanching System prompt $ps1
- Screen
- Find number of days since Jan 1
- Mount your files the Linux way
- Script
- Bunring audio and data CDs in Linux
- How to play VCD .dat files using mplayer
- Converting a VCD .dat file to mp3
- An easy way to play songs remotely/have a media player...
- RPM package manager
- Autopackage
- Convert between RPM, DEB, and TAR package formats
- How to make your own package CDs for offline use
- Intalling Mono in Linux
- Configuring Java in linux
- Installing Active x in Linux
- How to install beryl on Ubuntu
- VIM
- Using Abiword to convert filetypes on the command line
- iptables (starters guide)
- Designing a firewall using Iptables
- TCP Wrappers in Linux
- Apache Webserver
- Routing, NAT, and Gateways explained
- Apache
- Understanding DNS
- DNS on Linux
- Who owns which port
- NIS client (server configuration)
- DHCP server configuration
- Change the hostname of your machine
- Intergrating Mac, Linux, and Windows machines in a network with centerlized login
- Sendmail
- Sendmail configuration
- Change your MTA
- Redirecting roots mail to another user
- Mutt
- fetchmail and Gmail
- Creating a Linux mail server
- Different ways of locking a users account in Linux
- Preventing a non-root user from shutting down / restarting the machine
- Disk Quotas in Linux
- Change system log in banner in Linux
- Enable centerlized login with Linux
- System Logging explaned
- Tips to secure your computer
- Find
- Cron
- SSH
- Setting up SSH in Linux
- SUDO
- Job Control
- Sharing Directories among several users
- /proc filesystem explained
- NFS
- hdparm
- Adding a swap file to your Linux system
- chroot
- Get exact control over your files and directories in Linux
- Mounting NTFS filesystem in Linux
- Autofs
- LVM creation
- Resizing LVM
- CPIO
- Backup your data with rsync
- Confinguring the Rockwell chipset winmodem in Linux
- Configuring sound in Linux
- Configuring Microsoft serial intellimouse
- NVIDEA
- Installing HD in Linux
- How to install a network card in Linux
- Assigning a IP adress to your NIC
- Setting up multiple IP adresses on a single NIC
- How to change the MAC address of your machine
- Find the speed of your NIC
- Compilation of Linux kernel from source (2.4 only)
- Compilation of Linux kernel from source (2.6 only)
- MySQL Cheatsheet - Enable restart option on KDE menu - Connection to a BSNL internet dailup account - 3ddesktop
- Linux EyeCandy
- New Desktop theme
- Skinning your Desktop
- Windows managers in Linux
- Tag your files in GNOME
- How to use windows fonts in Mozilla