Thursday, December 22, 2011

Drupal 7: HipHop for PHP vs APC – benchmark

SkyHi @ Thursday, December 22, 2011
Drupal is one of two most popular content management systems (CMS) written in PHP . It is used as a back-end system for at least 1.5% of all websites worldwide. It is also one with the the slowest systems of this kind on the Internet
There have been many suggestions on improving Drupal performance, some of them recommend the use of APC module, data caching, or even compilation of the entire system through HipHop for PHP. While the first two solutions have been successfully implemented, no one was able to perform the build process.
After many battles with the compiler and the Drupal code, I present you results of the first successful translation of Drupal 7 to C++ language.

Introduction

All tests were conducted on a modified version of Drupal. These changes were necessary in order to ensure compatibility with HipHop translator.
You can download modified source codes from this link.
The system was installed in the minimal version and then launched in three different ways:
  • as a standard PHP script
  • as a PHP script with APC opcode caching enabled
  • in the form of a compiled program
Due to hardware limitations the MySQL server is located on the same machine as the web server, more advanced tests will be performed in the near future using the multiple servers.

Testing platform

Processor: Intel(R) Core(TM)2 Duo CPU E7600 @ 3.06GHz
Memory: 2.5GB RAM
System: Fedora 12 (64bit)
Kernel: 2.6.32.26-175.fc12.x86_64 #1 SMP
The server was used exclusively for testing purposes – it was running only the services associated with the benchmark.

Test Configuration

Apache version: 2.2.15
MySQL Server Version: 5.1.47
PHP Version: 5.3.3
HipHop for PHP Version: 806ee06
Drupal Version: 7.0
Drupal was compiled with this command:
cd ~drupal
date && ~/hiphop/hiphop-php/src/hphp/hphp  --keep-tempdir=1\
 --log=3\
 --input-list=files.full.list\
 --include-path="." --force=1\
 --cluster-count=240\
 -v "AllDynamic=true"\
 -v "AllVolatile=true"\
 -o /tmp/drupal\
 --parse-on-demand=0\
 --sync-dir=/tmp/sync
And launched with this command:
cd ~drupal
/tmp/drupal/program -m server -p 80\
 -v "Server.SourceRoot=`pwd`"\
 -v "Server.DefaultDocument=index.php"\
 -c $HPHP_HOME/bin/mime.hdf\
 -v "Log.File=/tmp/errors"\
 -v "ErrorHandling.AssertActive=true"\
 -v "ErrorHandling.AssertWarning=true"\
 -v "ErrorHandling.WarningFrequency=10000"\
 -v "ErrorHandling.NoticeFrequency=10000" &

CPU usage

The following test examines the performance of Drupal by simulating the concurrent activity of many visitors on the Drupal home page.
I found that in case of a dual core server four was the optimal number of concurrent users, so I used the ab program as as a benchmark tool and launched it with a following command:
ab -n 300 -c 4 http://achilles.webtutor/
The first result shows the CPU usage of a regular PHP script during the execution of the 300 HTTP requests started by 4 concurrent users:

sy = system CPU usage (gradient color), us = user CPU usage (solid color)
As you can see Drupal is indeed a very demanding system. The test in this case took almost 20 seconds, which gave a dissapointing result of 15 requests per second.
Let’s see what we get after enabling the APC module. Results are as follows:

Drupal performance improved dramatically. The test was completed in 6 seconds, 3 times faster than with traditional PHP! Due to the size of Drupal code, however, this result is not shocking. While the APC module will not speed up the script itself, its opcode cache eliminates the delay caused by having to parse PHP code on every HTTP request.
Interestingly, Drupal is not able to use the full computing power of the test server. The official cause is unknown, however it may caused by some kind of internal locking in the APC module.
Since we know how much the opcode cache improves performance by omitting the PHP parser, its time to test how much we can accelerate the PHP code itself. We check this by translating Drupal source code to C++ and compiling the application:
Compiled Drupal application is five times faster than a regular script, and almost two times faster than a script launched from the opcode cache!
Let’s compare the results. The first is the detailed comparison of CPU usage:
And the overall CPU usage:
Here are the results taken directly from the ab tool:
Environment      Execution 
   Type        time [300 req]
-----------------------------
Regular PHP      19.873 sec
PHP + APC         6.396 sec
HipHop for PHP    3.896 sec

Concurrency benchmark

In this scenario I measured a number of requests performed per second. The summary results are as follows:
Type of environmentRequests per second [#/sec]Time per request [ms]Req/sec ratio [%]
Regular PHP15.1066.242100%
PHP + APC (opcode cache)46.9021.321310%
HipHop for PHP77.0112.985510%

Other concurrency levels

As a curiosity I decided to investigate how the Drupal’s performance can be affected by a variable number of concurrent users. In order to do so I tested the system with seven different workloads simulating 1, 2, 4, 8, 16, 32 and 64 concurrent users.
Here are the results:
Tabular version:
Users    PHP     APC   HipHop 
-----------------------------
  1      8.68   28.11   40.23
  2     13.34   38.25   56.12
  4     15.28   46.82   74.12
  8     14.76   49.96   72.12
  16    14.04   49.09   74.12
  32    12.35   45.00   77.67
  64     5.22   39.17   73.02
Please note: this test is heavily CPU bound and should be executed on a multicore servers instead.
As you can see, in case of APC and HipHop for PHP translator Drupal scales quite well up to the 8 simultaneous users on a dual CPU system. Unfortunately the same cannot be said about regular PHP interpreter, which is much slower in every tested scenario.

Different optimization levels in GCC compiler

Without any optimization option, the compiler’s goal is to reduce the cost of compilation and to make debugging produce the expected results.
Turning on optimization flags makes the compiler attempt to improve the performance and/or code size at the expense of compilation time and possibly the ability to debug the program.
Let’s see the results of different optimization levels switched on during the Drupal compilation:
optimization    req/sec
    level
--------------------------
   default         74.12
     -o2           87.11
     -o3           90.04
The difference of 12 req/sec between a default and -o2 optimization is quite big and almost equals to the 15 req/sec achieved by an interpreted PHP script!
What’s more in case of -o3 optimization Drupal is up to 6 times faster than in a pure PHP environment.

Summary

As I mentioned on the outset Drupal is not the fastest system on the Internet. However, after several changes in the code to add compatibility with HipHop for PHP, it becomes a very effective tool in the hands of every webmaster.

Other articles about HipHop for PHP

Linux: 20 Iptables Examples For New SysAdmins

SkyHi @ Thursday, December 22, 2011
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.

IPTABLES Rules Example

  • Most of the actions listed in this post are written with the assumption that they will be executed by the root user running the bash or any other modern shell. Do not type commands on remote system as it will disconnect your access.
  • For demonstration purpose I've used RHEL 6.x, but the following command should work with any modern Linux distro.
  • This is NOT a tutorial on how to set iptables. See tutorial here. It is a quick cheat sheet to common iptables commands.

#1: Displaying the Status of Your Firewall

Type the following command as root:
# iptables -L -n -v
Sample outputs:
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
Chain FORWARD (policy ACCEPT 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
Above output indicates that the firewall is not active. The following sample shows an active firewall:
# iptables -L -n -v
Sample outputs:
Chain INPUT (policy DROP 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
    0     0 DROP       all  --  *      *       0.0.0.0/0            0.0.0.0/0           state INVALID
  394 43586 ACCEPT     all  --  *      *       0.0.0.0/0            0.0.0.0/0           state RELATED,ESTABLISHED
   93 17292 ACCEPT     all  --  br0    *       0.0.0.0/0            0.0.0.0/0
    1   142 ACCEPT     all  --  lo     *       0.0.0.0/0            0.0.0.0/0
Chain FORWARD (policy DROP 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
    0     0 ACCEPT     all  --  br0    br0     0.0.0.0/0            0.0.0.0/0
    0     0 DROP       all  --  *      *       0.0.0.0/0            0.0.0.0/0           state INVALID
    0     0 TCPMSS     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0           tcp flags:0x06/0x02 TCPMSS clamp to PMTU
    0     0 ACCEPT     all  --  *      *       0.0.0.0/0            0.0.0.0/0           state RELATED,ESTABLISHED
    0     0 wanin      all  --  vlan2  *       0.0.0.0/0            0.0.0.0/0
    0     0 wanout     all  --  *      vlan2   0.0.0.0/0            0.0.0.0/0
    0     0 ACCEPT     all  --  br0    *       0.0.0.0/0            0.0.0.0/0
Chain OUTPUT (policy ACCEPT 425 packets, 113K bytes)
 pkts bytes target     prot opt in     out     source               destination
Chain wanin (1 references)
 pkts bytes target     prot opt in     out     source               destination
Chain wanout (1 references)
 pkts bytes target     prot opt in     out     source               destination
Where,
  • -L : List rules.
  • -v : Display detailed information. This option makes the list command show the interface name, the rule options, and the TOS masks. The packet and byte counters are also listed, with the suffix 'K', 'M' or 'G' for 1000, 1,000,000 and 1,000,000,000 multipliers respectively.
  • -n : Display IP address and port in numeric format. Do not use DNS to resolve names. This will speed up listing.

#1.1: To inspect firewall with line numbers, enter:

# iptables -n -L -v --line-numbers
Sample outputs:
Chain INPUT (policy DROP)
num  target     prot opt source               destination
1    DROP       all  --  0.0.0.0/0            0.0.0.0/0           state INVALID
2    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           state RELATED,ESTABLISHED
3    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0
4    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0
Chain FORWARD (policy DROP)
num  target     prot opt source               destination
1    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0
2    DROP       all  --  0.0.0.0/0            0.0.0.0/0           state INVALID
3    TCPMSS     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp flags:0x06/0x02 TCPMSS clamp to PMTU
4    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           state RELATED,ESTABLISHED
5    wanin      all  --  0.0.0.0/0            0.0.0.0/0
6    wanout     all  --  0.0.0.0/0            0.0.0.0/0
7    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0
Chain OUTPUT (policy ACCEPT)
num  target     prot opt source               destination
Chain wanin (1 references)
num  target     prot opt source               destination
Chain wanout (1 references)
num  target     prot opt source               destination
You can use line numbers to delete or insert new rules into the firewall.

#1.2: To display INPUT or OUTPUT chain rules, enter:

# iptables -L INPUT -n -v
# iptables -L OUTPUT -n -v --line-numbers

#2: Stop / Start / Restart the Firewall

If you are using CentOS / RHEL / Fedora Linux, enter:
# service iptables stop
# service iptables start
# service iptables restart

You can use the iptables command itself to stop the firewall and delete all rules:
# 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 OUTPUT ACCEPT
# iptables -P FORWARD ACCEPT

Where,
  • -F : Deleting (flushing) all the rules.
  • -X : Delete chain.
  • -t table_name : Select table (called nat or mangle) and delete/flush rules.
  • -P : Set the default policy (such as DROP, REJECT, or ACCEPT).

#3: Delete Firewall Rules

To display line number along with other information for existing rules, enter:
# iptables -L INPUT -n --line-numbers
# iptables -L OUTPUT -n --line-numbers
# iptables -L OUTPUT -n --line-numbers | less
# iptables -L OUTPUT -n --line-numbers | grep 202.54.1.1

You will get the list of IP. Look at the number on the left, then use number to delete it. For example delete line number 4, enter:
# iptables -D INPUT 4
OR find source IP 202.54.1.1 and delete from rule:
# iptables -D INPUT -s 202.54.1.1 -j DROP
Where,
  • -D : Delete one or more rules from the selected chain

#4: Insert Firewall Rules

To insert one or more rules in the selected chain as the given rule number use the following syntax. First find out line numbers, enter:
# iptables -L INPUT -n --line-numbers
Sample outputs:
Chain INPUT (policy DROP)
num  target     prot opt source               destination
1    DROP       all  --  202.54.1.1           0.0.0.0/0
2    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           state NEW,ESTABLISHED 
To insert rule between 1 and 2, enter:
# iptables -I INPUT 2 -s 202.54.1.2 -j DROP
To view updated rules, enter:
# iptables -L INPUT -n --line-numbers
Sample outputs:
Chain INPUT (policy DROP)
num  target     prot opt source               destination
1    DROP       all  --  202.54.1.1           0.0.0.0/0
2    DROP       all  --  202.54.1.2           0.0.0.0/0
3    ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           state NEW,ESTABLISHED

#5: Save Firewall Rules

To save firewall rules under CentOS / RHEL / Fedora Linux, enter:
# service iptables save
In this example, drop an IP and save firewall rules:
# iptables -A INPUT -s 202.5.4.1 -j DROP
# service iptables save

For all other distros use the iptables-save command:
# iptables-save > /root/my.active.firewall.rules
# cat /root/my.active.firewall.rules

#6: Restore Firewall Rules

To restore firewall rules form a file called /root/my.active.firewall.rules, enter:
# iptables-restore < /root/my.active.firewall.rules
To restore firewall rules under CentOS / RHEL / Fedora Linux, enter:
# service iptables restart

#7: Set the Default Firewall Policies

To drop all traffic:
# iptables -P INPUT DROP
# iptables -P OUTPUT DROP
# iptables -P FORWARD DROP
# iptables -L -v -n
#### you will not able to connect anywhere as all traffic is dropped ###
# ping cyberciti.biz
# wget http://www.kernel.org/pub/linux/kernel/v3.0/testing/linux-3.2-rc5.tar.bz2

#7.1: Only Block Incoming Traffic

To drop all incoming / forwarded packets, but allow outgoing traffic, enter:
# iptables -P INPUT DROP
# iptables -P FORWARD DROP
# iptables -P OUTPUT ACCEPT
# iptables -A INPUT -m state --state NEW,ESTABLISHED -j ACCEPT
# iptables -L -v -n
### *** now ping and wget should work *** ###
# ping cyberciti.biz
# wget http://www.kernel.org/pub/linux/kernel/v3.0/testing/linux-3.2-rc5.tar.bz2

#8:Drop Private Network Address On Public Interface

IP spoofing is nothing but to stop the following IPv4 address ranges for private networks on your public interfaces. Packets with non-routable source addresses should be rejected using the following syntax:
# iptables -A INPUT -i eth1 -s 192.168.0.0/24 -j DROP
# iptables -A INPUT -i eth1 -s 10.0.0.0/8 -j DROP

#8.1: IPv4 Address Ranges For Private Networks (make sure you block them on public interface)

  • 10.0.0.0/8 -j (A)
  • 172.16.0.0/12 (B)
  • 192.168.0.0/16 (C)
  • 224.0.0.0/4 (MULTICAST D)
  • 240.0.0.0/5 (E)
  • 127.0.0.0/8 (LOOPBACK)

#9: Blocking an IP Address (BLOCK IP)

To block an attackers ip address called 1.2.3.4, enter:
# iptables -A INPUT -s 1.2.3.4 -j DROP
# iptables -A INPUT -s 192.168.0.0/24 -j DROP

#10: Block Incoming Port Requests (BLOCK PORT)

To block all service requests on port 80, enter:
# iptables -A INPUT -p tcp --dport 80 -j DROP
# iptables -A INPUT -i eth1 -p tcp --dport 80 -j DROP
To block port 80 only for an ip address 1.2.3.4, enter:
# iptables -A INPUT -p tcp -s 1.2.3.4 --dport 80 -j DROP
# iptables -A INPUT -i eth1 -p tcp -s 192.168.1.0/24 --dport 80 -j DROP

#11: Block Outgoing IP Address

To block outgoing traffic to a particular host or domain such as cyberciti.biz, enter:
# host -t a cyberciti.biz
Sample outputs:
cyberciti.biz has address 75.126.153.206
Note down its ip address and type the following to block all outgoing traffic to 75.126.153.206:
# iptables -A OUTPUT -d 75.126.153.206 -j DROP
You can use a subnet as follows:
# iptables -A OUTPUT -d 192.168.1.0/24 -j DROP
# iptables -A OUTPUT -o eth1 -d 192.168.1.0/24 -j DROP

#11.1: Example - Block Facebook.com Domain

First, find out all ip address of facebook.com, enter:
# host -t a www.facebook.com
Sample outputs:
www.facebook.com has address 69.171.228.40
Find CIDR for 69.171.228.40, enter:
# whois 69.171.228.40 | grep CIDR
Sample outputs:
CIDR:           69.171.224.0/19
To prevent outgoing access to www.facebook.com, enter:
# iptables -A OUTPUT -p tcp -d 69.171.224.0/19 -j DROP
You can also use domain name, enter:
# iptables -A OUTPUT -p tcp -d www.facebook.com -j DROP
# iptables -A OUTPUT -p tcp -d facebook.com -j DROP
From the iptables man page:
... specifying any name to be resolved with a remote query such as DNS (e.g., facebook.com is a really bad idea), a network IP address (with /mask), or a plain IP address ...

#12: Log and Drop Packets

Type the following to log and block IP spoofing on public interface called eth1
# iptables -A INPUT -i eth1 -s 10.0.0.0/8 -j LOG --log-prefix "IP_SPOOF A: "
# iptables -A INPUT -i eth1 -s 10.0.0.0/8 -j DROP

By default everything is logged to /var/log/messages file.
# tail -f /var/log/messages
# grep --color 'IP SPOOF' /var/log/messages

#13: Log and Drop Packets with Limited Number of Log Entries

The -m limit module can limit the number of log entries created per time. This is used to prevent flooding your log file. To log and drop spoofing per 5 minutes, in bursts of at most 7 entries .
# iptables -A INPUT -i eth1 -s 10.0.0.0/8 -m limit --limit 5/m --limit-burst 7 -j LOG --log-prefix "IP_SPOOF A: "
# iptables -A INPUT -i eth1 -s 10.0.0.0/8 -j DROP

#14: Drop or Accept Traffic From Mac Address

Use the following syntax:
# iptables -A INPUT -m mac --mac-source 00:0F:EA:91:04:08 -j DROP
## *only accept traffic for TCP port # 8080 from mac 00:0F:EA:91:04:07 * ##
# iptables -A INPUT -p tcp --destination-port 22 -m mac --mac-source 00:0F:EA:91:04:07 -j ACCEPT

#15: Block or Allow ICMP Ping Request

Type the following command to block ICMP ping requests:
# iptables -A INPUT -p icmp --icmp-type echo-request -j DROP
# iptables -A INPUT -i eth1 -p icmp --icmp-type echo-request -j DROP

Ping responses can also be limited to certain networks or hosts:
# iptables -A INPUT -s 192.168.1.0/24 -p icmp --icmp-type echo-request -j ACCEPT
The following only accepts limited type of ICMP requests:
### ** assumed that default INPUT policy set to DROP ** #############
iptables -A INPUT -p icmp --icmp-type echo-reply -j ACCEPT
iptables -A INPUT -p icmp --icmp-type destination-unreachable -j ACCEPT
iptables -A INPUT -p icmp --icmp-type time-exceeded -j ACCEPT
## ** all our server to respond to pings ** ##
iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT

#16: Open Range of Ports

Use the following syntax to open a range of ports:
iptables -A INPUT -m state --state NEW -m tcp -p tcp --dport 7000:7010 -j ACCEPT

#17: Open Range of IP Addresses

Use the following syntax to open a range of IP address:
## only accept connection to tcp port 80 (Apache) if ip is between 192.168.1.100 and 192.168.1.200 ##
iptables -A INPUT -p tcp --destination-port 80 -m iprange --src-range 192.168.1.100-192.168.1.200 -j ACCEPT
## nat example ##
iptables -t nat -A POSTROUTING -j SNAT --to-source 192.168.1.20-192.168.1.25

#17: Established Connections and Restaring The Firewall

When you restart the iptables service it will drop established connections as it unload modules from the system under RHEL / Fedora / CentOS Linux. Edit, /etc/sysconfig/iptables-config and set IPTABLES_MODULES_UNLOAD as follows:
IPTABLES_MODULES_UNLOAD = no

#18: Help Iptables Flooding My Server Screen

Use the crit log level to send messages to a log file instead of console:
iptables -A INPUT -s 1.2.3.4 -p tcp --destination-port 80 -j LOG --log-level crit

#19: Block or Open Common Ports

The following shows syntax for opening and closing common TCP and UDP ports:
 
Replace ACCEPT with DROP to block port:
## open port ssh tcp port 22 ##
iptables -A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 22 -j ACCEPT
 
## open cups (printing service) udp/tcp port 631 for LAN users ##
iptables -A INPUT -s 192.168.1.0/24 -p udp -m udp --dport 631 -j ACCEPT
iptables -A INPUT -s 192.168.1.0/24 -p tcp -m tcp --dport 631 -j ACCEPT
 
## allow time sync via NTP for lan users (open udp port 123) ##
iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p udp --dport 123 -j ACCEPT
 
## open tcp port 25 (smtp) for all ##
iptables -A INPUT -m state --state NEW -p tcp --dport 25 -j ACCEPT
 
# open dns server ports for all ##
iptables -A INPUT -m state --state NEW -p udp --dport 53 -j ACCEPT
iptables -A INPUT -m state --state NEW -p tcp --dport 53 -j ACCEPT
 
## open http/https (Apache) server port to all ##
iptables -A INPUT -m state --state NEW -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -m state --state NEW -p tcp --dport 443 -j ACCEPT
 
## open tcp port 110 (pop3) for all ##
iptables -A INPUT -m state --state NEW -p tcp --dport 110 -j ACCEPT
 
## open tcp port 143 (imap) for all ##
iptables -A INPUT -m state --state NEW -p tcp --dport 143 -j ACCEPT
 
## open access to Samba file server for lan users only ##
iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 137 -j ACCEPT
iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 138 -j ACCEPT
iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 139 -j ACCEPT
iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 445 -j ACCEPT
 
## open access to proxy server for lan users only ##
iptables -A INPUT -s 192.168.1.0/24 -m state --state NEW -p tcp --dport 3128 -j ACCEPT
 
## open access to mysql server for lan users only ##
iptables -I INPUT -p tcp --dport 3306 -j ACCEPT
 

#20: Restrict the Number of Parallel Connections To a Server Per Client IP

You can use connlimit module to put such restrictions. To allow 3 ssh connections per client host, enter:
# iptables -A INPUT -p tcp --syn --dport 22 -m connlimit --connlimit-above 3 -j REJECT
Set HTTP requests to 20:
# iptables -p tcp --syn --dport 80 -m connlimit --connlimit-above 20 --connlimit-mask 24 -j DROP
Where,
  1. --connlimit-above 3 : Match if the number of existing connections is above 3.
  2. --connlimit-mask 24 : Group hosts using the prefix length. For IPv4, this must be a number between (including) 0 and 32.

#21: HowTO: Use iptables Like a Pro

For more information about iptables, please see the manual page by typing man iptables from the command line:
$ man iptables
You can see the help using the following syntax too:
# iptables -h
To see help with specific commands and targets, enter:
# iptables -j DROP -h

#21.1: Testing Your Firewall

Find out if ports are open or not, enter:
# netstat -tulpn
Find out if tcp port 80 open or not, enter:
# netstat -tulpn | grep :80
If port 80 is not open, start the Apache, enter:
# service httpd start
Make sure iptables allowing access to the port 80:
# iptables -L INPUT -v -n | grep 80
Otherwise open port 80 using the iptables for all users:
# iptables -A INPUT -m state --state NEW -p tcp --dport 80 -j ACCEPT
# service iptables save

Use the telnet command to see if firewall allows to connect to port 80:
$ telnet www.cyberciti.biz 80
Sample outputs:
Trying 75.126.153.206...
Connected to www.cyberciti.biz.
Escape character is '^]'.
^]
telnet> quit
Connection closed.
You can use nmap to probe your own server using the following syntax:
$ nmap -sS -p 80 www.cyberciti.biz
Sample outputs:
Starting Nmap 5.00 ( http://nmap.org ) at 2011-12-13 13:19 IST
Interesting ports on www.cyberciti.biz (75.126.153.206):
PORT   STATE SERVICE
80/tcp open  http
Nmap done: 1 IP address (1 host up) scanned in 1.00 seconds
I also recommend you install and use sniffer such as tcpdupm and ngrep to test your firewall settings.

Conclusion:

This post only list basic rules for new Linux users. You can create and build more complex rules. This requires good understanding of TCP/IP, Linux kernel tuning via sysctl.conf, and good knowledge of your own setup. Stay tuned for next topics:
  • Stateful packet inspection.
  • Using connection tracking helpers.
  • Network address translation.
  • Layer 2 filtering.
  • Firewall testing tools.
  • Dealing with VPNs, DNS, Web, Proxy, and other protocols.

Featured Articles:



#!/bin/bash
# Clear any previous rules.
/sbin/iptables -F
# Default drop policy.
/sbin/iptables -P INPUT DROP
/sbin/iptables -P OUTPUT ACCEPT
# Allow anything over loopback and vpn.
/sbin/iptables -A INPUT -i lo -s 127.0.0.1 -d 127.0.0.1 -j ACCEPT
/sbin/iptables -A OUTPUT -o lo -s 127.0.0.1 -d 127.0.0.1 -j ACCEPT
/sbin/iptables -A INPUT -i tun0 -j ACCEPT
/sbin/iptables -A OUTPUT -o tun0 -j ACCEPT
/sbin/iptables -A INPUT -p esp -j ACCEPT
/sbin/iptables -A OUTPUT -p esp -j ACCEPT
# Drop any tcp packet that does not start a connection with a syn flag.
/sbin/iptables -A INPUT -p tcp ! --syn -m state --state NEW -j DROP
# Drop any invalid packet that could not be identified.
/sbin/iptables -A INPUT -m state --state INVALID -j DROP
# Drop invalid packets.
/sbin/iptables -A INPUT -p tcp -m tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -j DROP
/sbin/iptables -A INPUT -p tcp -m tcp --tcp-flags SYN,FIN SYN,FIN              -j DROP
/sbin/iptables -A INPUT -p tcp -m tcp --tcp-flags SYN,RST SYN,RST              -j DROP
/sbin/iptables -A INPUT -p tcp -m tcp --tcp-flags FIN,RST FIN,RST              -j DROP
/sbin/iptables -A INPUT -p tcp -m tcp --tcp-flags ACK,FIN FIN                  -j DROP
/sbin/iptables -A INPUT -p tcp -m tcp --tcp-flags ACK,URG URG                  -j DROP
# Reject broadcasts to 224.0.0.1
/sbin/iptables -A INPUT -s 224.0.0.0/4 -j DROP
/sbin/iptables -A INPUT -d 224.0.0.0/4 -j DROP
/sbin/iptables -A INPUT -s 240.0.0.0/5 -j DROP
# Blocked ports
/sbin/iptables -A INPUT -p tcp -m state --state NEW,ESTABLISHED,RELATED --dport 8010 -j DROP
# Allow TCP/UDP connections out. Keep state so conns out are allowed back in.
/sbin/iptables -A INPUT  -p tcp -m state --state ESTABLISHED     -j ACCEPT
/sbin/iptables -A OUTPUT -p tcp -m state --state NEW,ESTABLISHED -j ACCEPT
/sbin/iptables -A INPUT  -p udp -m state --state ESTABLISHED     -j ACCEPT
/sbin/iptables -A OUTPUT -p udp -m state --state NEW,ESTABLISHED -j ACCEPT
# Allow only ICMP echo requests (ping) in. Limit rate in. Uncomment if needed.
/sbin/iptables -A INPUT  -p icmp -m state --state NEW,ESTABLISHED --icmp-type echo-reply -j ACCEPT
/sbin/iptables -A OUTPUT -p icmp -m state --state NEW,ESTABLISHED --icmp-type echo-request -j ACCEPT
# or block ICMP allow only ping out
/sbin/iptables -A INPUT  -p icmp -m state --state NEW -j DROP
/sbin/iptables -A INPUT  -p icmp -m state --state ESTABLISHED -j ACCEPT
/sbin/iptables -A OUTPUT -p icmp -m state --state NEW,ESTABLISHED -j ACCEPT
# Allow ssh connections in.
#/sbin/iptables -A INPUT -p tcp -s 1.2.3.4 -m tcp --dport 22 -m state --state NEW,ESTABLISHED,RELATED -m limit --limit 2/m -j ACCEPT
# Drop everything that did not match above or drop and log it.
#/sbin/iptables -A INPUT   -j LOG --log-level 4 --log-prefix "IPTABLES_INPUT: "
/sbin/iptables -A INPUT   -j DROP
#/sbin/iptables -A FORWARD -j LOG --log-level 4 --log-prefix "IPTABLES_FORWARD: "
/sbin/iptables -A FORWARD -j DROP
#/sbin/iptables -A OUTPUT  -j LOG --log-level 4 --log-prefix "IPTABLES_OUTPUT: "
/sbin/iptables -A OUTPUT  -j ACCEPT
iptables-save > /dev/null 2>&1



REFERENCES
http://www.cyberciti.biz/tips/linux-iptables-examples.html