Puppet Introduction

Puppet Introduction:

Anyone who works on computer systems, finds the regular system administration tasks very time consuming whether it is to install and configure software, taking backups, patching servers, user management etc. There are written procedures, shell scripts, and other ways to document your work and make it more automated and reliable. Puppet as a configuration management tool, helps automating these tasks very efficiently and easily compared to the other ways of automation.


Puppet Concepts:

  • Works on a server client model.
  • Server is called the puppet master and clients are called nodes.
  • Puppet master is a Linux server and the Puppet master application is “Ruby on Rails”. There is no version of puppet master which runs on windows but the nodes can be on Unix (any version), Linux (any version) and Windows
  • The master and nodes communicate with each other via SSL over tcp port 8140
  • Nodes pull configuration from the master (No Push)

Download Source:


 Installation Methods:

  1. Guided installation with web based interface


      2. Automated installation with answer file  http://docs.puppetlabs.com/pe/2016.1/install_automated.html

 Puppet Server Installation Prerequisites:

  • Please ensure your machine has sufficient resources available, till writing this document the recommendations are – you need to have minimum 4GB ram and 2 cores of cpu available for the master and minimum 1GB of ram for the agents.
  • The master and nodes should be able to resolve the hostnames for themselves and other nodes. If you don’t have DNS setup for preparing the lab, please ensure you have put the correct names in the hosts file.
  • The time should be synchronized in the puppet master and agents.

Once the installation tar archive is downloaded, you can place it on your Linux machine where you are willing to install the puppet master through winscp or any other medium of your preference. To start the installation, just execute the “puppet-enterprise-installer” script.

Run the execution script and follow the instructions further:

[root@puppet-server puppet-enterprise-3.3.1-el-6-x86_64]# pwd


[root@puppet-server puppet-enterprise-3.3.1-el-6-x86_64]# ls puppet-enterprise-installer


[root@puppet-server puppet-enterprise-3.3.1-el-6-x86_64]#

The installation script instructs you to open the webpage for your puppet master on port 3000. Open it in your favorite browser and choose the options asked for and begin the installation. The options asked are self-explanatory.

While the installation is running, you can always monitor the progress with

#tail –f /var/log/messages

Puppet agent installation:

Run the below script, which will automatically install the package and configure the service to run on puppet agent.

# curl -k https://puppet-server:8140/packages/current/install.bash | bash

If due to any reasons the curl command fails, then locate the install.bash on the puppet master for the location of the file, scp it to the agent and run it as a script. The agent will be installed.

Linux Interview Questions: FTP & Logs

  • How to create ftp users ?
  • On which port ftp works, configuration file, service name ?
  • How to enable or disable a ftp user ?
  • What is difference between sftp and vsftp ?
  • Where are system logs stored ?
  • Where are sudo and su logs stored ?
  • Where does mail server related logs stored ?
  • Where are the logs stored for system start up ?
  • What is dmesg command ?
  • What is the configuration file to configure log paths
  • Which service needs to be running to configure logging
  • How to set up remote logging ?
  • How log rotation works ?
  • How to monitor the log files ?

Linux Interview Questions: SSH

  • On which port ssh works?
  • Which package needs to be installed for ssh ?
  • What is configuration file for ssh ?
  • How will you Allow/Deny a user to ssh in your server ?
  • What is difference between ssh and telnet ?
  • How to make ssh work on a different port ?
  • How to connect ssh server on the new port ?
  • How to make password less authentication ?
  • What is ssh known_hosts file ?
  • What is SFTP, on which port it works ?
  • How to restrict a user/host for ssh on the server.
  • what is ssh-add command ?
  • what is sshpass command ?

Linux: IPTables


All packets inspected by iptables pass through a sequence of built-in tables (queues) for processing. Each of these queues is dedicated to a particular type of packet activity and is controlled by an associated packet transformation/filtering chain.

There are three tables in total. The first is the mangle table which is responsible for the alteration of quality of service bits in the TCP header. This is hardly used in a home or SOHO environment.

The second table is the filter queue which is responsible for packet filtering. It has three built-in chains in which you can place your firewall policy rules. These are the:

  • Forward chain: Filters packets to servers protected by the firewall.
  • Input chain: Filters packets destined for the firewall.
  • Output chain: Filters packets originating from the firewall.

The third table is the nat queue which is responsible for network address translation. It has two built-in chains; these are:

  • Pre-routing chain: NATs packets when the destination address of the packet needs to be changed.
  • Post-routing chain: NATs packets when the source address of the packet needs to be changed


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.
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  —  *      *             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/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 -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 cyberciti.biz, enter:
# host -t a cyberciti.biz
Sample outputs:

cyberciti.biz 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 Facebook.com Domain

First, find out all ip address of facebook.com, enter:
# host -t a http://www.facebook.com
Sample outputs:

http://www.facebook.com has address

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


To prevent outgoing access to http://www.facebook.com, enter:
# iptables -A OUTPUT -p tcp -d -j DROP
You can also use domain name, enter:
# iptables -A OUTPUT -p tcp -d http://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 -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 http://www.cyberciti.biz 80
Sample outputs:


Connected to http://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 http://www.cyberciti.biz
Sample outputs:

Starting Nmap 5.00 ( http://nmap.org ) at 2011-12-13 13:19 IST

Interesting ports on http://www.cyberciti.biz (


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.

TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

Featured Articles:

{ 72 comments… read them below or add one }

1 Happysysadm December 13, 2011 at 10:10 am

This is a nice breakdown of IPTABLES indeed! Thank you for taking the time for such a comprehensive explaination… I shall bookmark this!


2 logicos December 13, 2011 at 11:56 am

Try ferm, “for Easy Rule Making” .

In file like “ferm.conf” :

chain INPUT proto tcp dport ssh ACCEPT;

And next:
ferm -i ferm.conf

Source: http://ferm.foo-projects.org/


3 LeftMeAlone December 13, 2011 at 1:58 pm

Can any one tell me the difference between the DROP vs REJECT? Which one is recommended for my mail server?


4 Worked December 13, 2011 at 2:59 pm

LeftMeAlone, “drop” does not send anything to the remote socket while “reject” sending the following message to the remote socket: (icmp destination port unrechable).

Make clean… “drop” maybe the service does not exists. “reject” you can not access to the service.


5 Joeman1 December 13, 2011 at 3:07 pm


DROP will silently drop a packet, not notifying the remote host of any problems, just won’t be available. This way, they will no know if the port is active and prohibited or just not used.

REJECT will send an ICMP packet back to the remote host explaining (For the lack of better words) that the host is administratively denied.

The former is preferred as a remote host will not be able to determine if the port is even up.

The latter is not recommended unless software requires the ICMP message for what ever reason. Its not recommended because the remote host will know that the port is in use, but will not be able to connect to it. This way, they can still try to hack the port and get into the system,

Hope this helps!


6 Prabal Mishra December 13, 2011 at 3:36 pm

thanks !

help for Iptables…………..


7 smilyface December 13, 2011 at 4:11 pm



8 noone December 13, 2011 at 7:28 pm

how about you try
host -t a http://www.facebook.com
a few times, just to see how dns round-rbin works…


9 noone December 13, 2011 at 7:37 pm

also, you can try this


# 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 -d -j ACCEPT

/sbin/iptables -A OUTPUT -o lo -s -d -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

/sbin/iptables -A INPUT -s -j DROP

/sbin/iptables -A INPUT -d -j DROP

/sbin/iptables -A INPUT -s -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 -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


10 Coolm@x December 13, 2011 at 7:38 pm

Nice examples, but missing one. Commonly searched rule is one for masquerade.


11 Roy December 13, 2011 at 10:19 pm

This is extremely useful, somekind of magic and quick recipe…
(Of course now i can’t send mail on my remote server (to strict rate limit …))


12 3y3lop December 14, 2011 at 3:00 am

Nice examples & thanks.


13 Jani December 15, 2011 at 9:00 am

.. I’m anxiously awaiting similar translated to ip6tables. 🙂


14 Howard December 22, 2011 at 3:24 am

A most excellent presentation of iptables setup and use. Really Superior work. Thanks kindly.


15 Linus Gasser December 22, 2011 at 7:32 pm

Point 8:

And for the private address ranges to block on public interfaces, you’ll also want to block

169.254/16 – zeroconf


16 Pieter December 23, 2011 at 5:44 pm

Nice post, thanks! In example #19 there is an error in the last line:

## open access to mysql server for lan users only ##

iptables -I INPUT -p tcp –dport 3306 -j ACCEPT

Should probably be:

## open access to mysql server for lan users only ##

iptables -I INPUT -p tcp -s –dport 3306 -j ACCEPT


17 shawn cao February 24, 2012 at 4:33 am

that is right.


18 Alejandro December 23, 2011 at 11:15 pm

Thanks for this post, I hope you don’t mind if I translate this to spanish and post it on my blog, Mentioning the original source, of course.



19 strangr December 24, 2011 at 12:41 am

Simple rules to share your connection to internet (interface IFNAME) with other hosts on your local LAN (NATTED_SUBNET).
In other words how to do NAT and MASQEURADEing.



# 1) load appropriate kernel module

modprobe iptable_nat

# 2) make sure IPv4 forwarding is enabled

echo 1 > /proc/sys/net/ipv4/ip_forward

# 3) the appropriate rules

iptables -A POSTROUTING -t nat -o $IFNAME -s $NATTED_SUBNET -d 0/0 \


iptables -A FORWARD -t filter -o $IFNAME -s $NATTED_SUBNET -m state \


iptables -A FORWARD -t filter -i $IFNAME -d $NATTED_SUBNET -m state \



20 liRONux July 8, 2013 at 12:50 pm

THANKS for this.
How about blocking a website while having those rules?


21 JD December 31, 2011 at 2:27 am

## open access to mysql server for lan users only ##
iptables -I INPUT -p tcp -s –dport 3306 -j ACCEPT

This should be like this:

-s -d -i eth0 -p tcp -m state –state NEW -m tcp –dport 3306 -j ACCEPT

a rule like this should go under RELATED,ESTABLISHED in the INPUT chain


22 JD December 31, 2011 at 2:39 am

For email servers, I have rate limiting rules in place for all service ports.

In the INPUT chain I have the spam firewall ip(s), allowed via port 25.

Then for the email ports, I impose a hit count of 10 in 60 seconds, smart phones, email clients do not poll every second. Anything more than this is dropped and they can continue on a rampage with no affect on the server(s). It took me a while to come up with the rate-limiting chains to work with the email server. Since the Watch Guard XCS devices needed to be exempt from the rules. They have rate-limits on incoming connections as well, a lot better than Barracuda.

I always specify the source/destination interface, state then the port.


23 MB January 3, 2012 at 8:17 am

How do i open the port 25 on a public ip (eg. because it is close, I can only send email but can’t receive email?
But on my localhost it’s open, when I test I able to send and receive only on This is my rule

iptables -A INPUT -p tcp -m tcp –dport 25 -j ACCEPT

when i check netstat -tulpn | grep :25
tcp 0 0* LISTEN 2671/exim4
tcp6 0 0 ::1:25 :::* LISTEN 2671/exim4

Hope you can help me on this matter. I really confused on this one.


24 Badr Najah January 2, 2012 at 6:55 pm

Very useful.


25 dilip January 5, 2012 at 7:36 am

Wooooooooooowwwwww. thats coooool…
very usefull link….

Thanks yar….


26 nbasileu January 9, 2012 at 10:19 am

Rule #14

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

–destination-port 8080 not 22

Anyway, this is a fu**** good website with fully nice articles.
Very big thx dudes.

Happy new year everyone.


27 Atul Modi March 11, 2012 at 10:16 am

Excellent Stuff Guys!!!

Everyone is putting their part. Great to see this kind of community flourish further.

I am thankful to the ppl who started this website.


28 Daniel Vieceli March 13, 2012 at 2:38 pm

Excellent thanks.


29 jm April 1, 2012 at 3:48 am

Good info and well written.Easy to understand for everyone… I will be back to learn more needed security rules.. Oh and yes I’m a human but I hate to say the definition of human is ( MONSTER) don’t believe me ? Look it up on the net ! Ha ha ha ha
Thank you for this page….


30 rw1 April 5, 2012 at 7:45 am

thank you! for the information on how to delete a firewall rule! priceless! thanks!


31 Eli May 11, 2012 at 12:19 am

How can i use iptable rules to use multiple internet connections for the same bit torrent download?
Actually, i have two broadband connections. I want to combine them. I am told to get load balancing hardware and i cant afford that. So, i did some experimenting. On first DSL modem, i set its IP to be
On second modem, i set its IP to be
Then in windows network adapter settings, i set Metric value of each adapter to 1. Thats about it. My bit torrent downloads/uploads use both my internet connections at the same time which gives effect of combined speed.
Can i do something like that in Linux?
Or, how can i combine two internet connections by using iptables? I dont want any hardware changes. All i have is two DSL modems and two network interface cards. Precise help would be greatly appreciated.


32 kolya May 13, 2012 at 6:55 pm

Hi, got a question to the author of the article. I have tried different kind of commands from the command line, edited the file /etc/sysconfig/iptables directly with following saving and restarting iptables/rebooting system. Nothing helps, my rules get overwritten by the system flushing my new rules or editing them. I tried to open ports (22,21 etc). The goal why I edit my firewall is to get connected to ftp server via FileZilla. Would you recommend me how to open ports? Tell me please if you need any system outputs or something. Cheers


33 nixCraft May 13, 2012 at 8:35 pm

> my rules get overwritten by the system flushing my new rules or editing them

I think you got some sort of script or other firewall product running that is overwriting your rules. Check your cron job and you find the source for the same. If you need further assistance head over to the nixcraft Linux Support forum.


34 kolya May 14, 2012 at 12:21 pm

thanks for your respond, as I am not a specialist I didn’t any changes to my crontab yet, anyway I checked it, also /cron.d and everything connected to cron in /var/spool/…. Nothing about iptables or something. What I noticed there are several iptables files in /etc/sysconfig/: iptables.old written by system-config-firewall, iptables generated by iptables-save with some changes what I didn’t entered.
Here is what I entered from wiki.centos.org/HowTos/Network/IPTables:

# iptables -P INPUT ACCEPT
# iptables -F
# iptables -A INPUT -i lo -j ACCEPT
# iptables -A INPUT -m state –state ESTABLISHED,RELATED -j ACCEPT
# iptables -A INPUT -p tcp –dport 22 -j ACCEPT
# iptables -P INPUT DROP
# iptables -P FORWARD DROP
# iptables -P OUTPUT ACCEPT
# iptables -L -v

Here is what I got in the iptables’s file:

:INPUT DROP [1:40]
:OUTPUT ACCEPT [526:43673]
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m tcp –dport 22 -j ACCEPT
Don’t know why it changes, probably it is aplying kind of default settings, but analyzing this settings the port 22 should be open. Nmap says it is closed, telnet outputs connection refused. Was trying to set samba server with the same result due to my firewall. What to do?


35 Sigma May 25, 2012 at 6:53 am

Thanks a lot for this article, which is extremely easy to understand and follow for beginners as me!


36 dima June 9, 2012 at 10:38 am

Regarding the block #7.1: Only Block Incoming Traffic
The rule
# iptables -A INPUT -m state –state NEW,ESTABLISHED -j ACCEPT
looks dubious to me
Why would you want to allow NEW connections?
In my view it should read
# iptables -A INPUT -m state –state RELATED,ESTABLISHED -j ACCEPT


37 qubits4all February 2, 2013 at 8:08 am

I noticed this as well. The rule as given is not right. I’ve been using iptables for a couple of years now, and the INPUT rule here should read:
iptables -A INPUT -m state –state ESTABLISHED,RELATED
(actually the above order is equivalent), because one clearly wouldn’t want to match the NEW state here. Doing so would open up the door to TCP connects (i.e., TCP SYN packets) to any listening TCP services, as well as to UDP datagrams.

Cheers to the author(s) of nixCraft for a nice article & a useful collection of iptables rules. This has become one of my favorite Linux/Unix blogs, so please keep the articles coming.


38 BiBi June 21, 2012 at 3:24 am

Thank you very much, this site is very useful. I love all of you.


39 Juan July 14, 2012 at 1:53 pm

Excellent tutorial. My desire is to block social networking in my job, I did it with squid in transparent mode but skipped to enter https. I did the tests on a virtual pc and it worked fine. The issue is that I is working on the production server. This has two network cards, eth0 traffic where it enters the Internet and eth1 to connect to the network. For the case of Facebook do the following:

# We block Facebook
iptables-A OUTPUT-p tcp-d 443-j DROP
iptables-A OUTPUT-p tcp-d 443-j DROP
iptables-A OUTPUT-p tcp-d 443-j DROP
iptables-A OUTPUT-p tcp-d http://www.facebook.com-dport 443-j DROP
iptables-A OUTPUT-p tcp-d facebook.com-dport 443-j DROP

Any suggestions?.



40 jaydatt August 30, 2012 at 10:47 am

really helpful article


41 Borislav Bozhanov September 11, 2012 at 11:13 pm


Here is how to BLOCK FACEBOOK with single line command and iptables:

for i in $(nslookup facebook.com|grep Address|grep -v “#53″|awk ‘{print $2}’); do iptables -I FORWARD -m tcp -p tcp -d $i/24 –dport 443 -j DROP; done

You can replace the website with any other secure (https) you want.

For http websites (non-secure) – use the following line, replacing yahoo.com with the desired domain name:
for i in $(nslookup yahoo.com|grep Address|grep -v “#53″|awk ‘{print $2}’); do iptables -I FORWARD -m tcp -p tcp -d $i/24 –dport 80 -j DROP; done

Don’t forget to save your iptables configuration.

Borislav Bozhanov


42 Łukasz Bodziony September 13, 2012 at 7:37 pm

Thank you!!!


43 Gus September 29, 2012 at 6:51 pm

I’m working with virtual machines. and would like to make a firewall and rootin bash.

My question is this
I have several public ip — IP1 = (200.45.xx.xxx) IP2 (=200.xx), IP3 = ·

The issue is that one of them use to Wan IP1.

Now I want to direct traffic from outside to inside. But I also want to redirect the traffic that comes to public ip 2 ( IP2 to the local machine in lan ( and what comes to public ip 3 (IP3) to the local machine (

I can not find examples of how to redirect traffic coming to a specific public IP to a particular LAN private IP.
If you can ask to help me.



## Pello Xabier Altadill Izura

echo -n Aplicando Reglas de Firewall…

## Paramos el ipchains y quitamos el modulo

/etc/rc.d/init.d/firewall stop

rmmod ipchains

## Instalando modulos

modprobe ip_tables

modprobe ip_nat_ftp

modprobe ip_conntrack_ftp

## Variables




## En este caso,

## la tarjeta eth1 es la que va al ROUTER y la eth0 la de la LAN

## Primeras reglas

/sbin/iptables -P INPUT DROP

/sbin/iptables -F INPUT

/sbin/iptables -P OUTPUT ACCEPT

/sbin/iptables -F OUTPUT

/sbin/iptables -P FORWARD ACCEPT

/sbin/iptables -F FORWARD

/sbin/iptables -t nat -F

### En principio, si las reglas INPUT por defecto hacen DROP, no haria falta

### meter mas reglas, pero si temporalmente se pasa a ACCEPT no esta de mas.

## Todo lo que viene de cierta IP se deja pasar (administradores remotos…)

/sbin/iptables -A INPUT -i $EXTIF -s -d -j ACCEPT

## El localhost se deja

/sbin/iptables -A INPUT -i lo -j ACCEPT

/sbin/iptables -A OUTPUT -o lo -j ACCEPT

## Aceptar al exterior al 80 y al 443

# Permitir salida al 80

/sbin/iptables -A INPUT -i $EXTIF -p tcp –sport 80 -j ACCEPT

/sbin/iptables -A OUTPUT -o $EXTIF -p tcp –dport 80 -j ACCEPT

# Permitir salida al 443

/sbin/iptables -A INPUT -i $EXTIF -p tcp –sport 443 -j ACCEPT

/sbin/iptables -A OUTPUT -o $EXTIF -p tcp –dport 443 -j ACCEPT

## SALIDA SMTP – Para que el servidor se pueda conectar a otros MTA

# Permitir salida SMTP

/sbin/iptables -A INPUT -i $EXTIF -p tcp –sport 25 -j ACCEPT

/sbin/iptables -A OUTPUT -o $EXTIF -p tcp –dport 25 -j ACCEPT

## SALIDA FTP – Para que el servidor se pueda conectar a FTPs

/sbin/iptables -A INPUT -i $EXTIF -p tcp –sport 21 -m state –state ESTABLISHED -j ACCEPT

/sbin/iptables -A OUTPUT -o $EXTIF -p tcp –dport 21 -m state –state NEW,ESTABLISHED -j ACCEPT

# ftp activo

/sbin/iptables -A INPUT -i $EXTIF -p tcp –sport 20 -m state –state ESTABLISHED,RELATED -j ACCEPT

/sbin/iptables -A OUTPUT -o $EXTIF -p tcp –dport 20 -m state –state ESTABLISHED -j ACCEPT

# ftp pasivo

/sbin/iptables -A INPUT -i $EXTIF -p tcp –sport 1024:65535 –dport 1024:65535 -m state –state ESTABLISHED -j ACCEPT

/sbin/iptables -A OUTPUT -o $EXTIF -p tcp –sport 1024:65535 –dport 1024:65535 -m state –state ESTABLISHED,RELATED -j ACCEPT



Q.1  How to configure NAT on your linux server.

Ans.  Nating is used to share a single public ip for accessing internet for many local private network users.


  1. Configure two Ethernet cards, one with your private ip (eth0) and one with public ip (eth1).
  2. Add the ip of private network ethernet (eth0) as your gateway :

cat /etc/sysconfig/network

GATEWAY=xx.xx.xx.1    # Internet Gateway, provided by the ISP

  1. Specify your DNS name

cat /etc/resolv.conf

nameserver      # Primary DNS Server provided by the ISP
nameserver        # Secondary DNS Server provided by the ISP

  1. Configure NAT with IPTABLES:

# Delete and flush. Default table is “filter”. Others like “nat” must be explicitly stated.

Iptables –F  (F = –flush)

Iptables –t nat –F (t = –table)

Iptables –D (–delete chain)

# Delete all chains that are not in default filter and nat table

Iptables –t nat –D

# Set up IP FORWARDing and Masquerading

  1. iptables –table nat –append POSTROUTING –out-interface eth0 -j MASQUERADE
  2. iptables –append FORWARD –in-interface eth1 -j ACCEPT

# Enables packet forwarding by kernel

  1. echo 1 > /proc/sys/net/ipv4/ip_forward
  2. #Apply the configuration

service iptables restart. (It saves the configuration in /etc/sysconfig/iptables)


# Ping the Gateway of the network from client system

Ping (Your gateway ip)

Q.2 What is Prerouting and Postrouting.

Ans. As the name implies, the PREROUTING chain is responsible for packets that just arrived at the network interface. So far no routing decision has taken place, therefore it is not yet known whether the packet would be interpreted locally or whether it would be forwarded to another machine located at another network interface. After the packet has passed the PREROUTING chain the routing decision is made. In case that the local machine is the recipient, the packet will be directed to the corresponding process and we do not have to worry about NAT anymore. In case that the recipient is located in a (sub-)net located at a different network interface, the packet will be forwarded to that interface, provided that the machine is configured to do so. Just before are forwarded packet leaves the machine it passes the POSTROUTING chain and then leaves through the network interface. For locally generated packets there is a small difference: Instead of passing the PREROUTING chain it passes the OUTPUT chain and then moves on to the POSTROUTING chain.

Q.3 What is SNAT and DNAT ?

I divide NAT into two different types: Source NAT (SNAT) and Destination NAT (DNAT).

Source NAT is when you alter the source address of the first packet: i.e. you are changing where the connection is coming from. Source NAT is always done post-routing, just before the packet goes out onto the wire. Masquerading is a specialized form of SNAT.

Destination NAT is when you alter the destination address of the first packet: i.e. you are changing where the connection is going to. Destination NAT is always done before routing, when the packet first comes off the wire. Port forwarding, load sharing, and transparent proxying are all forms of DNAT.

Q.4 Example of configuring IPTABLES:

Ans. NAT we have another possibility: All incoming packets going to port 80 will be redirected to port 8080. The command is:

# Transparent proxying:

# (local net at eth0, proxy server at port 8080)

$> iptables -t nat -A PREROUTING -i eth0 -p tcp –dport 80 \

       -j REDIRECT –to-ports 8080

Of course a HTTP-Proxy at port 8080 needs to be up and running. Maybe some special configurations (or even a special compilation) are needed for your proxy server in order to support transparent proxying. Disadvantages of transparent proxying are the higher CPU load (especially for really large networks) and some problems with old or very simple browsers.

Help! I am behind a restrictive firewall!

Before we start I have to place a warning:

Everybody has to check on his or her own, whether the following steps violate any existing usage conditions, BEFORE he or she uses one of the presented techniques! Usage of the following commands is at your own risk, I can not hold any responsibilty for damages or fines that result from an unappropriate usage of the following commands and techniques!

Although you may not expect it, but NAT can even help you in such a case! Let us assume that only a few ports can be reached from your local network. First of all one has to find these open ports. One wide spread utility to use is nmap: (please scan your own computers only, scanning unknown computers can be interpreted as a first step to intrusion!)

# Scan a machine:

# (Replace http://www.example.com by an appropriate machine)

$> nmap http://www.example.com

The output will display various ports, most of them will be in state ‘closed’ (no service at that port), others will be in state ‘filtered’ (no connection to that port), perhaps some are in state ‘open’ (service running). Let us assume all ports below 5000 are closed, except port 80, but there are ports starting at 5000 that can be reached. To get a connection to any port below 5000 to an arbitrary machine one needs a (Linux-) machine that is located outside the firewall (no matter where as long as it can be reached and is not itself restricted by a firewall), that can be accessed and that supports NAT (iptables).

First of all we have to gain access to that machine (suppose IP outside the firewall. We use any workstation outside the firewall to establish a SSH connection to Then we issue the command

# Redirect SSH from port 5000 to port 22:

$> iptables -t nat -A PREROUTING -p tcp –dport 5000 -j REDIRECT –to-ports 22

Now we can return to our machine behind the restrictive firewall and can access via SSH on port 5000. Alternatively you can configure your SSH-daemon to run on port 5000. However, now you are able to configure the remote machine appropriately. To connect to port 110 (POP3) on machine, issue the command

# redirect port 5001 to port 110 (POP3) at

$> iptables -t nat -A PREROUTING -p tcp –dport 5001 \

       -j DNAT –to-destination

# Change sender to redirecting machine:

$> iptables -t nat -A POSTROUTING -p tcp –dport 110 \

       -j MASQUERADE

Instead of the last MASQUERADE command SNAT is possible as well (-j SNAT –to-source, but since we are the only user of that connection this does not matter, therefore I chose MASQUERADE because it is shorter and easier to use.

We can connect to all other ports in exactly the same manner as long as we have enough open ports. Even secure connections (like IMAPS) can be redirected in that way, warnings regarding the security certificate have to be ignored (as long as we know what we are doing!). For the POP3-connection from above you still have to configure your mail client accordingly, your server for mails would then be, port 5001.

If our ‘provider’ runs a proxy for connections to port 80 (i.e. the provider uses a transparent proxy) and monitors the content and we do not agree with that, then NAT can help us once again. Assuming that proxy avoidance is not prohibited, we can set up a proxy (configured for transparent proxying) at, port 5002. After that you enter on your local machine the following command:

# redirect http-Traffic going to Port 80 to

$> iptables -t nat -A OUTPUT -p tcp –dport 80 \

       -j DNAT –to-destination

In that way you have successfully circumvented the provider’s proxy! (In my view it is very fancy to circumvent a transparent proxy using a transparent proxy! 🙂 ) Alternatively you can again configure your browser by hand to use your new proxy, but this may still lead to some troubles with other programs. However, configuring your browser by hand would at least avoid the disadvantages of transparent proxying.

To close this application I want to recapitulate our steps: First we find an open port for a SSH-connection. Then we statically redirect the other open ports to the desired destinations (usually one is not using that many non-HTTP-servers). If one manages to do this redirection dynamically, then two open TCP ports (one for SSH) and one open UDP port are sufficient to connect to nearly every port at every machine, the only disadvantage then would be that you can have only one connection at a time (per protocol).

Running a Server behind a NAT-router

For servers running behind a NAT-router additional steps are needed since at first you cannot connect from outside to the server. Let us assume that we have a HTTP-server with IP and our router has the IP address and is connected to the internet over its second network interface with IP To reach the HTTP-server from outside, type

# redirect http traffic to

$> iptables -t nat -A PREROUTING -p tcp -i eth1 –dport 80 -j DNAT –to

and you are done. Now you are able to access the HTTP-server from outside using the IP

Linux: Apache Tutorial

Apache Webserver:

  1. Install the packages for webserver (httpd)

#Yum groupinstall “Web Server”

  1. #/etc/init.d/httpd start/stop/restart or service httpd start/stop/restart or apachectl start/stop/gracefull (reload)
  2. #Chkconfig httpd on
  3. Check the configuration file:

#less  /etc/httpd/conf/httpd.conf

No more configuration is required for basic apache webserver. Start the web browser and enter a URL of http://localhost. The web page is based on the contents of the etc/httpd/conf.d/welcome.conf file,which refers to the /var/www/error/noindex.html.

From the command line, elinks can be used as a browser. Example: elinks http://localhost

The default page visible on browser is the index.html page specified in the DocumentRoot. If ti is not there the browser will show you the welcome.conf page. To see a specific page specify that in the url i.e. http://localhost/test.html

See the directives:

DocumentRoot:  This directive specifies the directory containing the webpages of Apache server. By default it is /var/www/html.

DirectoryIndex: The default DirectoryIndex directive looks for an index.html web page file

in this directory. A standard RHEL 6 index.html page is available in the /usr/share/doc/HTML/en-US directory. Copy that file to the /var/www/html directory, and navigate to http://localhost with a browser such as ELinks


ServerRoot: The base location of configuration and log files is determined by the ServerRoot

directive. The default value from httpd.conf is ServerRoot “/etc/httpd”

Apache Log Files:

Apache log files are configured in the /etc/httpd/logs directory, they’re actually stored in the /var/log/httpd directory. Based on the standard Apache configuration files, access attempts are logged in the access_log file and errors are recorded in the error_log file. Standard secure log

files include ssl_access_log, ssl_error_log, and ssl_request_log.




Apache Security:


Security Levels for Apache:

  1. Firewalls (iptables)
  2. Security options given in Apache configuration file
  3. Secured Apache (https)
  4. Selinux


With the Listen and NameVirtualHost directives, the Apache web server specifies the standard communication ports associated with both the HTTP and HTTPS protocols, 80 and 443. To allow external communication through the noted ports, you can set up both ports as trusted services in the Firewall Configuration tool. Of course, for systems where HTTP and HTTPS are configured on nonstandard ports, you’ll have to adjust the associated iptables rules accordingly.

You can restrict access to webserver as given below:

-A INPUT -m state –state NEW -m tcp -p tcp -s

–dport 80 -j REJECT

-A INPUT -m state –state NEW -m tcp -p tcp -s

–dport 80 -j ACCEPT


The default file labels for Apache configuration files are consistent, as shown in the output to the ls -Z /etc/httpd and ls -Z /var/www commands. Individual files use the same contexts as their directory.

For example if you create a web page or directory and simply place it in the document root, selinux may not allow the webserver to invoke it unless you correct the selinux contexts on the files.

Run the ls -Z /var/www command. Note the SELinux contexts. For most directories, the user context is system_u and the type is http_sys_content_t. For a newly created /www directory, you could just change the SELinux contexts with the following commands. The -R applies the changes recursively, so the new contexts are applied to files and subdirectories.

# chcon -R -u system_u /www/

# chcon -R -t httpd_sys_content_t /www/

To make the selinux changes persistent (can be restored if you run restorecon command after a relabel) run :

# semanage fcontext -a -s system_u -t httpd_sys_content_t /www/

This command adds a entry in command adds the following entry to  /etc/selinux/targeted/contexts/files/file_contexts.local and if the files contexts are to be restored from any reason, it is possible.

Apache and SELinux Boolean Settings:

All the selinux Boolean values can be seen with:

# getsebool -a

Out of the many other SELinux options, the one of particular interest for this chapter is httpd_enable_homedirs, which supports access to files from user home directories. Other scripts of potential interest relate to interactions with other services, specifically, httpd_enable_ftp_server, httpd_use_cifs, and httpd_use_nfs. These options allow Apache to act as an FTP server, as well as to read shared Samba / NFS directories.

To enable a particular Boolean use :

#setsebool -P httpd_use_nfs on

Virtual Hosts:


With the help of virtual hosts, you can run multiple websites, on a single ip address of your web server. The websites can be of different domains. To create virtual hosts, follow the steps:

  1. # vi /etc/httpd/conf/httpd.conf and enable the below directive:

NameVirtualHost *:80

To use a name-based host, leave the asterisk after this directive. Otherwise, set

the IP address for the local network interface.

  1. In the bottom section of httpd.conf file copy the virtual host stanza in bottom and make changes as below:

NameVirtualHost *:80 (Add this directive to enable multiple virtual hosts to be accessed by name. This is not required if the virtual hosts are to be accessed over IP  )

<VirtualHost *:80>

ServerAdmin webmaster@machine101.itbrains.com

DocumentRoot /www/docs/machine101.itbrains.com

ServerName machine101.itbrains.com

ErrorLog logs/machine101.itbrains.com-error_log


<VirtualHost *:80>

ServerAdmin webmaster@machine103.itbrains.com

DocumentRoot /www/docs/machine103.itbrains.com

ServerName machine103.itbrains.com

ServerAlias http://www.machine103.itbrains.com

ErrorLog logs/machine103.itbrains.com-error_log


Error messages are sent to the email address defined by    ServerAdmin directive.

The webpages are stored  in DocumnetRoot. Make sure the SELinux security contexts of any DocumentRoot directory you create is consistent with the contexts of the default /var/www directory (and subdirectories). Apply the chcon and semanage fcontext -a commands as required to make the security contexts match.

Clients can call this web site through the ServerName.

The ErrorLog directive specify a relative log directory, relative to the ServerRoot. Unless you’ve created a different ServerRoot for this virtual host, these files can be found in the /etc/httpd/logs directory. Normally, that directory is soft linked to /var/logs/httpd.

  1. Check the syntax of configuration changes with

# httpd –t   (The output should be : Syntax OK)

If multiple virtual hosts are configured, check them with

# httpd –S

Secure Virtual Host:

  1. Change <VirtualHost _default_:443> to <VirtualHost *:443>
  2. Add below:

ServerAdmin webmaster@vhost1.example.com

DocumentRoot /www/securedocs/vhost1.example.com

ServerName vhost1.example.com

Save the file.

SSL Certificate:


Mod_ssl package supports the SSL/TSL. The configuration file is /etc/httpd/conf.d/ssl.conf.

Simply by installing it and restarting the webserver, a SSL encrypted version of the default website on server will be made available with a self signed test certificate for localhost.

While the default SSL certificate listed in the ssl.conf configuration file can work for

basic configuration, you may want to either create a specialized local certificate or

otherwise use an actual certificate purchased from a certificate authority (CA) such

as VeriSign and Thawte.

  1. Yum install mod_ssl
  2. Since you are generating a sel
  3. # genkey machine103.itbrains.com

The genkey command is convenient, as when the process is complete, it

automatically writes the key to the /etc/pki/tls/private directory and writes the

certificate to the /etc/pki/tls/certs directory

It will pop up a window, verify the key and certificate directories and click Next.

  1. Select the size of key to minimum as it will save your time in exam.
  2. On the next screen select if you want to encrypt the key. It will ask password everytime server starts.
  3. In the next screen put the locaton specifc information and click Next.
  4. Once the key and certificate is generated, put it in the /etc/httpd/conf.d/ssl.conf file.


Apache is the most popular, secure, robust, reliable and powerful web server. Apache is used by more websites than all other web servers combined. RHEL6 includes Apache version 2.2

RHCE6 Exam objectives covered in this article

  • Configure a virtual host.
  • Configure private directories.
  • Deploy a basic CGI application.
  • Configure group-managed content.

In this tutorial I will use three systems Server, linuxclient and windowclient from our LAB environment. I will configure Apache Web Server on Server system and test from inuxclient and windowclient system. If you want to check the network topology used in this article please check following article.Lab set up for RHCE 6 practice

Installation of Apache

Two packages are required for Apache server

  • httpd
  • mod_ssl
  • elinks

httpd package install Apache web server.

mod_ssl is the additional package which required to create secure websites

elinks is the additional package for text based web browser.

If you have yum repository configured use following command to install Apache web server with additional package

# yum install –y httpd mod_ssl # yum install elinks

Or you can do it in more simpler way by using groupinsatall. With following command you can install mandatory and all default packages.

# yum groupinstall “Web Server”

If yum repository is not configured use rpm command to install necessary RPM. Mount installation disk of RHEL6 in media folder and move in Packages folder.

Run following command to install httpd

#rpm -ivh httpd* –nodeps –force

Run following command to install mod_ssl

#rpm -ivh mod_ssl* –nodeps –force

Run following command to install elinks

#rpm -ivh elinks* –nodeps –force

Verify that the packages were installed correctly

Run following command to start service when the system boots

Start httpd service

httpd service requires at least one active network connection, if it does not detect any active connection it will throw following message

Starting httpd: httpd: apr_sockaddr_info_get() failed for Server

httpd service try to resolve system IP with domain name. It will throw following error, If it fails to resolve.

httpd: Could not reliably determine the server’s fully qualified domain name, using for ServerName

In real world DNS Server are used to bind IP address with domain name. In LAB environment where we have limited systems , we can also use hosts file for this purpose.

Open /etc/sysconfig/network

Change hostname to Server.example.com and save the file

Reboot the system

Verify that hostname is changed

Before we update hosts file on server also verify the hostname and ip address of linuxclient

Now on server open /etc/hosts file

Add entry for server and linuxclient system and save the file

Verify the network card status

Now restart the httpd service

Default versions of httpd create a generic web server service which is sufficient for most basic operations. Once httpd service is running start web browser and enter a URL http://localhost

Same testing can be done form text based web browser ,If GUI is unavailable.

# elinks

We got Apache test page which confirm successful Apache configuration.

Exit from the ELinks browser. Press Q, and when the Exit ELinks text menu appears, press Y to exit Elinks.

We have successfully installed Apache Web Server. So far its a generic web server service, to make it a regular and a secure web server, we need to configure it.

IPTABLES Firewall rules for web Server

Default installation of Apache web server use port 80 for HTTP traffic and 443 for HTTPS traffic.

You can create custom iptables rule to limit access to one or more networks or systems. For example following rules allows access to every computers on network except one with IP address over port 80.

-A INPUT -m state –state NEW -m tcp -p tcp -s –dport 80 -j REJECT-A INPUT -m state –state NEW -m tcp -p tcp -s –dport 80 -j ACCEPT

We have a well written article for IPTABLES firewall, use that to create custom firewall rules for web server. For this article create rules to allow all traffic on port 80 and 443.

#iptables -A INPUT -m state –state NEW -m tcp -p tcp –dport 80 -j ACCEPT#iptables -A INPUT -m state –state NEW -m tcp -p tcp –dport 443 -j ACCEPT

Save the firewall rules you have just created and restart the iptables service

# service iptables save# service iptables restart

Until you change the value of DocumentRoot directive in httpd.conf file , Apache looks for web pages in default location /var/www/html directory.

To get your web server up and running, all you need to do is to transfer the web pages or websites in /var/www/html directory.

We will make two websites for testing. RHCE exam does not test your ability to make websites. Its only test your ability to configure and run web server. You can use most simple html web page for testing.

Make two directories mysite1 and mysite2 in /var/www/html folder

Make a sample html page in both directories

Our sample websites are ready for use.

Configure SELinux for web server

Use following command to check all associated SELinux Booleans with httpd

Most of these options are self explained and relate to interactions with other services. for example httpd_enable_ftp_server allow Apache to act as an FTP server, which is out of scope for this article.

Default enabled SELinux options

Booleans Descriptions
httpd_builtin_scripting Used to provide permission for php content
httpd_dbus_avahi Supports access from HTTP services
httpd_enable_cgi Allows HTTP services to execute GCI scripts
httpd_tty_comm Enables communication with controlling terminals
httpd_unified Supports read/write/execute access by httpd_t files

httpd_enable_homedirs supports access to files from user home directories, default value is off. We will enable it later in this article.

Default enabled options are sufficient to provide basic web services , you do not need to make any changes. But you need to configure SELinux contexts, user context is system_u and the type is http_sys_content_t.

Check the current context of the files

#ls -Z /var/www#ls -Z /var/www/html

We need to set context of any newly created file or directory for the web server user to be able to access it.

Use the chcon command to change the context

#chcon -R -u system_u /var/www/html#chcon -R -t httpd_sys_content_t /var/www/html/

Verify that all the context fields have been changed correctly

#ls -Z /var/www/html

Test these websites form linuxclient system [make sure client system have elinks rpm installed]


Verify the site

Close elinks

On window client open browser and type

We have set up Apache web server with default configuration.

Back up the default httpd.conf file on a safe location.

Open the /etc/httpd/conf/httpd.conf

This is the main configuration file for httpd web service and completely usable right out of the box for generic web service.

This file is grouped in three sections and each section is well commented

  • Global environment directives that control the whole operation of Apache server process.
  • Directives that define the parameters of the main or default server, which responds to requests that are not handled by a virtual host. These directives also provide default values for the settings of all virtual hosts.
  • Settings for virtual hosts, which allow Web requests to be sent to different IP addresses or hostnames and have them handled by the same Apache server process.

To make navigation easier, turn on line number ESC Key + : +set nu + Enter Key

Host-Based Security

If server have multiple IP address, you can limit the IP address and port on which the server can listen for incoming connection. By default server listen on port 80, but can be update as well.

For example to limit server only to listen on IP address with port 80 Set Listen Directive


Now Server will listen only on the IP address on port 80 for incoming requests.

Apache also let you configure the hosts which should be allow to access to web server. <Directory> section allow you to specify the hosts base security.

Value Example Descriptions
Allow from all Default value, allow access from all hosts
Allow from [IP Address] Allow from To allow only a specific IP or host
Allow from [Host name] Allow from linuxclient To allow only specific host
Allow from [Network] Allow from .example.com To allow only example.com network
Allow from [Network]
To allow only from network
Deny from all Deny access from all hosts
Deny from [IP Address] Deny from To Deny only a specific IP or host
Deny from [Host name] Deny from linuxclient To deny only specific host
Deny from [Network] Deny from .example.com To deny only example.com network
Deny from [Network]
To deny only from network

For exam remember

  • If DNS service is unreliable use IP address.
  • When specify domain name to allow or deny from, make sure you include the leading dot[.]
  • When specify a subnet, there is no ending dot[.] at last octet.
  • Order play the most important role, when set allow or deny access.
  • If you set Order allow, deny Only those host names or IP addresses associated with allow directive are allowed access. All remaining hosts or IP address would be denied.
  • If you set Order deny, allow Only those host names or IP addresses associated with deny directive are denied access. All remaining hosts or IP address would be allowed.

Default value is Allow from all

In our LAB setup we have two clients linuxclient [], and windowclient []. Lets allow access only to linuxclient system.

Save the file and restart the httpd service

Try to access same websites again from both client systems. This time linuxclient system would be able to access web server as usual, but on windowsystem you will be denied

User-Based Security

User based authentication provides a way to allow only certain users or group to access web server.

In exam you can use following options to configure user based authentication.

Options Descriptions
AuthType Defines the authentication method
AuthName Comment for the users
AuthUserFile File used to define username and password
AuthGroupFile File used to define groups
Require Specifies the users or groups that can log in

Open httpd.conf file again

In last practice we have restricted all hosts except one

Before we do this exercise lets allow all hosts to access the web server.

In < directory > section add following and save the file

AuthType BasicAuthName “Password Restricted Area”AuthUserFile /etc/httpd/userauthfileRequire user rhceuser01

Use htpasswd command to create a userauthfile, that will be holds user accounts.

# htpasswd -cm /etc/httpd/userauthfile rhceuser01

-c Create new file and populates it with first user and password.

-m Passwords will be encrypted in MD5 before saving

Do not use -c options for creating subsequent users, otherwise it will completely override the file. Use -c option only first time for first user, from second users do not use -c option.

Restart the web server

Try again to access same sites from client, this time it will ask for user name and password

If you cancel or use wrong user name and password, access would be denied

Use correct user name and password

Upon successful authentication access would be granted

Secure web server with .htaccess file

In previous exercise we have secured entire sites. However in real life you want to allow certain parts of site publicly accessible, while other by only authenticated users. For this we will use .htaccess file.

Open /etc/httpd/conf/httpd.conf file again

Change AllowOverride directive value to authconfig

In previous example we did user base authentication

Remove that and save the file

Make a directory and file under mysite1

mkdir /var/www/html/mysite1/salary

Suppose that salary folder contains the salary sheet of employees and we want to allow only hr group to access it.

Create a .htaccess file in the salary folder

#vi /var/www/html/mysite1/salary/.htaccess

Add followings and save the file

AuthType BasicAuthName “Password Restricted Area”AuthGroupFile /etc/httpd/rhcegroupfileRequire group hr

Now only users from hr group, defined in /etc/httpd/rhcegroupfile can assess this.

Create few more accounts

Create rhcegroupfile, this file will hold entry for groups

Add user accounts in hr group and save file

Update the SELinux context of .htaccess file

Restart the web server

Try again to access site for client, access to other parts of site are allowed except salary

To access salary folder you need to provide user name and password

Upon successful authentication access would be granted

Configure public_html folder in user home directory

httpd.conf file includes a commented directive UserDir public_html just under the default UserDir disable , when it’s enabled, it allows users to browse and access the public_html directory within their home folder.

Open /etc/httpd/conf/httpd.conf file

Comment the default directive

Uncomment the UserDir public_html directive and save the file

Now anyone will have access to web pages that a user puts in his ~/public_html directory. This option can be useful if you want each user to share files over the Web. For this option you need to make users home directory executable for world. You also need to make public_html readable and executable. By default this option is disable because this requires a bit of security compromise. So unless you need to be able to share content out of a users home directory, do not enable this option. If you have to enable it in real world, take all caution in setting up this option.

Create a new normal user

Make public_html folder under his home folder and create a test file in public_html folder

Change file permission

Enable SELinux Boolean associated with home directory

Restart the web server

Access it from client system by typing

How to create virtual hosts

Virtual host feature of Apache allows you to define multiple web sites on single IP address. For Virtual hosts configuration following options are required

NameVirtualHost Hostname or IP address of the virtual host
ServerAdmin Email address of the webmaster
DocumentRoot Location of the directory, which holds virtual host files
ServerName URL of the virtual host
ErrorLog Location for the error log
CustomLog Location for a custom log

Suppose that we want to host a new website example.com in virtual host.

Make new directory which will hold our new site

Make a sample file in new site

Update SELinux context

Open main configuration file again

By default NameVirtualHost directive is disabled

Enable it

At the end of file in virtual host section add following lines and save the file

<VirtualHost *:80>ServerAdmin webmaster@example.comDocumentRoot /webdata/example.comServerName example.comErrorLog logs/example.com-error_logCustomLog logs/example.com-access_log common</VirtualHost>

If you have DNS server configured update the zone files, otherwise update the hosts files . On server open the /etc/hosts file

Add entry for new virtual host site and save the file

Restart the httpd service

On linuxclient system you also need to update the hosts file before testing. Open hosts file

Add entry for new virtual host site and save the file

Now use elinks command to browse new site

Test page confirms that we have successfully configured virtual host.

How to deploy a basic CGI application

In this section we will deploy a basic CGI application. RHCE exam objective “Deploy a basic CGI application”, does not test your programming skills, so you need not to worry about programming language. You only need to know the method.

Create a directory to hold your web application:

# mkdir /var/www/webapp

Make a new sample perl file

Add following in file and save the file. [This will make a sample perl script to print hello, world. Based on Apache manual]

#!/usr/bin/perlprint “Content-type: text/html\n\n”;print “Hello, World!”;

Update file permission and SELinux context

Open configuration file

At end of file add following and save the file

ScriptAlias /webapp “/var/www/webapp”<Directory “/var/www/webapp/”>Options ExecCGI FollowSymLinksOrder allow,denyAllow from all</Directory>

Restart the web server

On client now you can access this CGI application.

Configure secure virtual host

In this last section of tutorial we will configure a secure virtual host with self signed certificate. Make a directory to host our secure site

Make a sample index.htm file in it

Change file permission and Update SELinux context

Open main configuration file /etc/httpd/conf.d/ssl.conf

Make sure Listen Directive remain on

Add new Directive NameVirtualHost *:443 just above the <VirtualHost _default_:443> and replace _default_ with * in <VirtualHost _default_:443> tag.Uncomment the DocumentRoot and ServerName directives.

Change the value of directives and save the file

Move in certificate holder directory /etc/pki/tls/certs and use genkey command to generate new certificate and private key for secure site

Select Next and press enter on Keypair generation window

During the exam always choose minimum available key size. Even smaller key size can take up to several minutes and in exam every minute is precious. Select 512 and move to Next tab and press enter

Wait while key generates

Select No and press enter on Generate CSR window

Keep default details and select Next and press Enter

We have sucessfully created the certificate ,now we to update the hosts file on server

Restart the httpd service

On client updated the hosts file

To test secure site open the web browser and type https://host1.example.com/index.htm in URL

You will see Untrusted connection screen Unless you purchase an actual certificate from a certificate authority (CA) such as VeriSign and Thawte. For RHCE exam we do not need third party certificate, as we have self signed certificate. Click on I Understand the Risks and Click on Add Exception

Click on confirm security exception

Test page confirms that we have successfully configured the secure virtual host

To test secure sites form elinks test based browser we need to comment two standard directives

open /etc/elinks.conf file

You need to comment these directives

Comment them and save the file

Now you can access secure sites form elinks as well

Test page confirms our secure web hosting

When you restarts the httpd service, restart process actually stop the service from running before starting it again. This process hardly take few seconds that is ok for exam purpose but in real life where thousands of people are hitting your site, you can’t afford any outage even its in seconds. In that situation you can use reload option which allows the main configuration to reread without the actually bringing service down.

#service httpd reload

One more important option which should know for real world is graceful

#service httpd graceful

This option reread the new configuration file without disconnecting any currently connected users. Only drawback of this option is that the currently active connections use the old configuration file until they terminate their connection and reconnect.

One more cool options is configtest, when used , service parses the main config file for any errors and reports back if something is found. It’s your helping hand during the exam to detect any syntax errors in configuration file.

# service httpd configtestSyntax OK

If this command detect any syntax related error it return with that, otherwise it return with Syntax ok.

Interview Questions: NFS and Samba

  • What is hard and soft mounting?
  • What are daemons for NFS ?
  • What is No Stale error in NFS ?
  • How to see which version of NFS is presently running ?
  • What is impact of version mismatch ?
  • What is no_root_squash ?
  • What is difference between nfs V3 and V4 ?
  • How to change nfs port in v3 ?
  • Why Samba is required?
  • What are Samba ports ?
  • What is CIFS ?