Articles taggués ‘firewall’

Linux: 20 Iptables Examples For New SysAdmins

28/07/2017 Comments off

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 lists most simple 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 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 the 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 that use the netfliter.
  • It 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  --  *      *             state INVALID
  394 43586 ACCEPT     all  --  *      *             state RELATED,ESTABLISHED
   93 17292 ACCEPT     all  --  br0    *  
    1   142 ACCEPT     all  --  lo     *  

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 DROP       all  --  *      *             state INVALID
    0     0 TCPMSS     tcp  --  *      *             tcp flags:0x06/0x02 TCPMSS clamp to PMTU
    0     0 ACCEPT     all  --  *      *             state RELATED,ESTABLISHED
    0     0 wanin      all  --  vlan2  *  
    0     0 wanout     all  --  *      vlan2  
    0     0 ACCEPT     all  --  br0    *  

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


  • -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  --             state INVALID
2    ACCEPT     all  --             state RELATED,ESTABLISHED
3    ACCEPT     all  --  
4    ACCEPT     all  --  

Chain FORWARD (policy DROP)
num  target     prot opt source               destination
1    ACCEPT     all  --  
2    DROP       all  --             state INVALID
3    TCPMSS     tcp  --             tcp flags:0x06/0x02 TCPMSS clamp to PMTU
4    ACCEPT     all  --             state RELATED,ESTABLISHED
5    wanin      all  --  
6    wanout     all  --  
7    ACCEPT     all  --  

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


  • -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

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 and delete from rule:
# iptables -D INPUT -s -j DROP

  • -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  -- 
2    ACCEPT     all  --             state NEW,ESTABLISHED 

To insert rule between 1 and 2, enter:
# iptables -I INPUT 2 -s -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  -- 
2    DROP       all  -- 
3    ACCEPT     all  --             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 -j DROP
# service iptables save

For all other distros use the iptables-save command:
# iptables-save > /root/
# cat /root/

#6: Restore Firewall Rules

To restore firewall rules form a file called /root/, enter:
# iptables-restore < /root/
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
# wget

#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
# wget

#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 -j DROP
# iptables -A INPUT -i eth1 -s -j DROP

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

  • -j (A)
  • (B)
  • (C)
  • (E)

#9: Blocking an IP Address (BLOCK IP)

To block an attackers ip address called, enter:
# iptables -A INPUT -s -j DROP
# iptables -A INPUT -s -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, enter:
# iptables -A INPUT -p tcp -s --dport 80 -j DROP
# iptables -A INPUT -i eth1 -p tcp -s --dport 80 -j DROP

#11: Block Outgoing IP Address

To block outgoing traffic to a particular host or domain such as, enter:
# host -t a
Sample outputs: has address

Note down its ip address and type the following to block all outgoing traffic to
# iptables -A OUTPUT -d -j DROP
You can use a subnet as follows:
# iptables -A OUTPUT -d -j DROP
# iptables -A OUTPUT -o eth1 -d -j DROP

#11.1: Example – Block Domain

First, find out all ip address of, enter:
# host -t a
Sample outputs: has address

Find CIDR for, enter:
# whois | grep CIDR
Sample outputs:


To prevent outgoing access to, enter:
# iptables -A OUTPUT -p tcp -d -j DROP
You can also use domain name, enter:
# iptables -A OUTPUT -p tcp -d -j DROP
# iptables -A OUTPUT -p tcp -d -j DROP

From the iptables man page:

… specifying any name to be resolved with a remote query such as DNS (e.g., 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 -j LOG --log-prefix "IP_SPOOF A: "
# iptables -A INPUT -i eth1 -s -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 -m limit --limit 5/m --limit-burst 7 -j LOG --log-prefix "IP_SPOOF A: "
# iptables -A INPUT -i eth1 -s -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 -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 and ##
iptables -A INPUT -p tcp --destination-port 80 -m iprange --src-range -j ACCEPT

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

#18: 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:


#19: 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 -p tcp --destination-port 80 -j LOG --log-level crit

#20: 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 -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 -p udp -m udp --dport 631 -j ACCEPT
iptables -A INPUT -s -p tcp -m tcp --dport 631 -j ACCEPT
## allow time sync via NTP for lan users (open udp port 123) ##
iptables -A INPUT -s -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 -m state --state NEW -p tcp --dport 137 -j ACCEPT
iptables -A INPUT -s -m state --state NEW -p tcp --dport 138 -j ACCEPT
iptables -A INPUT -s -m state --state NEW -p tcp --dport 139 -j ACCEPT
iptables -A INPUT -s -m state --state NEW -p tcp --dport 445 -j ACCEPT
## open access to proxy server for lan users only ##
iptables -A INPUT -s -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

#21: 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

  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.

#22: 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

#22.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 80
Sample outputs:

Connected to
Escape character is '^]'.

telnet> quit
Connection closed.

You can use nmap to probe your own server using the following syntax:
$ nmap -sS -p 80
Sample outputs:

Starting Nmap 5.00 ( ) at 2011-12-13 13:19 IST
Interesting ports on (
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.


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.

Iptables Allow MYSQL server incoming request on port 3306

24/03/2017 Comments off

MySQL database is a popular for web applications and acts as the database component of the LAMP, MAMP, and WAMP platforms. Its popularity as a web application is closely tied to the popularity of PHP, which is often combined with MySQL. MySQL is open source database server and by default it listen on TCP port 3306. In this tutorial you will learn how to open TCP port # 3306 using iptables command line tool on Linux operating system.

Task: Open port 3306

In most cases following simple rule opens TCP port 3306:

iptables -A INPUT -i eth0 -p tcp -m tcp --dport 3306 -j ACCEPT

The following iptable rules allows incoming client request (open port 3306) for server IP address Add rules to your iptables shell script:

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

However in real life you do not wish give access to everyone. For example in a web hosting company, you need to gives access to MySQL database server from web server only. Following example allows MySQL database server access ( from Apache web server ( only:

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

Please note if you follow above setup, then you need tell all your hosting customer to use as MySQL host in PHP/Perl code. A better approach is to create following entry in /etc/hosts file or use fully qualified domain name (create dns entry) which points to ip: mysql

In shot MySQL database connection code from PHP hosted on our separate webserver would look like as follows:

// ** MySQL settings ** //
define('DB_NAME', 'YOUR-DATABASE-NAME');     // The name of the database
define('DB_USER', 'YOUR-USER-NAME');     // Your MySQL username
define('DB_PASSWORD', 'YOUR-PASSWORD''); // ...and password
define('DB_HOST', 'mysql');       // mysql i.e.
// ** rest of PHP code ** //

Lire la suite…

Make the configuration of iptables persistent (Debian)

22/03/2017 Comments off


To make the configuration of iptables persistent on a Debian-based system


The iptables and ip6tables commands can be used to instruct Linux to perform functions such as firewalling and network address translation, however the configuration that they create is non-persistent so is lost whenever the machine is rebooted. For most practical applications this is not the desired behaviour, so some means is needed to reinstate the configuration at boot time.

For security, the iptables configuration should be applied at an early stage of the bootstrap process: preferably before any network interfaces are brought up, and certainly before any network services are started or routing is enabled. If this is not done then there will be a window of vulnerability during which the machine is remotely accessible but not firewalled.


Suppose you have a machine that you wish to protect using a firewall. You have written iptables and ip6tables rulesets, and wish to install them so that they will remain active if the machine is rebooted.

Lire la suite…

GeoIP pour iptables

18/03/2017 Comments off


Marre des pays exotiques qui essaient de s’introduire sur le serveur et pourrissent vos logs et font bosser fail2ban ?

Une solution pour bloquer les pays avec lesquels vous n’avez pas de relations. Pour Debian mais sûrement adaptable à d’autres distributions.

# Install GeoIP pour iptables

apt-get install dkms xtables-addons-dkms xtables-addons-common xtables-addons-dkms geoip-database libgeoip1 libtext-csv-xs-perl unzip

# On vérifie que c’est ok

dkms status xtables-addons

# on crée le repertoire

mkdir /usr/share/xt_geoip

# on se déplace dedans

cd /usr/share/xt_geoip/

# on télécharge le fichier


# on le décompresse

tar xvf geoip-dl-build.tar.gz

# on l’exécute


# si cela donne un message d’erreur, on fait ceci

/usr/bin/perl -MCPAN -e'install Text::CSV_XS'

# on exécute l’autre fichier

./xt_geoip_build -D . *.csv

# on efface les fichiers inutiles

rm -rf geoip-dl-build.tar.gz

# on teste iptables en bloquant la Chine et la Russie

iptables -A INPUT -m geoip --src-cc CN,RU -j DROP

# on vérifie

iptables -L -v

# ce qui donnera cette ligne indiquant que les pays seront bloqués

DROP all -- anywhere anywhere -m geoip --source-country CN,RU

pour interdire le port 22 à ces pays

iptables -A INPUT -p tcp --dport 22 -m geoip --src-cc CN,RU -j DROP

Block entire countries on Ubuntu server with Xtables and GeoIP

18/03/2017 Comments off


Anyone who has administered even a moderately high traffic server will have noticed that certain unwelcome traffic such as port scans and probes tend to come from IP addresses belonging to a certain group of countries. If your application or service does not cater to users in these countries, it might be a safe bet to block these countries off entirely.

This is especially true for email servers. The average email server, based on anecdotal evidence of servers for around 20 domains, rejects about 30% of incoming email every day as spam. Some servers on some days reject up to as much as 97% of incoming email as spam. Most of these originate in a certain subset of countries. That is a lot of wasted CPU cycles being expended on scanning these undesired emails for spam and viruses. Although tools such as amavisd and spamassasin do a good job of keeping the vast majority of spam out of users’ inboxes, when the rare well crafted and targeted phishing email does get through, it wrecks havoc in the enterprise.

Lire la suite…

How to save rules of the iptables?

18/03/2017 Comments off

Saving iptables rules for reboot

On a server, iptables rules don’t reload automatically at reboot. You need to reload the rules using ax executable shell scripture a dedicated utility that will load them at the same time as the program itself, i.e. with the kernel.

Depending of the version of Linux you use, you can select different methods:

sudo su
iptables-save > /etc/iptables.rules

In /etc/network/if-pre-up.d/iptables, put:

iptables-restore < /etc/iptables.rules
exit 0

After, in /etc/network/if-post-down.d/iptables, put:

iptables-save -c > /etc/iptables.rules
if [ -f /etc/iptables.rules ];
       then iptables-restore < /etc/iptables.rules
exit 0

After, give permission to the scripts:

sudo chmod +x /etc/network/if-post-down.d/iptables sudo chmod +x /etc/network/if-pre-up.d/iptables

Another scenario is to is to install iptables-persistent:

sudo apt-get install iptables-persistent

After it’s installed, you can save/reload iptables rules anytime:

    sudo /etc/init.d/iptables-persistent save 
    sudo /etc/init.d/iptables-persistent reload

Or if you use Ubuntu server 16.04, things are simpler:

The installation as described above works without a problem, but the two commands for saving and reloading above do not seem to work with a 16.04 server. The following commands work with that version:

    sudo netfilter-persistent save
    sudo netfilter-persistent reload

Easy Ubuntu 16.04 Server Firewall

23/02/2017 Comments off

If you read our previous article Easy Ubuntu Server Firewall, then you may have noted that on Ubuntu 16.04 the described method no longer works. This is due to systemd. In the article below we will walk through creating a persistent IPTables based firewall on Ubuntu 16.04 LTS. First we need to install some required software packages. As seen in the command below, install iptables-persistent. Next we will make netfilter-persistent run at boot. This is the most important step as it will ensure your rules are reloaded at boot time.

# Install IPTables Persistent Package
apt-get install -y iptables-persistent
# Add netfilter-persistent Startup
invoke-rc.d netfilter-persistent save
# Stop netfilter-persistent Service
service netfilter-persistent stop

Once the packages above are installed and the service is stopped, you will have a new directory at /etc/iptables/. This directory holds the IPTables filter rules that will be reloaded at boot time. These files are named rules.v4 and rules.v6 respectively. IPV4 rules are loaded into rules.v4 and IPV6 rules are loaded into rules.v6. For the purpose of this article we will focus on IPV4 rules. Next we will want to copy the rules below into our rules.v4 file. Of course the rules will need to be modified to fit your environment.

# Generated by iptables-save v1.3.3 on Wed Apr 9 10:51:08 2008
# Flush out any rules that are already in there
:INPUT ACCEPT [146:11332]
:OUTPUT ACCEPT [104:9831]
# Allow internal loopback connections
-A INPUT -i lo -j ACCEPT
# Allow pinging
-A INPUT -p icmp -m icmp --icmp-type 8 -j ACCEPT
# Allow any outbound data, and any inbound data related to a connection that is already in use
# Allow SCP/SSH Access from Green & Blue Subnet
-A INPUT -s -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -s -p tcp -m tcp --dport 22 -j ACCEPT
# Allow HTTP Access from Red Subnet/Internet
-A INPUT -p tcp -m state --state NEW,ESTABLISHED --dport 80 -j ACCEPT
# Allow HTTPS Access from Red Subnet/Internet
-A INPUT -p tcp -m state --state NEW,ESTABLISHED --dport 443 -j ACCEPT
# Allow MySQL Access from Red Subnet/Internet
-A INPUT -p tcp -m state --state NEW,ESTABLISHED --dport 3306 -j ACCEPT
# Allow FTP Access from Red Subnet/Internet
-A INPUT -p tcp -m state --state NEW,ESTABLISHED --dport 21 -j ACCEPT
-A INPUT -p tcp -m state --state NEW,ESTABLISHED --dport 58000:58010 -j ACCEPT
# Drop everything that hasn't been picked up by one of the rules above
# Completed on Wed Apr 9 10:51:08 2008

Lastly, in order for our new rules to take affect, we simply need to start the netfilter-persistent service as seen below. That’s it, you now have a fully functional IPTables based firewall.

# Start netfilter-persistent Service
service netfilter-persistent start

# Check if IPTables were applied
iptables -L

A Deep Dive into Iptables and Netfilter Architecture

09/06/2016 Comments off


Firewalls are an important tool that can be configured to protect your servers and infrastructure. In the Linux ecosystem, iptables is a widely used firewall tool that interfaces with the kernel’s netfilter packet filtering framework. For users and administrators who don’t understand the architecture of these systems, creating reliable firewall policies can be daunting, not only due to challenging syntax, but also because of number of interrelated parts present in the framework.

In this guide, we will dive into the iptables architecture with the aim of making it more comprehensible for users who need to build their own firewall policies. We will discuss how iptables interacts with netfilter and how the various components fit together to provide a comprehensive filtering and mangling system.


What Are IPTables and Netfilter?

The basic firewall software most commonly used in Linux is called iptables. The iptables firewall works by interacting with the packet filtering hooks in the Linux kernel’s networking stack. These kernel hooks are known as the netfilter framework.

Every packet that enters networking system (incoming or outgoing) will trigger these hooks as it progresses through the stack, allowing programs that register with these hooks to interact with the traffic at key points. The kernel modules associated with iptables register at these hooks in order to ensure that the traffic conforms to the conditions laid out by the firewall rules.


Netfilter Hooks

There are five netfilter hooks that programs can register with. As packets progress through the stack, they will trigger the kernel modules that have registered with these hooks. The hooks that a packet will trigger depends on whether the packet is incoming or outgoing, the packet’s destination, and whether the packet was dropped or rejected at a previous point.

The following hooks represent various well-defined points in the networking stack:

  • NF_IP_PRE_ROUTING: This hook will be triggered by any incoming traffic very soon after entering the network stack. This hook is processed before any routing decisions have been made regarding where to send the packet.
  • NF_IP_LOCAL_IN: This hook is triggered after an incoming packet has been routed if the packet is destined for the local system.
  • NF_IP_FORWARD: This hook is triggered after an incoming packet has been routed if the packet is to be forwarded to another host.
  • NF_IP_LOCAL_OUT: This hook is triggered by any locally created outbound traffic as soon it hits the network stack.
  • NF_IP_POST_ROUTING: This hook is triggered by any outgoing or forwarded traffic after routing has taken place and just before being put out on the wire.

Kernel modules that wish to register at these hooks must provide a priority number to help determine the order in which they will be called when the hook is triggered. This provides the means for multiple modules (or multiple instances of the same module) to be connected to each of the hooks with deterministic ordering. Each module will be called in turn and will return a decision to the netfilter framework after processing that indicates what should be done with the packet.


IPTables Tables and Chains

The iptables firewall uses tables to organize its rules. These tables classify rules according to the type of decisions they are used to make. For instance, if a rule deals with network address translation, it will be put into the nat table. If the rule is used to decide whether to allow the packet to continue to its destination, it would probably be added to the filter table.

Within each iptables table, rules are further organized within separate « chains ». While tables are defined by the general aim of the rules they hold, the built-in chains represent the netfilter hooks which trigger them. Chains basically determine when rules will be evaluated.

As you can see, the names of the built-in chains mirror the names of the netfilter hooks they are associated with:

  • PREROUTING: Triggered by the NF_IP_PRE_ROUTING hook.
  • INPUT: Triggered by the NF_IP_LOCAL_IN hook.
  • FORWARD: Triggered by the NF_IP_FORWARD hook.
  • OUTPUT: Triggered by the NF_IP_LOCAL_OUT hook.
  • POSTROUTING: Triggered by the NF_IP_POST_ROUTING hook.

Chains allow the administrator to control where in a packet’s delivery path a rule will be evaluated. Since each table has multiple chains, a table’s influence can be exerted at multiple points in processing. Because certain types of decisions only make sense at certain points in the network stack, every table will not have a chain registered with each kernel hook.

There are only five netfilter kernel hooks, so chains from multiple tables are registered at each of the hooks. For instance, three tables have PREROUTING chains. When these chains register at the associated NF_IP_PRE_ROUTING hook, they specify a priority that dictates what order each table’s PREROUTING chain is called. Each of the rules inside the highest priority PREROUTING chain is evaluated sequentially before moving onto the next PREROUTING chain. We will take a look at the specific order of each chain in a moment.
Lire la suite…

What is a Distributed Firewall?

01/06/2016 Comments off

In the post “What is Network Virtualization?” I described a model where the application’s complete L2-L7 virtual network is decoupled from hardware and moved into a software abstraction layer for the express purpose of automation and business agility. In this post I’ll focus on network security, and describe an imminent firewall form factor enabled by Network Virtualization — the Distributed Firewall.


If InfoSec ruled the world … well, OK, maybe not the world … if InfoSec ruled the data center network design, and if money was no object, we would probably have something like this. Every server in the data center directly connected to its own port on one massive firewall. Every packet sent from every server would be inspected against a stateful security policy before going anywhere. And every packet received by every server would pass one final policy check before hitting the server’s NIC receive buffer. The firewall wouldn’t care about the IP address of the servers, for the simple reason that it’s directly connected to every server. E.g. “The server on this port can talk to the server on that port, on TCP port X”. And if that wasn’t good enough, the firewall knows everything about the servers connected to it, and can create rules around a rich set of semantics. All of this with no performance penalty. That would be awesome, right?

Let’s pretend money was not the issue. How would you design this massive omnipresent data center firewall? I can think of three ways off hand.

  1. You design a monstrous power sucking stateful firewall chassis with thousands of line-rate ports. At this point it’s time to route a ghastly mess of cables from every server to this centralized mega firewall core chassis – but that’s somebody else’s problem. Oh, and don’t forget you’ll need two of those bad boys for “redundancy”. Your monster firewall is pretty freaking awesome at security, but only so-so at basic L2 and L3 networking. But so what — the network team can learn to like it or find a new job. And if you run out of ports … no worries; just wait another few years for a bigger chassis and do the rip/replace routine.
  2. You design a line rate stateful firewall ToR switch. Rip out the network team’s favorite ToR and put this one in its place. Tell them to stop throwing a fit and just deal with it. You’ll have hundreds of these ToR firewalls to manage and configure consistently. No problem … just let the network team re-apply for their jobs as firewall engineers.

Go ahead and pinch yourself now. This is nothing but a fantasy nightmare.

The interests of security often poorly translate into networking. Comprehensive security ~= Compromisednetworking.

What about design #3? More on that in a minute. (Hint: title of the post)

In the real world, rest assured we do have firewalls to provide some security. But this security is not ubiquitous, nor is it assured. Instead, we have firewalls (physical or virtual) hanging off the network somewhere catching steered packets – and we can only hope the network was configured correctly to steer the right traffic to the right policy.

In this post we’ll briefly review the physical and virtual firewall, followed by a discussion on the Distributed Firewall.

Lire la suite…

Categories: Logiciel, Réseau Tags:

Tutorial: Using VMWare ESXi and PFsense as a network firewall/router

12/05/2016 Comments off

vmware esxi

Using VMWare ESXi and PFsense as a network firewall/router

In most networks, you will have dedicated hardware to function as your “edge” (firewall/router). This is typically for the best, but there are always cases where you can’t put out that dedicated hardware. Sometimes it’s for cost reasons and sometimes it’s for complexity. In my particular case, I was installing an ESXi server in a datacenter and only had 2 amps of power to work with, of which my server took up ~1.8amps at peak load. So cost came into play and we simply couldn’t afford to put in dedicated hardware that could push enough bits. In such cases, it is possible the setup ESXi on the network edge, in a reasonably secure fashion, with PFSense acting as a firewall.

vmware_vsphereThe most important requirement to this project is that your VMWare ESXi server has at least two network ports on it. One will be the WAN port, one will be the LAN port. Also throughout this tutorial I will use PFSense as my firewall/router OS of choice, however it is just an example that can be easily swapped out with any other virtualized firewall product. Some options include Palo Alto Networks, Fortinet, and even generic *NIX operating systems with the right forwarding/firewall setup.

Section 1 – VMWare Setup

Step 1 – Install & Connect to ESXi

  • You should already have ESXi setup and connected via the VSphere client on Windows.
  • It’s recommended that you static the IP address of the VMWare Management interface, if you’ve not done so already.
  • Go to Configuration > Networking
  • Rename the vSwitch interface you’re using to “LAN”
Step 2 – Add new interface
You want “Virtual Machine” type
Step 3 – Select NIC
You want to select your unused NIC (assuming you only have two)
Step 4 – Name it
This is your “WAN” interface
Step 5 – Confirm you’ve got two networks
You’ll notice that we’ve got two vSwitches now. The “LAN” switch has the Management network and is connected currently. The “WAN” switch has nothing, and the adapter is disconnected.

Section 2 – Virtual Machine Setup

Step 1 – New VM 2015-08-25-18_29_17-New-VM
Step 2 – Typical Setup 2015-08-25-18_29_31-Create-New-Virtual-Machine
Step 3 – Name your VM 2015-08-25-18_29_39-Create-New-Virtual-Machine
Step 4 – Select Datastore 2015-08-25-18_29_46-Create-New-Virtual-Machine
Step 5 – OS Type
If you’re using PFSense, select “Other” and “FreeBSD 64bit”
Step 6 – Two NICs
Unlike most VMs with 1 NIC, add 2 NICs to this VM.
Make sure one adapter is on “WAN” network and one adapter is on “LAN” network.
Step 7 – Allocated HD
PFSense doesn’t need much space, but it should be allocated a 2:1 for swap (e.g. 4096 MB swap file for 2048 MB of RAM), plus some extra space for packages and logs may be useful.
Step 8 – Edit before completion 2015-08-25-18_30_46-Create-New-Virtual-Machine
Step 9 – Final settings
As this is my firewall, I want to make sure it is plenty fast. So I opted for 4 cores and 2 GB RAM. Also attach the CD drive to PFSense installer (be it datastore ISO or real USB/Optical drive).
Step 8 – Verify Network
Hop back to Configuration > Networking and you should see something like this. Note: various VMs are all attached to the LAN vSwitch, however only PFsense VM is attached to both WAN & LAN (just like a real firewall).
Step 9 – VM Startup
Go to Configuration > VM Startup/Shutdown
Click Properties
Step 10 – Set PFSense to first boot order
You may have other VMs that you want to auto-start, but as this is your firewall, it should be the first to start.

Section 3 – PFSense

Step 1 – Install PFSense
Once you’ve installed PFSense, it will automatically configure its local interface to
Step 2 (Optional) – Change local network
You can reconfigure the local network either via web interface (at the aforementioned IP: or command line
Step 3 – Configure WAN
Again, this can be configured either via the web, or command line.
Step 4 – Plug in WAN cable 2015-08-19-13.59.53
Step 5 – Test
If you’ve got the ports configured properly (i.e. WAN hardware is WAN in VMWare and WAN in PFSense), you should be able to connect to the internet.

There are two big questions after building a setup like this, the first is security. Since PFSense is the host to provide an interface on the WAN, it should be the only method of ingress into your network. With no VMware management interface on the WAN, there should be no way for an outside party to access ESXi directly. I’ve used this setup successfully (and safely) before, as have others. However, you always need to balance your particular security concerns with the cost of dedicated devices.

The second question is remote management/maintenance/failure. Managing ESXi remotely is easy, if you setup a VPN on your PFSense VM. Without that (or similar) you will not be able to remotely manage the box (by design). But what happens if there is a failure either in the VMWare hardware or the PFSense virtual machine? That’s the big failing point of this setup – you’re down. If, for whatever reason, PFsense dies – your network is offline and you cannot remotely manage it. If this hardware is installed in a dateacenter, you’d need to either get in there yourself or remote hands reboot. Something to keep in mind when balancing the cost issue. OF course, if it’s local (say you use this at home), then it’s not such a big deal.
IMG_07121I will note that this is the setup I use in my home network, which doubles as my homelab. Having a VM for a firewall gives me a lot of flexibility, like adding an entirely separate vSwitched network for experimental VMs. I can also swap out the firewall VM for another one with next to no downtime. It also allows me to skip one more piece of hardware at home which would add to my otherwise hefty powerbill.


Categories: Réseau, Sécurité, Tutoriel Tags: ,