Nagios Directory Structure

0

Nagios Directory Structure

Main Config File
/usr/local/nagios/etc/nagios.cfg

Log File
/usr/local/nagios/var/nagios.log

Object Config Files
/usr/local/nagios/etc/objects/*.cfg

Nagios Plugins
/usr/local/nagios/libexec     // defined in /usr/local/nagios/etc/resource.cfg file

Nagios Web interface
/usr/local/nagios/etc/cgi.cfg

Nagios config file for Apache to interpret
/usr/local/apache/conf.d/nagios.conf

This contains directives for the following URLs
http://<nagios-host>/nagios/
http://<nagios-host>/nagios/cgi-bin/

Nagios Log rotation configuration File
/etc/logrotate.d/nagios

Advertisements

Iftop Installation

0

Iftop Installation

1- Install dependencies mudule

yum install libpcap-devel
yum install libpcap

2- Now, download the iftop source:

cd /usr/src
wget http://www.ex-parrot.com/~pdw/iftop/download/iftop-0.17.tar.gz

3- Installation Process

gzip -d iftop-0.17.tar.gz
tar xvf iftop-0.17.tar
cd iftop-0.17
./configure
make
make install

http://www.slashroot.in/linux-iptraf-and-iftop-monitor-and-analyse-network-traffic-and-bandwidth

Easy to monitoring CPU Utilization with SAR

0

Sar command generates the stats for CPU usage, RAM usage and load average of the server and stores them in a file at regular interval. By default, the command without an option displays CPU stats of the current day.

Download the latest version from sysstat download page.

http://sebastien.godard.pagesperso-orange.fr/download.html

wget http://pagesperso-orange.fr/sebastien.godard/sysstat-10.0.0.tar.bz2

tar xvfj sysstat-10.0.0.tar.bz2

cd sysstat-10.0.0

./configure –enable-install-cron

make

make install

# sar -V
sysstat version 7.0.2
(C) Sebastien Godard

Edit /etc/cron.d/sysstat, enter:

# vi /etc/cron.d/sysstat

Update it as follows to log all disk stats (the -d option force to log stats for each block device and the -I option force report statistics for all system interrupts)

# Run system activity accounting tool every 10 minutes
*/10 * * * * root /usr/lib64/sa/sa1 -I -d 1 1
# Generate a daily summary of process accounting at 23:53
53 23 * * * root /usr/local/lib/sa/sa2 -A

Save and close the file. Turn on the service, enter:

# chkconfig sysstat on
# service sysstat start

Edit /etc/sysconfig/sysstat file specify how long to keep log files in days.

# How long to keep log files (in days).
# If value is greater than 28, then log files are kept in
# multiple directories, one for each month.
HISTORY=7

Usage sar -function

-a reports usage of file access system calls.
-b reports buffer cache usage and hit rate.
-c reports system calls.
-d report block device activity.
-g report paging activity (V.4 only)
-k report kernel memory allocation activity. (v.4 only)
-m report message and sephamore activity.
-p report paging activity.
-q report average queue length waiting for CPU.
-r report unused memory pages and disk blocks.
-u report CPU utilization.
-v report status of system tables.
-w report swapping and paging activity.
-x report RFS operation (V.4 only)
-y reports terminal activity.
-A reports all data (same as sar -udqbwcayvmprgkxSDC)
-C reports RFS buffer caching overhead.
-Db report buffer cache usage for RFS and local activity.
-Dc report system calls separately for RFS and local activity.
-Du report CPU utilization by RFS and local activity.
-S reports RFS server and request queue status.

Where,

3 = interval
10 = count

To view process creation statistics, enter:
# sar -c 3 10

To view I/O and transfer rate statistics, enter:
# sar -b 3 10

To view paging statistics, enter:
# sar -B 3 10

To view block device statistics, enter:
# sar -d 3 10

To view statistics for all interrupt statistics, enter:
# sar -I XALL 3 10

To view device specific network statistics, enter:
# sar -n DEV 3 10
# sar -n EDEV 3 10

To view CPU specific statistics, enter:
# sar -P ALL
# Only 1st CPU stats
# sar -P 1 3 10

To view queue length and load averages statistics, enter:
# sar -q 3 10

To view memory and swap space utilization statistics, enter:
# sar -r 3 10
# sar -R 3 10

To view status of inode, file and other kernel tables statistics, enter:
# sar -v 3 10

To view system switching activity statistics, enter:
# sar -w 3 10

To view swapping statistics, enter:
# sar -W 3 10

To view statistics for a given process called Apache with PID # 4252, enter:
# sar -x 4252 3 10

===========================>

System Monitoring using ATOP

9

System Monitoring using ATOP

ATOP is an advanced interactive monitoring tool to analyze the load and hardware resources on a Linux system. It shows the CPU, Memory, Disk and Network resource usages. Atop gives the resource occupation on system level followed by the information of processes that have been active during the time interval (10 seconds default).
In an Atop window , various system activity reports can be generated by using different keys:

Key m : Memory consumption
Key d : Disk utilization
Key s : Scheduling information
Key v : Variable information
Key c : Command line
Key p : Accumulated per program
Key u : Accumulated per user
Key n : Network utilization

Installation

1. To install on Centos, depending on 32 or 64 bit you can choose rpm from “http://pkgs.repoforge.org/atop/”.

2. yum install atop

After installation you can use interactive atop commands from atop man page.
Logs
When atop is installed, a cronjob is activated to run a background incarnation of atop that writes compressed samples to a log file in raw format.
These log files can be found in the directory /var/log/atop. When the command “atop -r” is started, today’s log file will be shown. When specifying another date as argument, the concerning log file will be shown.

Advantages

Atop has some major advantages compared to other performance-monitors:

1. Resource consumption by all processes
It shows the resource-consumption by all processes that were active during the interval, so also the resource-consumption by those processes that have finished during the interval.

2. Utilization of all relevant resources
Shows system-level counters concerning cpu-, memory- and swap-utilization, however it also shows disk I/O and network utilization counters on system-level.

3. Permanent logging of resource utilization
It is able to store raw counter-data in a file (compressed) for long-term analysis on system- and process-level. By default the daily log files are preserved for 28 days .

4. Highlight critical resources
It is able to highlight resources that have (almost) reached a critical load by using colors for system statistics.

5. Accumulated process activity per user
For each interval it is able to accumulate the resource consumption for all processes per user.

6.Accumulated process activity per program
For each interval it is able to accumulate the resource consumption for all processes with the same name.

7. Disk and network activity per process
In combination with optional kernel patches it shows process-level counters concerning disk I/O and network activity.

Nagios Installation

6

Nagios is a powerful tool that provides you with instant awareness of your organization’s mission-critical IT infrastructure. Nagios allows you to detect and repair problems and mitigate future issues before they affect end-users and customers
This article deals with the step by step installation and configuration of Nagios.

Login as root

Download the latest version of Nagios from http://www.nagios.org/download.

Unpacking The Distribution

To unpack the Nagios distribution:

tar xzf nagios-version.tar.gz

cd nagios-version

Create Nagios User/Group

Add a new user (and group) to the system with the following command :

adduser nagios

Create Installation Directory

Create the base directory where to install Nagios as follows…

mkdir /usr/local/nagios

Change the owner of the base installtion directory to be the Nagios user and group you added earlier as follows:

chown nagios.nagios /usr/local/nagios

Identify Web Server User

The following command can be used to quickly determine what user Apache is running as :

grep “^User” /etc/httpd/conf/httpd.conf

Add Command File Group

Create a new group whose members include the user of the web server is running as and the user Nagios is running . Call this new group ‘nagcmd‘ & name it .

/usr/sbin/groupadd nagcmd

Next, add the users that web server and Nagios run as to the newly created group with the following commands:

/usr/sbin/usermod -G nagcmd apache
/usr/sbin/usermod -G nagcmd nagios

Run the Configure Script

Run the configure script to initialize variables and create a Makefile as follows…(the last two options: –with-command-xxx are optional, but needed if you want to issue external commands)

./configure –prefix=prefix –with-cgiurl=cgiurl –with-htmurl=htmurl –with-nagios-user=someuser –with-nagios-group=somegroup –with-command-group=cmdgroup

Replace prefix with the installation directory that you created in the step above (default is /usr/local/nagios)
Replace cgiurl with the actual url you will be using to access the CGIs (default is /nagios/cgi-bin). Do NOT append a slash at the end of the url.
Replace htmurl with the actual url you will be using to access the HTML for the main interface and documentation (default is /nagios/)
Replace someuser with the name of a user on your system that will be used for setting permissions on the installed files (default is nagios)
Replace somegroup with the name of a group on your system that will be used for setting permissions on the installed files (default is nagios)
Replace cmdgroup with the name of the group running the web server (default is nagios, in the example above it was nagcmd). This will allow group members (i.e. your web server) to be able to submit external commands to Nagios.
OR

./configure To configure with the default options,not needed to provide all the options given as above

Compile Nagios and the CGIs with the following command:

make all

Install the binaries and HTML files with the following command:

make install

Install the sample init script to /etc/rc.d/init.d/nagios with the following command:

make install-init

Directory Structure And File Locations

cd /usr/local/nagios

You should see five different subdirectories. A brief description of what each directory contains is given in the table below.

Sub-Directory Contents
bin/ Nagios core program
etc/ Main, resource, object, and CGI configuration files should be put here
sbin/ CGIs
share/ HTML files (for web interface and online documentation)
var/ Empty directory for the log file, status file, retention file, etc.
var/archives Empty directory for the archived logs
var/rw Empty directory for the external command file
Open the Apache configuration file & add the following;

ScriptAlias /nagios/cgi-bin /usr/local/nagios/sbin

Options ExecCGI AllowOverride None Order allow,deny Allow from all AuthName “Nagios Access” AuthType Basic AuthUserFile /usr/local/nagios/etc/htpasswd.users Require valid-userAlias /nagios /usr/local/nagios/share Options None AllowOverride None Order allow,deny Allow from all AuthName “Nagios Access” AuthType Basic AuthUserFile /usr/local/nagios/etc/htpasswd.users Require valid-userRestart ApacheConfigure Web Authentication Running the following command will create a new file called htpasswd.users in the /usr/local/nagios/etc directssory. It will also create a username/password entry for nagiosadmin. It will be asked to provide a password that will be used when nagiosadmin authenticates to the web server.
htpasswd -c /usr/local/nagios/etc/htpasswd.users nagiosadmin

Once the htpasswd file is created ,we can add more users to access the CGIs. Use the following command to add additional users, replacing with the actual username you want to add. Note that the -c option is not used, since you already created the initial file.
htpasswd /usr/local/nagios/etc/htpasswd.users

When we are pointing the web browser to access the Nagios , username and password will prompt and provide the same.

Enabling Authentication/Authorization Functionality In The CGIs

Make sure that the CGIs are configured to use the authentication and authorization functionality in determining what information and/or commands users have access to. This is done be setting the use_authentication variable in the CGI configuration file to a non-zero value.

Open the CGI file using ;

vi /usr/local/nagios/etc/cgi.cfg

Check whether use_authentication is 1 or 0,If its 0 make it 1

Example:

use_authentication=1

Download and Install Nagios Plugins

[root@server1 ~]#cd /usr/src
[root@server1 ~]#wget http://downloads.sourceforge.net/project/nagiosplug/nagiosplug/1.4.14/nagios-plugins-1.4.14.tar.gz?use_mirror=dfn
[root@server1 ~]#tar xzf nagios-plugins-1.4.13.tar.gz
[root@server1 ~]#cd nagios-plugins1.4.13
Compile and Configure Nagios Plugins

We need the openssl-devel package installed to compile plugins with ssl support.

[root@server1 ~]# yum -y install openssl-devel
[root@server1 ~]#./configure –with-nagios-user=nagios –with-nagios-group=nagios –with-openssl
[root@server1 ~]#make
[root@server1 ~]#make install

Configure nagiosadmin email address for alerts:-

[root@server1 ~]#vi /usr/local/nagios/etc/objects/contacts.cfg

email nagios@localhost ; <<– CHANGE THIS TO YOUR EMAIL ADDRESS

eg. mail.zoom@gmail.com

Verify the sample Nagios configuration files:-

[root@server1 ~]#/usr/local/nagios/bin/nagios -v /usr/local/nagios/etc/nagios.cfg
Total Warnings: 0
Total Errors: 0
Enable Nagios to start at system startup / boot

[root@server1 ~]#chkconfig –add nagios
[root@server1 ~]#chkconfig nagios on
[root@server1 ~]#chkconfig httpd on

Start Nagios:-

[root@server1 ~]#service nagios start

Access the web interface now by:-

http://ip-address/nagios/

Eg: http://216.36.54.3/nagios

NRPE Installation and Setup:-

Download nrpe

OR

[root@server1 ~]#wget http://downloads.sourceforge.net/project/nagios/nrpe-2.x/nrpe-2.12/nrpe-2.12.tar.gz?use_mirror=nchc

Extract the Files:

[root@server1 ~]#tar -xzf nrpe-2.12.tar.gz
[root@server1 ~]#cd nrpe-2.12

Compile & configure NRPE using;

[root@server1 ~]# ./configure

[root@server1 ~]#make all

[root@server1 ~]#make install-plugin

[root@server1 ~]#make install-daemon

[root@server1 ~]#make install-daemon-config
[root@server1 ~]#make install-xinetd

Post NRPE Configuration:

Edit Xinetd NRPE entry:

Add Nagios Monitoring server to the “only_from” directive
[root@server1 ~]# vi /etc/xinetd.d/nrpe

Entry will be like this:-

service nrpe
{
flags = REUSE
socket_type = stream
port = 5666
wait = no
user = nagios
group = nagios
server = /usr/local/nagios/bin/nrpe
server_args = -c /etc/nrpe.conf –inetd
log_on_failure += USERID
disable = no
# only_from = 127.0.0.1
}

only_from = 127.0.0.1

Edit services file entry:

Add entry for nrpe daemon

[root@server1 ~]# vi /etc/services

nrpe 5666/tcp # NRPE

Restart Xinetd and Set to start at boot:

[root@server1 ~]#chkconfig xinetd on

[root@server1 ~]#service xinetd restart

Test NRPE Daemon Install

Check NRPE daemon is running and listening on port 5666:

[root@server1 ~]# netstat -at |grep nrpe

Output should be:-

tcp 0 0 *:nrpe *.* LISTEN
or
[root@server1 src]# netstat -plan | grep 5666
tcp 0 0 0.0.0.0:5666 0.0.0.0:* LISTEN 15721/xinetd

Check NRPE daemon is functioning:

[root@server1 src]# /usr/local/nagios/libexec/check_nrpe -H localhost

Output should be NRPE version:

NRPE v2.12

Open Port 5666 on Firewall

Make sure to open port 5666 on the firewall of the remote server so that the Nagios monitoring server can access the NRPE daemon.

you need to create the files /usr/local/nagios/etc/objects/hosts.cfg ,/usr/local/nagios/etc/objects/servicess.cfg manually & add it into /usr/local/nagios/etc/nagios.cfg as follows .

[root@server1 src]#vi /usr/local/nagios/etc/nagios.cfg
########These entries are imporatant############
cfg_file=/usr/local/nagios/etc/objects/commands.cfg
cfg_file=/usr/local/nagios/etc/objects/contacts.cfg
cfg_file=/usr/local/nagios/etc/objects/hosts.cfg
cfg_file=/usr/local/nagios/etc/objects/services.cfg
cfg_file=/usr/local/nagios/etc/objects/timeperiods.cfg
cfg_file=/usr/local/nagios/etc/objects/templates.cfg
########These entries are imporatant#############

Open the file /usr/local/nagios/etc/objects/commands.cfg and add the following entry to it.

root@server1]#vi /usr/local/nagios/etc/objects/commands.cfg

define command{
command_name check_nrpe
command_line /usr/local/nagios/libexec/check_nrpe -H $HOSTADDRESS$ -c $ARG1$
}

Now edit the file /usr/local/nagios/etc/objects/contacts.cfg and add your contact details there;

define contact{
contact_name nagiosadmin ; Short name of user
use generic-contact ; Inherit default values from generic-contact template (defined above)
alias Nagios Admin ; Full name of user
email jamesakm@yahoo.co.in ; <<— CHANGE THIS TO YOUR EMAIL ADDRESS

}
define contactgroup{
contactgroup_name admins
alias Nagios Administrators
members nagiosadmin
}

Edit the file /usr/local/nagios/etc/objects/hosts.cfg. entries will be like this:-

[root@server1 ~]# vi /usr/local/nagios/etc/objects/hosts.cfg

define hostgroup{
hostgroup_name Fsck
alias Fsck
members exam2.admin-ahead.com

}

define host{
use generic-host ; Name of host template to use
host_name exam2.admin-ahead.com
alias Fsck
address 216.36.54.3
check_command check-host-alive
max_check_attempts 3
notification_interval 300
notification_period 24×7
notification_options d,u,r
contact_groups admins
}

Now we need to edit the /usr/local/nagios/etc/objects/services.cfg file.
This file is used to define all the services. Entries will be like this:-

[root@server1 ~]# vi /usr/local/nagios/etc/objects/services.cfg

# Service definition

define service{

use generic-service ; Name of service template to use

# host_name exam2.admin-ahead.com

hostgroup_name nagios

service_description FTP

is_volatile 0

check_period 24x7_sans_holidays

max_check_attempts 3

normal_check_interval 3

retry_check_interval 1

contact_groups admins

notification_interval 300

notification_period 24x7_sans_holidays

notification_options c

check_command check_ftp

}

Repeat the same block for every services by changing service_description with the required service name( Eg. HTTP,SMTP,POP ) and check_command with check_ service name( Eg. HTTP,SMTP,POP ) like check_smtp,check_pop etc.

Client side (To monitor a remote client)

Use th NRPE daemon to execute Nagios plugins on the remote server and report back to the monitoring host server.

Create Nagios user account on the client :

[root@server1 ~]# useradd nagios
[root@server1 ~]# passwd nagios

Download and Install Nagios Plugins:

[root@server1 ~]# cd /usr/src

[root@server1 ~]#wget http://downloads.sourceforge.net/project/nagiosplug/nagiosplug/1.4.14/nagios-plugins-1.4.14.tar.gz?use_mirror=dfn

Extract Files:

[root@server1 ~]#tar xzf nagios-plugins-1.4.14.tar.gz

[root@server1 ~]#cd nagios-plugins-1.4.14.tar.gz

Compile and Configure Nagios Plugins

You need the openssl-devel package installed to compile plugins with ssl support.

[root@server1 ~]# yum -y install openssl-devel

Install Plugins:-

[root@server1 ~]# ./configure –with-nagios-user=nagios –with-nagios-group=nagios –with-openssl

[root@server1 ~]# make

[root@server1 ~]# make install

The permissions on the plugin directory and the plugins will need to be changed to nagios user

[root@server1 ~]# chown nagios.nagios /usr/local/nagios

[root@server1 ~]# chown -R nagios.nagios /usr/local/nagios/libexec

Install the xinetd Package

[root@server1 ~]# yum install xinetd

Downlad and Install NRPE Daemon

[root@server1 ~]#wget http://downloads.sourceforge.net/project/nagios/nrpe-2.x/nrpe-2.12/nrpe-2.12.tar.gz?use_mirror=nchc

Extract the Files:

[root@server1 ~]#tar -xzf nrpe-2.12.tar.gz # cd nrpe-2.12

Compile and Configure NRPE

You need the openssl-devel package installed to compile NRPE with ssl support.

Install NRPE:

[root@server1 ~]# ./configure

[root@server1 ~]#make all

[root@server1 ~]#make install-plugin

[root@server1 ~]#make install-daemon

[root@server1 ~]#make install-daemon-config
[root@server1 ~]#make install-xinetd

Post NRPE Configuration

Edit Xinetd NRPE entry:

Add Nagios Monitoring server to the “only_from” directive

[root@server1 ~]# vi /etc/xinetd.d/nrpe

Entry will be like this:-

service nrpe
{
flags = REUSE
socket_type = stream
port = 5666
wait = no
user = nagios
group = nagios
server = /usr/local/nagios/bin/nrpe
server_args = -c /etc/nrpe.conf –inetd
log_on_failure += USERID
disable = no
# only_from = 127.0.0.1
}

only_from = 127.0.0.1

Edit services file entry:

Add entry for nrpe daemon
[root@server1 ~]# vi /etc/services

nrpe 5666/tcp # NRPE

Restart Xinetd and Set to start at boot:

[root@server1 ~]#chkconfig xinetd on

[root@server1 ~]#service xinetd restart

Test NRPE Daemon Install

Check NRPE daemon is running and listening on port 5666:

[root@server1 ~]# netstat -at |grep nrpe

Output should be:-

tcp 0 0 *:nrpe *.* LISTEN

or

[root@server1 src]# netstat -plan | grep 5666
tcp 0 0 0.0.0.0:5666 0.0.0.0:* LISTEN 15721/xinetd

Check NRPE daemon is functioning:

[root@server1 src]# /usr/local/nagios/libexec/check_nrpe -H localhost

Output should be NRPE version:

NRPE v2.12

[root@server1 ~]#vi /etc/nrpe.conf

Entries:-

command[check_users]=/usr/local/nagios/libexec/check_users -w 5 -c 10
command[check_load]=/usr/local/nagios/libexec/check_load -w 5,100,100 -c 10,100,100
command[check_hda1]=/usr/local/nagios/libexec/check_disk -w 20% -c 10% -p /dev/hda1
command[check_zombie_procs]=/usr/local/nagios/libexec/check_procs -w 5 -c 10 -s Z
command[check_total_procs]=/usr/local/nagios/libexec/check_procs -w 150 -c 200
command[check_procs]=/usr/local/nagios/libexec/check_procs -w 500 -c 1000
command[check_cron]=/usr/local/nagios/libexec/check_procs -w 1:5 -c 1:20 -C crond
command[check_mem]=/usr/local/nagios/libexec/check_mem -w 90 -c 95
command[check_swap]=/usr/local/nagios/libexec/check_swap -w 10% -c 5%

Test Connection to NRPE daemon on Remote Server:-

Make sure that the NRPE on ther Nagios server can talk to the NRPE daemon on the remote server (Client) we want to monitor.
Execute the command:-

[root@server1 src]# /user/local/nagios/libexec/check_nrpe -H
NRPE v2.12

From the Server side:

Go to the Nagios Server side again and add the following changes.

Open the file /usr/local/nagios/etc/objects/hosts.cfg

[root@exam2 ~]# vim /usr/local/nagios/etc/objects/hosts.cfg

Add the clientside details along with the server side details , for example consider the following;

#For Server side

define hostgroup{

hostgroup_name nagios

alias Nagios Administrators

members exam2.admin-ahead.com

}

define host{

use generic-host ; Name of host template to use

host_name exam2.admin-ahead.com

alias Nagios Administrators

address 216.36.54.3

check_command check-host-alive

max_check_attempts 3

notification_interval 300

notification_period 24x7_sans_holidays

notification_options d,u,r

contact_groups admins

}

#For client side

define hostgroup{

hostgroup_name client

alias Client Administrator

members test.admin-ahead.com

}

define host{

use generic-host ; Name of host template to use

#use test.admin-ahead.com ; Name of host template to use

host_name test.admin-ahead.com

alias Client Administrator

address 67.219.63.169

check_command check-host-alive

max_check_attempts 3

notification_interval 300

notification_period 24x7_sans_holidays

Open the /usr/local/nagios/etc/objects/services.cfg file for adding client side Services;

[root@exam2 ~]# vim /usr/local/nagios/etc/objects/services.cfg

#Entries here for monitoring Server side FTP & client side FTP,HTTP,SSH & PING only ,we can customize as suitable to our requirement

# Service definition

define service{

use generic-service ; Name of service template to use

# host_name exam2.admin-ahead.com

hostgroup_name nagios

service_description FTP

is_volatile 0

check_period 24x7_sans_holidays

max_check_attempts 3

normal_check_interval 3

retry_check_interval 1

contact_groups admins

notification_interval 300

notification_period 24x7_sans_holidays

notification_options c

check_command check_ftp

}

define service{

use generic-service ; Name of service template to use

# host_name test.admin-ahead.com

hostgroup_name client

service_description HTTP

is_volatile 0

check_period 24x7_sans_holidays

max_check_attempts 3

normal_check_interval 3

retry_check_interval 1

contact_groups admins

notification_interval 300

notification_period 24x7_sans_holidays

notification_options c

check_command check_http

}

define service{

use generic-service ; Name of service template to use

# host_name test.admin-ahead.com

hostgroup_name client

service_description FTP

is_volatile 0

check_period 24x7_sans_holidays

max_check_attempts 3

normal_check_interval 3

retry_check_interval 1

contact_groups admins

notification_interval 300

notification_period 24x7_sans_holidays

notification_options c

check_command check_ftp

}

define service{

use generic-service ; Name of service template to use

# host_name test.admin-ahead.com

hostgroup_name client

service_description SSH

is_volatile 0

check_period 24x7_sans_holidays

max_check_attempts 3

normal_check_interval 3

retry_check_interval 1

contact_groups admins

notification_interval 300

notification_period 24x7_sans_holidays

notification_options c

check_command check_ssh

}

define service{

use generic-service ; Name of service template to use

# host_name test.admin-ahead.com

hostgroup_name client

service_description PING

is_volatile 0

check_period 24x7_sans_holidays

max_check_attempts 3

normal_check_interval 3

retry_check_interval 1

contact_groups admins

notification_interval 300

notification_period 24x7_sans_holidays

notification_options c

check_command check_ping

}

Restart the service;

[root@exam2 ~]#service nagios restart

[root@exam2 ~]#chkconfig nagios on
============================================

Nginx WebServer Security Tips

3

Nginx WebServer Security Tips

Nginx is a lightweight, high performance web server/reverse proxy and e-mail (IMAP/POP3) proxy. It runs on UNIX, GNU/Linux, BSD variants, Mac OS X, Solaris, and Microsoft Windows. According to Netcraft, 6% of all domains on the Internet use nginx webserver. Nginx is one of a handful of servers written to address the C10K problem. Unlike traditional servers, Nginx doesn’t rely on threads to handle requests. Instead it uses a much more scalable event-driven (asynchronous) architecture. Nginx powers several high traffic web sites, such as WordPress, Hulu, Github, and SourceForge. This page collects hints how to improve the security of nginx web servers running on Linux or UNIX like operating systems.

Default Config Files and Nginx Port

/usr/local/nginx/conf/ – The nginx server configuration directory and /usr/local/nginx/conf/nginx.conf is main configuration file.
/usr/local/nginx/html/ – The default document location.
/usr/local/nginx/logs/ – The default log file location.
Nginx HTTP default port : TCP 80
Nginx HTTPS default port : TCP 443
You can test nginx configuration changes as follows:
# /usr/local/nginx/sbin/nginx -t

Sample outputs:

the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
configuration file /usr/local/nginx/conf/nginx.conf test is successful
To load config changes, type:
# /usr/local/nginx/sbin/nginx -s reload

To stop server, type:
# /usr/local/nginx/sbin/nginx -s stop

#1: Turn On SELinux

Security-Enhanced Linux (SELinux) is a Linux kernel feature that provides a mechanism for supporting access control security policies which provides great protection. It can stop many attacks before your system rooted. See how to turn on SELinux for CentOS / RHEL based systems.

Do Boolean Lockdown

Run the getsebool -a command and lockdown system:

getsebool -a | less
getsebool -a | grep off
getsebool -a | grep o
To secure the machine, look at settings which are set to ‘on’ and change to ‘off’ if they do not apply to your setup with the help of setsebool command. Set correct SE Linux booleans to maintain functionality and protection. Please note that SELinux adds 2-8% overheads to typical RHEL or CentOS installation.

#2: Allow Minimal Privileges Via Mount Options

Server all your webpages / html / php files via separate partitions. For example, create a partition called /dev/sda5 and mount at the /nginx. Make sure /nginx is mounted with noexec, nodev and nosetuid permissions. Here is my /etc/fstab entry for mounting /nginx:

LABEL=/nginx /nginx ext3 defaults,nosuid,noexec,nodev 1 2
Note you need to create a new partition using fdisk and mkfs.ext3 commands.

#3: Linux /etc/sysctl.conf Hardening
You can control and configure Linux kernel and networking settings via /etc/sysctl.conf.

# Avoid a smurf attack
net.ipv4.icmp_echo_ignore_broadcasts = 1

# Turn on protection for bad icmp error messages
net.ipv4.icmp_ignore_bogus_error_responses = 1

# Turn on syncookies for SYN flood attack protection
net.ipv4.tcp_syncookies = 1

# Turn on and log spoofed, source routed, and redirect packets
net.ipv4.conf.all.log_martians = 1
net.ipv4.conf.default.log_martians = 1

# No source routed packets here
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0

# Turn on reverse path filtering
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1

# Make sure no one can alter the routing tables
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.all.secure_redirects = 0
net.ipv4.conf.default.secure_redirects = 0

# Don’t act as a router
net.ipv4.ip_forward = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0

# Turn on execshild
kernel.exec-shield = 1
kernel.randomize_va_space = 1

# Tuen IPv6
net.ipv6.conf.default.router_solicitations = 0
net.ipv6.conf.default.accept_ra_rtr_pref = 0
net.ipv6.conf.default.accept_ra_pinfo = 0
net.ipv6.conf.default.accept_ra_defrtr = 0
net.ipv6.conf.default.autoconf = 0
net.ipv6.conf.default.dad_transmits = 0
net.ipv6.conf.default.max_addresses = 1

# Optimization for port usefor LBs
# Increase system file descriptor limit
fs.file-max = 65535

# Allow for more PIDs (to reduce rollover problems); may break some programs 32768
kernel.pid_max = 65536

# Increase system IP port limits
net.ipv4.ip_local_port_range = 2000 65000

# Increase TCP max buffer size setable using setsockopt()
net.ipv4.tcp_rmem = 4096 87380 8388608
net.ipv4.tcp_wmem = 4096 87380 8388608

# Increase Linux auto tuning TCP buffer limits
# min, default, and max number of bytes to use
# set max to at least 4MB, or higher if you use very high BDP paths
# Tcp Windows etc
net.core.rmem_max = 8388608
net.core.wmem_max = 8388608
net.core.netdev_max_backlog = 5000
net.ipv4.tcp_window_scaling = 1

See also:

Linux Tuning The VM (memory) Subsystem
Linux Tune Network Stack (Buffers Size) To Increase Networking Performance
#4: Remove All Unwanted Nginx Modules

You need to minimizes the number of modules that are compiled directly into the nginx binary. This minimizes risk by limiting the capabilities allowed by the webserver. You can configure and install nginx using only required modules. For example, disable SSI and autoindex module you can type:
# ./configure –without-http_autoindex_module –without-http_ssi_module
# make
# make install

Type the following command to see which modules can be turn on or off while compiling nginx server:
# ./configure –help | less

Disable nginx modules that you don’t need.

(Optional) Change Nginx Version Header

Edit src/http/ngx_http_header_filter_module.c, enter:
# vi +48 src/http/ngx_http_header_filter_module.c

Find line

static char ngx_http_server_string[] = “Server: nginx” CRLF;
static char ngx_http_server_full_string[] = “Server: ” NGINX_VER CRLF;

Change them as follows:

static char ngx_http_server_string[] = “Server: Ninja Web Server” CRLF;
static char ngx_http_server_full_string[] = “Server: Ninja Web Server” CRLF;

Save and close the file. Now, you can compile the server. Add the following in nginx.conf to turn off nginx version number displayed on all auto generated error pages:

server_tokens off
#5: Use mod_security (only for backend Apache servers)

mod_security provides an application level firewall for Apache. Install mod_security for all backend Apache web servers. This will stop many injection attacks.

#6: Install SELinux Policy To Harden The Nginx Webserver

By default SELinux will not protect the nginx web server. However, you can install and compile protection as follows. First, install required SELinux compile time support:
# yum -y install selinux-policy-targeted selinux-policy-devel

Download targeted SELinux policies to harden the nginx webserver on Linux servers from the project home page:
# cd /opt
# wget ‘http://downloads.sourceforge.net/project/selinuxnginx/se-ngix_1_0_10.tar.gz?use_mirror=nchc&#8217;

Untar the same:
# tar -zxvf se-ngix_1_0_10.tar.gz

Compile the same
# cd se-ngix_1_0_10/nginx
# make

Sample outputs:
Compiling targeted nginx module
/usr/bin/checkmodule: loading policy configuration from tmp/nginx.tmp
/usr/bin/checkmodule: policy configuration loaded
/usr/bin/checkmodule: writing binary representation (version 6) to tmp/nginx.mod
Creating targeted nginx.pp policy package
rm tmp/nginx.mod.fc tmp/nginx.mod
Install the resulting nginx.pp SELinux module:
# /usr/sbin/semodule -i nginx.pp

#7: Restrictive Iptables Based Firewall

The following firewall script blocks everything and only allows:
Incoming HTTP (TCP port 80) requests
Incoming ICMP ping requests
Outgoing ntp (port 123) requests
Outgoing smtp (TCP port 25) requests
#!/bin/bash
IPT=”/sbin/iptables”

#### IPS ######
# Get server public ip
SERVER_IP=$(ifconfig eth0 | grep ‘inet addr:’ | awk -F’inet addr:’ ‘{ print $2}’ | awk ‘{ print $1}’)
LB1_IP=”204.54.1.1″
LB2_IP=”204.54.1.2″

# Do some smart logic so that we can use damm script on LB2 too
OTHER_LB=””
SERVER_IP=””
[[ “$SERVER_IP” == “$LB1_IP” ]] && OTHER_LB=”$LB2_IP” || OTHER_LB=”$LB1_IP”
[[ “$OTHER_LB” == “$LB2_IP” ]] && OPP_LB=”$LB1_IP” || OPP_LB=”$LB2_IP”

### IPs ###
PUB_SSH_ONLY=”122.xx.yy.zz/29″

#### FILES #####
BLOCKED_IP_TDB=/root/.fw/blocked.ip.txt
SPOOFIP=”127.0.0.0/8 192.168.0.0/16 172.16.0.0/12 10.0.0.0/8 169.254.0.0/16 0.0.0.0/8 240.0.0.0/4 255.255.255.255/32 168.254.0.0/16 224.0.0.0/4 240.0.0.0/5 248.0.0.0/5 192.0.2.0/24″
BADIPS=$( [[ -f ${BLOCKED_IP_TDB} ]] && egrep -v “^#|^$” ${BLOCKED_IP_TDB})

### Interfaces ###
PUB_IF=”eth0″ # public interface
LO_IF=”lo” # loopback
VPN_IF=”eth1″ # vpn / private net

### start firewall ###
echo “Setting LB1 $(hostname) Firewall…”

# DROP and close everything
$IPT -P INPUT DROP
$IPT -P OUTPUT DROP
$IPT -P FORWARD DROP

# Unlimited lo access
$IPT -A INPUT -i ${LO_IF} -j ACCEPT
$IPT -A OUTPUT -o ${LO_IF} -j ACCEPT

# Unlimited vpn / pnet access
$IPT -A INPUT -i ${VPN_IF} -j ACCEPT
$IPT -A OUTPUT -o ${VPN_IF} -j ACCEPT

# Drop sync
$IPT -A INPUT -i ${PUB_IF} -p tcp ! –syn -m state –state NEW -j DROP

# Drop Fragments
$IPT -A INPUT -i ${PUB_IF} -f -j DROP

$IPT -A INPUT -i ${PUB_IF} -p tcp –tcp-flags ALL FIN,URG,PSH -j DROP
$IPT -A INPUT -i ${PUB_IF} -p tcp –tcp-flags ALL ALL -j DROP

# Drop NULL packets
$IPT -A INPUT -i ${PUB_IF} -p tcp –tcp-flags ALL NONE -m limit –limit 5/m –limit-burst 7 -j LOG –log-prefix ” NULL Packets ”
$IPT -A INPUT -i ${PUB_IF} -p tcp –tcp-flags ALL NONE -j DROP

$IPT -A INPUT -i ${PUB_IF} -p tcp –tcp-flags SYN,RST SYN,RST -j DROP

# Drop XMAS
$IPT -A INPUT -i ${PUB_IF} -p tcp –tcp-flags SYN,FIN SYN,FIN -m limit –limit 5/m –limit-burst 7 -j LOG –log-prefix ” XMAS Packets ”
$IPT -A INPUT -i ${PUB_IF} -p tcp –tcp-flags SYN,FIN SYN,FIN -j DROP

# Drop FIN packet scans
$IPT -A INPUT -i ${PUB_IF} -p tcp –tcp-flags FIN,ACK FIN -m limit –limit 5/m –limit-burst 7 -j LOG –log-prefix ” Fin Packets Scan ”
$IPT -A INPUT -i ${PUB_IF} -p tcp –tcp-flags FIN,ACK FIN -j DROP

$IPT -A INPUT -i ${PUB_IF} -p tcp –tcp-flags ALL SYN,RST,ACK,FIN,URG -j DROP

# Log and get rid of broadcast / multicast and invalid
$IPT -A INPUT -i ${PUB_IF} -m pkttype –pkt-type broadcast -j LOG –log-prefix ” Broadcast ”
$IPT -A INPUT -i ${PUB_IF} -m pkttype –pkt-type broadcast -j DROP

$IPT -A INPUT -i ${PUB_IF} -m pkttype –pkt-type multicast -j LOG –log-prefix ” Multicast ”
$IPT -A INPUT -i ${PUB_IF} -m pkttype –pkt-type multicast -j DROP

$IPT -A INPUT -i ${PUB_IF} -m state –state INVALID -j LOG –log-prefix ” Invalid ”
$IPT -A INPUT -i ${PUB_IF} -m state –state INVALID -j DROP

# Log and block spoofed ips
$IPT -N spooflist
for ipblock in $SPOOFIP
do
$IPT -A spooflist -i ${PUB_IF} -s $ipblock -j LOG –log-prefix ” SPOOF List Block ”
$IPT -A spooflist -i ${PUB_IF} -s $ipblock -j DROP
done
$IPT -I INPUT -j spooflist
$IPT -I OUTPUT -j spooflist
$IPT -I FORWARD -j spooflist

# Allow ssh only from selected public ips
for ip in ${PUB_SSH_ONLY}
do
$IPT -A INPUT -i ${PUB_IF} -s ${ip} -p tcp -d ${SERVER_IP} –destination-port 22 -j ACCEPT
$IPT -A OUTPUT -o ${PUB_IF} -d ${ip} -p tcp -s ${SERVER_IP} –sport 22 -j ACCEPT
done

# allow incoming ICMP ping pong stuff
$IPT -A INPUT -i ${PUB_IF} -p icmp –icmp-type 8 -s 0/0 -m state –state NEW,ESTABLISHED,RELATED -m limit –limit 30/sec -j ACCEPT
$IPT -A OUTPUT -o ${PUB_IF} -p icmp –icmp-type 0 -d 0/0 -m state –state ESTABLISHED,RELATED -j ACCEPT

# allow incoming HTTP port 80
$IPT -A INPUT -i ${PUB_IF} -p tcp -s 0/0 –sport 1024:65535 –dport 80 -m state –state NEW,ESTABLISHED -j ACCEPT
$IPT -A OUTPUT -o ${PUB_IF} -p tcp –sport 80 -d 0/0 –dport 1024:65535 -m state –state ESTABLISHED -j ACCEPT

# allow outgoing ntp
$IPT -A OUTPUT -o ${PUB_IF} -p udp –dport 123 -m state –state NEW,ESTABLISHED -j ACCEPT
$IPT -A INPUT -i ${PUB_IF} -p udp –sport 123 -m state –state ESTABLISHED -j ACCEPT

# allow outgoing smtp
$IPT -A OUTPUT -o ${PUB_IF} -p tcp –dport 25 -m state –state NEW,ESTABLISHED -j ACCEPT
$IPT -A INPUT -i ${PUB_IF} -p tcp –sport 25 -m state –state ESTABLISHED -j ACCEPT

### add your other rules here ####

#######################
# drop and log everything else
$IPT -A INPUT -m limit –limit 5/m –limit-burst 7 -j LOG –log-prefix ” DEFAULT DROP ”
$IPT -A INPUT -j DROP

exit 0
#8: Controlling Buffer Overflow Attacks

Edit nginx.conf and set the buffer size limitations for all clients.
# vi /usr/local/nginx/conf/nginx.conf

Edit and set the buffer size limitations for all clients as follows:

## Start: Size Limits & Buffer Overflows ##
client_body_buffer_size 1K;
client_header_buffer_size 1k;
client_max_body_size 1k;
large_client_header_buffers 2 1k;
## END: Size Limits & Buffer Overflows ##

Where,

client_body_buffer_size 1k – (default is 8k or 16k) The directive specifies the client request body buffer size.
client_header_buffer_size 1k – Directive sets the headerbuffer size for the request header from client. For the overwhelming majority of requests a buffer size of 1K is sufficient. Increase this if you have a custom header or a large cookie sent from the client (e.g., wap client).
client_max_body_size 1k- Directive assigns the maximum accepted body size of client request, indicated by the line Content-Length in the header of request. If size is greater the given one, then the client gets the error “Request Entity Too Large” (413). Increase this when you are getting file uploads via the POST method.
large_client_header_buffers 2 1k – Directive assigns the maximum number and size of buffers for large headers to read from client request. By default the size of one buffer is equal to the size of page, depending on platform this either 4K or 8K, if at the end of working request connection converts to state keep-alive, then these buffers are freed. 2x1k will accept 2kB data URI. This will also help combat bad bots and DoS attacks.
You also need to control timeouts to improve server performance and cut clients. Edit it as follows:

## Start: Timeouts ##
client_body_timeout 10;
client_header_timeout 10;
keepalive_timeout 5 5;
send_timeout 10;
## End: Timeouts ##

client_body_timeout 10; – Directive sets the read timeout for the request body from client. The timeout is set only if a body is not get in one readstep. If after this time the client send nothing, nginx returns error “Request time out” (408). The default is 60.
client_header_timeout 10; – Directive assigns timeout with reading of the title of the request of client. The timeout is set only if a header is not get in one readstep. If after this time the client send nothing, nginx returns error “Request time out” (408).
keepalive_timeout 5 5; – The first parameter assigns the timeout for keep-alive connections with the client. The server will close connections after this time. The optional second parameter assigns the time value in the header Keep-Alive: timeout=time of the response. This header can convince some browsers to close the connection, so that the server does not have to. Without this parameter, nginx does not send a Keep-Alive header (though this is not what makes a connection “keep-alive”).
send_timeout 10; – Directive assigns response timeout to client. Timeout is established not on entire transfer of answer, but only between two operations of reading, if after this time client will take nothing, then nginx is shutting down the connection.
#9: Control Simultaneous Connections

You can use NginxHttpLimitZone module to limit the number of simultaneous connections for the assigned session or as a special case, from one IP address. Edit nginx.conf:

### Directive describes the zone, in which the session states are stored i.e. store in slimits. ###
### 1m can handle 32000 sessions with 32 bytes/session, set to 5m x 32000 session ###
limit_zone slimits $binary_remote_addr 5m;

### Control maximum number of simultaneous connections for one session i.e. ###
### restricts the amount of connections from a single ip address ###
limit_conn slimits 5;

The above will limits remote clients to no more than 5 concurrently “open” connections per remote ip address.

#10: Allow Access To Our Domain Only

If bot is just making random server scan for all domains, just deny it. You must only allow configured virtual domain or reverse proxy requests. You don’t want to display request using an IP address:

## Only requests to our Host are allowed i.e. nixcraft.in, images.nixcraft.in and http://www.nixcraft.in
if ($host !~ ^(nixcraft.in|www.nixcraft.in|images.nixcraft.in)$ ) {
return 444;
}
##
#11: Limit Available Methods

GET and POST are the most common methods on the Internet. Web server methods are defined in RFC 2616. If a web server does not require the implementation of all available methods, they should be disabled. The following will filter and only allow GET, HEAD and POST methods:

## Only allow these request methods ##
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 444;
}
## Do not accept DELETE, SEARCH and other methods ##
More About HTTP Methods

The GET method is used to request document such as http://www.cyberciti.biz/index.php.
The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response.
The POST method may involve anything, like storing or updating data, or ordering a product, or sending E-mail by submitting the form. This is usually processed using the server side scripting such as PHP, PERL, Python and so on. You must use this if you want to upload files and process forms on server.
#12: How Do I Deny Certain User-Agents?

You can easily block user-agents i.e. scanners, bots, and spammers who may be abusing your server.

## Block download agents ##
if ($http_user_agent ~* LWP::Simple|BBBike|wget) {
return 403;
}
##
Block robots called msnbot and scrapbot:

## Block some robots ##
if ($http_user_agent ~* msnbot|scrapbot) {
return 403;
}
#12: How Do I Block Referral Spam?

Referer spam is dengerouns. It can harm your SEO ranking via web-logs (if published) as referer field refer to their spammy site. You can block access to referer spammers with these lines.

## Deny certain Referers ###
if ( $http_referer ~* (babes|forsale|girl|jewelry|love|nudit|organic|poker|porn|sex|teen) )
{
# return 404;
return 403;
}
##
#13: How Do I Stop Image Hotlinking?

Image or HTML hotlinking means someone makes a link to your site to one of your images, but displays it on their own site. The end result you will end up paying for bandwidth bills and make the content look like part of the hijacker’s site. This is usually done on forums and blogs. I strongly suggest you block and stop image hotlinking at your server level itself.

# Stop deep linking or hot linking
location /images/ {
valid_referers none blocked http://www.example.com example.com;
if ($invalid_referer) {
return 403;
}
}
Example: Rewrite And Display Image

Another example with link to banned image:

valid_referers blocked http://www.example.com example.com;
if ($invalid_referer) {
rewrite ^/images/uploads.*\.(gif|jpg|jpeg|png)$ http://www.examples.com/banned.jpg last
}
See also:

HowTo: Use nginx map to block image hotlinking. This is useful if you want to block tons of domains.
#14: Directory Restrictions

You can set access control for a specified directory. All web directories should be configured on a case-by-case basis, allowing access only where needed.

Limiting Access By Ip Address

You can limit access to directory by ip address to /docs/ directory:

location /docs/ {
## block one workstation
deny 192.168.1.1;
## allow anyone in 192.168.1.0/24
allow 192.168.1.0/24;
## drop rest of the world
deny all;
}
Password Protect The Directory

First create the password file and add a user called vivek:
# mkdir /usr/local/nginx/conf/.htpasswd/
# htpasswd -c /usr/local/nginx/conf/.htpasswd/passwd vivek

Edit nginx.conf and protect the required directories as follows:

### Password Protect /personal-images/ and /delta/ directories ###
location ~ /(personal-images/.*|delta/.*) {
auth_basic “Restricted”;
auth_basic_user_file /usr/local/nginx/conf/.htpasswd/passwd;
}
Once a password file has been generated, subsequent users can be added with the following command:
# htpasswd -s /usr/local/nginx/conf/.htpasswd/passwd userName

#15: Nginx SSL Configuration

HTTP is a plain text protocol and it is open to passive monitoring. You should use SSL to to encrypt your content for users.

Create an SSL Certificate

Type the following commands:
# cd /usr/local/nginx/conf
# openssl genrsa -des3 -out server.key 1024
# openssl req -new -key server.key -out server.csr
# cp server.key server.key.org
# openssl rsa -in server.key.org -out server.key
# openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

Edit nginx.conf and update it as follows:

server {
server_name example.com;
listen 443;
ssl on;
ssl_certificate /usr/local/nginx/conf/server.crt;
ssl_certificate_key /usr/local/nginx/conf/server.key;
access_log /usr/local/nginx/logs/ssl.access.log;
error_log /usr/local/nginx/logs/ssl.error.log;
}
Restart the nginx:
# /usr/local/nginx/sbin/nginx -s reload

See also:

For more information, read the Nginx SSL documentation.
#16: Nginx And PHP Security Tips

PHP is one of the popular server side scripting language. Edit /etc/php.ini as follows:

# Disallow dangerous functions
disable_functions = phpinfo, system, mail, exec

## Try to limit resources ##

# Maximum execution time of each script, in seconds
max_execution_time = 30

# Maximum amount of time each script may spend parsing request data
max_input_time = 60

# Maximum amount of memory a script may consume (8MB)
memory_limit = 8M

# Maximum size of POST data that PHP will accept.
post_max_size = 8M

# Whether to allow HTTP file uploads.
file_uploads = Off

# Maximum allowed size for uploaded files.
upload_max_filesize = 2M

# Do not expose PHP error messages to external users
display_errors = Off

# Turn on safe mode
safe_mode = On

# Only allow access to executables in isolated directory
safe_mode_exec_dir = php-required-executables-path

# Limit external access to PHP environment
safe_mode_allowed_env_vars = PHP_

# Restrict PHP information leakage
expose_php = Off

# Log all errors
log_errors = On

# Do not register globals for input data
register_globals = Off

# Minimize allowable PHP post size
post_max_size = 1K

# Ensure PHP redirects appropriately
cgi.force_redirect = 0

# Disallow uploading unless necessary
file_uploads = Off

# Enable SQL safe mode
sql.safe_mode = On

# Avoid Opening remote files
allow_url_fopen = Off

See also:

PHP Security: Limit Resources Used By Script
PHP.INI settings: Disable exec, shell_exec, system, popen and Other Functions To Improve Security
#17: Run Nginx In A Chroot Jail (Containers) If Possible

Putting nginx in a chroot jail minimizes the damage done by a potential break-in by isolating the web server to a small section of the filesystem. You can use traditional chroot kind of setup with nginx. If possible use FreeBSD jails, XEN, or OpenVZ virtualization which uses the concept of containers.

#18: Limits Connections Per IP At The Firewall Level

A webserver must keep an eye on connections and limit connections per second. This is serving 101. Both pf and iptables can throttle end users before accessing your nginx server.

Linux Iptables: Throttle Nginx Connections Per Second

The following example will drop incoming connections if IP make more than 15 connection attempts to port 80 within 60 seconds:

/sbin/iptables -A INPUT -p tcp –dport 80 -i eth0 -m state –state NEW -m recent –set
/sbin/iptables -A INPUT -p tcp –dport 80 -i eth0 -m state –state NEW -m recent –update –seconds 60 –hitcount 15 -j DROP
service iptables save

BSD PF: Throttle Nginx Connections Per Second

Edit your /etc/pf.conf and update it as follows. The following will limits the maximum number of connections per source to 100. 15/5 specifies the number of connections per second or span of seconds i.e. rate limit the number of connections to 15 in a 5 second span. If anyone breaks our rules add them to our abusive_ips table and block them for making any further connections. Finally, flush keyword kills all states created by the matching rule which originate from the host which exceeds these limits.

webserver_ip=”202.54.1.1″
table persist
block in quick from
pass in on $ext_if proto tcp to $webserver_ip port www flags S/SA keep state (max-src-conn 100, max-src-conn-rate 15/5, overload flush)
Please adjust all values as per your requirements and traffic (browsers may open multiple connections to your site). See also:

Sample PF firewall script.
Sample Iptables firewall script.
#19: Configure Operating System to Protect Web Server

Turn on SELinux as described above. Set correct permissions on /nginx document root. The nginx runs as a user named nginx. However, the files in the DocumentRoot (/nginx or /usr/local/nginx/html) should not be owned or writable by that user. To find files with wrong permissions, use:
# find /nginx -user nginx
# find /usr/local/nginx/html -user nginx

Make sure you change file ownership to root or other user. A typical set of permission /usr/local/nginx/html/
# ls -l /usr/local/nginx/html/

Sample outputs:

-rw-r–r– 1 root root 925 Jan 3 00:50 error4xx.html
-rw-r–r– 1 root root 52 Jan 3 10:00 error5xx.html
-rw-r–r– 1 root root 134 Jan 3 00:52 index.html
You must delete unwated backup files created by vi or other text editor:
# find /nginx -name ‘.?*’ -not -name .ht* -or -name ‘*~’ -or -name ‘*.bak*’ -or -name ‘*.old*’
# find /usr/local/nginx/html/ -name ‘.?*’ -not -name .ht* -or -name ‘*~’ -or -name ‘*.bak*’ -or -name ‘*.old*’

Pass -delete option to find command and it will get rid of those files too.

#20: Restrict Outgoing Nginx Connections

The crackers will download file locally on your server using tools such as wget. Use iptables to block outgoing connections from nginx user. The ipt_owner module attempts to match various characteristics of the packet creator, for locally generated packets. It is only valid in the OUTPUT chain. In this example, allow vivek user to connect outside using port 80 (useful for RHN access or to grab CentOS updates via repos):

/sbin/iptables -A OUTPUT -o eth0 -m owner –uid-owner vivek -p tcp –dport 80 -m state –state NEW,ESTABLISHED -j ACCEPT
Add above rule to your iptables based shell script. Do not allow nginx web server user to connect outside.

Bounce Tip: Watching Your Logs & Auditing

Check the Log files. They will give you some understanding of what attacks is thrown against the server and allow you to check if the necessary level of security is present or not.
# grep “/login.php??” /usr/local/nginx/logs/access_log
# grep “…etc/passwd” /usr/local/nginx/logs/access_log
# egrep -i “denied|error|warn” /usr/local/nginx/logs/error_log

The auditd service is provided for system auditing. Turn it on to audit service SELinux events, authetication events, file modifications, account modification and so on. As usual disable all services and follow our “Linux Server Hardening” security tips.

Conclusion

Your nginx server is now properly harden and ready to server webpages. However, you should be consulted further resources for your web applications security needs. For example, wordpress or any other third party apps has its own security requirements.