≡ Menu

iptables command

Linux: 20 Iptables Examples For New SysAdmins

Linux comes with a host based firewall called Netfilter. According to the official project site:

netfilter is a set of hooks inside the Linux kernel that allows kernel modules to register callback functions with the network stack. A registered callback function is then called back for every packet that traverses the respective hook within the network stack.

This Linux based firewall is controlled by the program called iptables to handles filtering for IPv4, and ip6tables handles filtering for IPv6. I strongly recommend that you first read our quick tutorial that explains how to configure a host-based firewall called Netfilter (iptables) under CentOS / RHEL / Fedora / Redhat Enterprise Linux. This post list most common iptables solutions required by a new Linux user to secure his or her Linux operating system from intruders.
[click to continue…]

I've already wrote about setting up a Linux transparent squid proxy system. However I'm getting lots of questions about Squid basic installation and configuration:

How do I install Squid Proxy server on CentOS 5 Liinux server?

Sure Squid server is a popular open source GPLd proxy and web cache. It has a variety of uses, from speeding up a web server by caching repeated requests, to caching web, name server query , and other network lookups for a group of people sharing network resources. It is primarily designed to run on Linux / Unix-like systems. Squid is a high-performance proxy caching server for Web clients, supporting FTP, gopher, and HTTP data objects. Unlike traditional caching software, Squid handles all requests in a single, non-blocking, I/O-driven process. Squid keeps meta data and especially hot objects cached in RAM, caches DNS lookups, supports non-blocking DNS lookups, and implements negative caching of failed requests. Squid consists of a main server program squid, a Domain Name System lookup program (dnsserver), a program for retrieving FTP data (ftpget), and some management and client tools.

Install Squid on CentOS / RHEL 5

Use yum command as follows:
# yum install squid

Loading "installonlyn" plugin
Setting up Install Process
Setting up repositories
Reading repository metadata in from local files
Parsing package install arguments
Resolving Dependencies
--> Populating transaction set with selected packages. Please wait.
---> Package squid.i386 7:2.6.STABLE6-4.el5 set to be updated
--> Running transaction check
Dependencies Resolved
 Package                 Arch       Version          Repository        Size
 squid                   i386       7:2.6.STABLE6-4.el5  updates           1.2 M
Transaction Summary
Install      1 Package(s)
Update       0 Package(s)
Remove       0 Package(s)
Total download size: 1.2 M
Is this ok [y/N]: y
Downloading Packages:
Running Transaction Test
Finished Transaction Test
Transaction Test Succeeded
Running Transaction
  Installing: squid                        ######################### [1/1]
Installed: squid.i386 7:2.6.STABLE6-4.el5

Squid Basic Configuration

Squid configuration file located at /etc/squid/squid.conf. Open file using a text editor:
# vi /etc/squid/squid.conf
At least you need to define ACL (access control list) to work with squid. The defaults port is TCP 3128. Following example ACL allowing access from your local networks and Make sure you adapt to list your internal IP networks from where browsing should be allowed:
acl our_networks src
http_access allow our_networks

Save and close the file. Start squid proxy server:
# chkconfig squid on
# /etc/init.d/squid start


init_cache_dir /var/spool/squid... Starting squid: .       [  OK  ]

Verify port 3128 is open:
# netstat -tulpn | grep 3128

tcp        0      0      *                   LISTEN      20653/(squid)

Open TCP port 3128

Finally make sure iptables is allowing to access squid proxy server. Just open /etc/sysconfig/iptables file:
# vi /etc/sysconfig/iptables
Append configuration:
-A RH-Firewall-1-INPUT -m state --state NEW,ESTABLISHED,RELATED -m tcp -p tcp --dport 3128 -j ACCEPT
Restart iptables based firewall:
# /etc/init.d/iptables restart

Flushing firewall rules:                                   [  OK  ]
Setting chains to policy ACCEPT: filter                    [  OK  ]
Unloading iptables modules:                                [  OK  ]
Applying iptables firewall rules:                          [  OK  ]
Loading additional iptables modules: ip_conntrack_netbios_n[  OK  ]

Client configuration

Open a webbrowser > Tools > Internet option > Network settings > and setup Squid server IP address and port # 3128.

See also

You may find our previous squid tips useful:

Squid Security and blocking content Related Tips

Squid Authentication Related Tips

Squid Other Tips

Someone recently asked me a question:

How can I save time and script size by specifying a range of IP addresses or ports using iptables?

In old version of iptables IP address ranges are only valid in the nat table (see below for example). However newer version does support option that allows you to specify a range of IP addresses or ports for regular tables such as input.

Iptables set range of IP addresses

You need to use following options with match extensions (-m Ext).

iprange : This matches on a given arbitrary range of IPv4 addresses.

  • [!]--src-range ip-ip: Match source IP in the specified range.
  • [!]--dst-range ip-ip: Match destination IP in the specified range.


-m iprange --src-range IP-IP -j ACTION
-m iprange --dst-range IP-IP -j ACTION

For example, allow incoming request on a port 22 for source IP in the range only. You need to add something as follows to your iptables script:

iptables -A INPUT -p tcp --destination-port 22 -m iprange --src-range -j ACCEPT  

Port range

if --protocol tcp (-p tcp) is specified, you can specify source port range with following syntax:

  • --source-port port:port
  • --sport port:port

And destination port range specification with following option :

  • --destination-port port:port
  • --dport port:port

For example block lock all incoming ssh access at port 22, for source port range 513:65535:

iptables -A INPUT -p tcp -s 0/0 --sport 513:65535 -d --dport 22 -m state --state NEW,ESTABLISHED -j DROP

On the other hand, just allow incoming ssh request with following port range:

iptables -A INPUT -p tcp -s 0/0 -d --sport 513:65535 --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -p tcp -s -d 0/0 --sport 22 --dport 513:65535 -m state --state ESTABLISHED -j ACCEPT

NAT table - range option

If you are using NAT table use options --to-source and --to-destination. For example IP address range:

iptables -t nat -A POSTROUTING -j SNAT --to-source

ALTERNATIVELY, try range of ports:

iptables -t nat -A POSTROUTING -j SNAT --to-source

Read man page of iptables for more information.

It is true that connections to remote X Window servers should be always made over SSH. SSH supports X windows connections. So my task was allow X over ssh but block unprivileged X windows mangers TCP ports.

The first running server (or display) use TCP port 6000. Next server will use 6001 and so on upto 6063 (max 64 X managers are allowed from 6000-6063).

So assuming that you are going to force user to use ssh for remote connections, here are rules for IPTABLES (add to your firewall script):

iptables -A OUTPUT -o eth0 -p tcp --syn --destination-port 6000:6063 -j REJECT
iptables -A INPUT -i eth0 -p tcp --syn --destination-port 6000:6063 -j DROP

a) The first rules blocks outgoing connection attempt to remove X windows manger.

b) The second rule block incoming request for X windows manger. By using --syn flag you are blocking only connection establishments to the server port.

This is the good way to disallow unprivileged X windows mangers - TCP 6000:6063 ports :)

See also:

Network attached storage (NAS) allows using TCP/IP network to backup files. This enables multiple servers in IDC to share the same storage for backup at once, which minimizes overhead by centrally managing hard disks. NAS is scalable, high performance network solution. The main advantage is more hard disk storage space added to a network that already utilizes servers without shutting them down for maintenance and upgrades.

Please note that NAS are not just common in IDC or offices but you can use it for file sharing and backup at home. You can purchase 200+GB NAS for less than $200 these days. Personally, I am using Maxtor ShareStorage 200GB Network Attached Storage at home. This is a step-by-step guide on connecting Linux or UNIX systems to SAN for backup or sharing files.

The protocol used with NAS is a file-based protocol such as NFS or Microsoft's Common Internet File System (CIFS). Both of them allow storing backups using UNIX and Linux servers or Windows 2003 server.

However many new Linux or UNIX sys admin find it difficult to use NAS backup. Here are quick handy tips most newbie will find useful.

(A) Use IP address of NAS. If you do not have properly configured SAMBA server it is difficult to resolve hostnames. IP address will save your time.

(B) If you are using IPTABLES or PF firewall then make sure the following UDP/TCP ports are open between your firewall and the NAS Backup Server:

  1. TCP 21 (ftp)
  2. TCP 20 (ftp-data)
  3. TCP/UDP 137 (NETBIOS Name Service aka netbios-ns)
  4. TCP/UDP 138 (NETBIOS Datagram Service aka netbios-dgm)
  5. TCP/UDP 139 (NETBIOS session service aka netbios-ssn )
  6. TCP/UDP 445 (Microsoft Naked CIFS aka microsoft-ds )

Sample network diagram

Following is sample network diagram for our setup:

+-------------+               +-------------+
|             |               |             |
|   N A S     |<=============>|   Linux/    |
|             |               |   UNIX      |
IP:              IP:

Iptables configuration

FTP outgoing client request using iptables (assuming that your server IP is and NAS IP is Append following iptables rules to your script:

iptables -A OUTPUT -p tcp -s --sport 1024:65535 -d --dport 21 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -p tcp -s --sport 21 -d --dport 1024:65535 -m state --state ESTABLISHED -j ACCEPT
iptables -A OUTPUT -p tcp -s --sport 1024:65535 -d --dport 1024:65535 -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -p tcp -s --sport 1024:65535 -d --dport 1024:65535 -m state --state ESTABLISHED -j ACCEPT

NETBIOS/CIFS outgoing client request

Please add following rules to your iptables script:

iptables -A OUTPUT -p udp -s --sport 137 -d 0/0 --dport 137 -j ACCEPT
iptables -A OUTPUT -p udp -s --sport 138 -d 0/0 --dport 138 -j ACCEPT
iptables -A OUTPUT -p tcp -s --sport 1024:65535 -d --dport 139 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A INPUT -p udp -s --sport 137 -d --dport 137 -j ACCEPT
iptables -A INPUT -p udp -s --sport 138 -d --dport 138 -j ACCEPT
iptables -A INPUT -p tcp -s --sport 139 -d --dport 1024:65535 -m state --state ESTABLISHED -j ACCEPT

Please note that when configuring a firewall, the high order ports (1024-65535) are often used for outgoing connections and therefore should be permitted through the firewall. It is prudent to block incoming packets on the high order ports except for established connections. This is what you are doing in above FTP and CIFS client request.

How do I access NAS server using FTP?

You need to use Internet file transfer program (FTP) that comes with UNIX/Linux or windows. Most service provider will provide you:

  • NAS Server IP (e.g. / nas.myserviceprovider.com)
  • NAS FTP Username (e.g. nixcraft)
  • NAS FTP Password (e.g. mySecret)

Let us assume you have file called mysqldump.tar.gz. You can put this file to NAS backup server using following ftp command:

$ ftp nas.myserviceprovider.com


$ ftp


Username: nixcraft
Password: mySecret
ftp> bin
200 Type set to I.
ftp> prom
Interactive mode off.
ftp> put mysqldump.tar.gz
ftp> quit

How do I access NAS server using SAMBA client?

Make sure you have samba client installed. Use apt-get or up2date command to install SAMBA client.

a) Create a directory

# mkdir /backup

b) Mount remote NAS share (NOTE: you must type following command on a single line)

# mount -t smbfs -o username=nixcraft,password=mySecret // /backup


# smbmount -o username=nixcraft,password=mySecret // /backup

You can skip password option for security reason (samba will prompt you for password).

c) Copy files using cp command:

# cp sitebackup.tar.gz /backup

d) You can use /backup directory to dump backup using mysql script or backup shell script.

A note for FreeBSD user

If you would like to access NAS server from FreeBSD use following command (NOTE: you must type following command on a single line):

# mkdir /backup
# mount_smbfs -I //nixcraft@ /backup



Related previous articles

Updated for accuracy.

How To Monitor Bandwidth With iptables

Simple and quick way to set up straightforward bandwidth monitoring with iptables,"Linux has a number of useful bandwidth monitoring and management programs. A quick search on Freshmeat.net for bandwidth returns a number of applications. However, if all you need is a basic overview of your total bandwidth usage, iptables is all you really need -- and it's already installed if you're using a Linux distribution based on the 2.4.x or 2.6.x kernels" ..

Full article: online here.

I use ADSL at home via ISP modem. As soon as my eth0 comes up I would like to have my firewall script get executed and setup the iptables firewall rules for me.
[click to continue…]