Showing posts with label Nginx. Show all posts
Showing posts with label Nginx. Show all posts

Wednesday, March 14, 2012

Supercharge WordPress, Part 1

— SkyHi @ Wednesday, March 14, 2012


Here are a few example configuration settings for servers of different memory sizes running both MySQL and a web server on the same machine. These are not perfect, but they are good starting points.
For servers with 512MB RAM:
thread_cache_size=50
key_buffer=40M
table_cache=384
sort_buffer_size=768K
read_buffer_size=512K
read_rnd_buffer_size=512K
query_cache_limit=2M
query_cache_size=16M
query_cache_type=1
thread_concurrency=2*CPU
skip-innodb
For servers with 1GB RAM:
thread_cache_size=80
key_buffer=150M
table_cache=512
sort_buffer_size=1M
read_buffer_size=1M
read_rnd_buffer_size=768K
query_cache_limit=4M
query_cache_size=32M
query_cache_type=1
thread_concurrency=2*CPU
skip-innodb
For servers with 2GB RAM:
thread_cache_size=80
key_buffer=350M
table_cache=1024
sort_buffer_size=2M
read_buffer_size=2M
read_rnd_buffer_size=768K
query_cache_limit=4M
query_cache_size=64M
query_cache_type=1
thread_concurrency=2*CPU
skip-innodb
Once WordPress has been up and running for some time you can tweak your settings by running MySQLTuner, a Perl script that analyzes your MySQL performance and, based on the statistics it gathers, gives recommendations about which variables you should adjust to increase performance. With MySQLTuner, you can tune your my.cnf file to tease out the last bit of performance from your MySQL server and make it work more efficiently.

REFERENCES
http://linuxaria.com/?p=3293?lang=en 
http://linuxaria.com/article/supercharge-wordpress-part-2?lang=en 

http://linuxaria.com/article/supercharge-wordpress-part-3?lang=en

Thursday, January 12, 2012

upstream timed out while reading response header from upstream

— SkyHi @ Thursday, January 12, 2012
Testing mcrypt library in PHP, this error occurs:

#sudo tail -100 /var/log/php5-fpm.log
Jan 04 12:17:14.425241 [WARNING] [pool www] child 28983 exited with code 2 after 1.756421 seconds from start

Jan 04 12:17:14.431710 [NOTICE] [pool www] child 28997 started

#tail /var/log/nginx/error.php
2012/01/12 11:33:25 [error] 29037#0: *6042 upstream timed out (110: Connection timed out) while reading response header from upstream, client:  192.168.218.238, server: localhost, request: "GET /murach2/ch21/encrypt.php HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "192.168.218.238"


you have too many connections and FPM is not able to handle
everything. You can play with backlog, max_client and timeouts.
#vi /etc/php5/fpm/pool.d/www.conf

REFERENCES





Tuesday, December 20, 2011

Setting up NGINX SSL reverse proxy for Tomcat

— SkyHi @ Tuesday, December 20, 2011
Setting up Tomcat in some cases can be pain in the ass, especially when your application is pretty complex, in terms of large number of upstream servers which you all want to proxy via SSL.
In my case, I was playing around with Shindig — an OpenSocial container, which itself is a Java servlet delivered via Apache Tomcat server.


The goal was to reverse proxy Shindig through SSL, i.e. it should be able to access it via
https://localhost/gadgets/
with localhost being served by Nginx.

Initial schema

nginx tomcat reverse proxy schemaInitial nginx config


daemon off;

worker_processes  2;
error_log /var/log/nginx_error.log info;
user bananos staff;

events {
    worker_connections  1024;
}

http {
    include /opt/nginx/conf/mime.types;
    default_type application/octet-stream;

    log_format main '$remote_addr - $remote_user [$time_local] "$request" $status $bytes_sent "$http_referer" "$http_user_agent" "$gzip_ratio"';
    ignore_invalid_headers on;
    index index.html;
    client_header_timeout 240;
    client_body_timeout 240;
    send_timeout 240;
    client_max_body_size 100m;
    proxy_buffer_size 128k;
    proxy_buffers 8 128k;

    upstream tomcat_server {
 # Tomcat is listening on default 8080 port
        server 127.0.0.1:8080 fail_timeout=0;
    }

    server {
        server_name localhost;
        listen 443;

        ssl on;
        ssl_session_timeout 5m;
        ssl_protocols SSLv2 SSLv3 TLSv1;
        #make sure you already have this certificate pair!
 ssl_certificate /var/certs/server.crt;
        ssl_certificate_key /var/certs/server.key;
        ssl_session_cache shared:SSL:10m;

 # www-root, we're serving static files from here, accessible via https://localhost/
        location / {
            root  /var/www;
            index index.html index.htm;
        }

 # Our endpoint for tomcat reverse-proxy, assuming your endpoint java-servlet knows
 # how to handle http://localhost/gadgets  requests
        location /gadgets {
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
     proxy_set_header X-Forwarded-Proto https;
            proxy_redirect off;
            proxy_connect_timeout      240;
            proxy_send_timeout         240;
            proxy_read_timeout         240;
            # note, there is not SSL here! plain HTTP is used
    proxy_pass http://tomcat_server;
        }
     }
}

Tomcat config

And here the magic begins, the main point to not miss here is
Tomcat needs to be explicitly told that it’s being proxied through 443(SSL) port!
Here is a sample Tomcat config which is usually found at
{$CATALINA_HOME}/conf/server.xml


<?xml version='1.0' encoding='utf-8'?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!-- Note:  A "Server" is not itself a "Container", so you may not
     define subcomponents such as "Valves" at this level.
     Documentation at /docs/config/server.html
 -->
<Server port="8005" shutdown="SHUTDOWN">
  <!-- Security listener. Documentation at /docs/config/listeners.html
  <Listener className="org.apache.catalina.security.SecurityListener" />
  -->
  <!--APR library loader. Documentation at /docs/apr.html -->
  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
  <!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html -->
  <Listener className="org.apache.catalina.core.JasperListener" />
  <!-- Prevent memory leaks due to use of particular java/javax APIs-->
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />

  <!-- Global JNDI resources
       Documentation at /docs/jndi-resources-howto.html
  -->

<!--  <GlobalNamingResources>-->
    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users
    -->
<!--
    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources> -->

  <!-- A "Service" is a collection of one or more "Connectors" that share
       a single "Container" Note:  A "Service" is not itself a "Container",
       so you may not define subcomponents such as "Valves" at this level.
       Documentation at /docs/config/service.html
   -->
  <Service name="Catalina">

    <!--The connectors can use a shared executor, you can define one or more named thread pools-->
    <!--
    <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
        maxThreads="150" minSpareThreads="4"/>
    -->

    <!-- A "Connector" represents an endpoint by which requests are received
         and responses are returned. Documentation at :
         Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL HTTP/1.1 Connector on port 8080
    -->
    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443"
        proxyName="localhost"
               proxyPort="443"
                />
    <!-- A "Connector" using the shared thread pool-->
    <!--
    <Connector executor="tomcatThreadPool"
               port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    -->
    <!-- Define a SSL HTTP/1.1 Connector on port 8443
         This connector uses the JSSE configuration, when using APR, the
         connector should be using the OpenSSL style configuration
         described in the APR documentation -->
    <!--
    <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" />
    -->

    <!-- Define an AJP 1.3 Connector on port 8009 -->
  <!--  <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />-->

    <!-- An Engine represents the entry point (within Catalina) that processes
         every request.  The Engine implementation for Tomcat stand alone
         analyzes the HTTP headers included with the request, and passes them
         on to the appropriate Host (virtual host).
         Documentation at /docs/config/engine.html -->

    <!-- You should set jvmRoute to support load-balancing via AJP ie :
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
    -->
    <Engine name="Catalina" defaultHost="localhost">

      <!--For clustering, please take a look at documentation at:
          /docs/cluster-howto.html  (simple how to)
          /docs/config/cluster.html (reference documentation) -->
      <!--
      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
      -->        

      <!-- Use the LockOutRealm to prevent attempts to guess user passwords
           via a brute-force attack -->
<!--      <Realm className="org.apache.catalina.realm.LockOutRealm"> -->
        <!-- This Realm uses the UserDatabase configured in the global JNDI
             resources under the key "UserDatabase".  Any edits
             that are performed against this UserDatabase are immediately
             available for use by the Realm.  -->
<!--        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"    resourceName="UserDatabase"/>-->
<!--      </Realm>-->

      <Host name="localhost"  appBase="webapps"   unpackWARs="true" autoDeploy="true">

        <!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->

        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html
             Note: The pattern used is equivalent to using pattern="common" -->

        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log." suffix=".txt"
               pattern="%h %l %u %t "%r" %s %b" resolveHosts="false"/>

      </Host>
    </Engine>
  </Service>
</Server>



As it turned out proxyPort property was the key to proxying Tomcat via Nginx.


REFERENCES
http://webapp.org.ua/sysadmin/setting-up-nginx-ssl-reverse-proxy-for-tomcat/

Friday, December 9, 2011

Nginx PHP-FastCGI https 502 error/white pages

— SkyHi @ Friday, December 09, 2011
Server { 
      listen 1.1.1.1:443 ssl; 
      server_name website www.website; 
      access_log logs/website.access.log main; 
      error_log logs/website.error.log error; 
      keepalive_timeout 70; 

      root /srv/http/website/public_html; 
      index index.php index.html index.htm; 

      location /gallery/ { 
         auth_basic "Restricted"; 
         auth_basic_user_file /srv/http/website/htpasswd; 
      } 

      ssl_certificate /etc/ssl/private/website.pem; 
      ssl_certificate_key /etc/ssl/private/website.key; 
      ssl_session_timeout 5m; 
      ssl_protocols SSLv2 SSLv3 TLSv1; 
      ssl_ciphers HIGH:!aNULL:!MD5; 
      ssl_prefer_server_ciphers on; 

      location ~* \.(jpg|jpeg|gif|css|png|js|ico|html)$ { 
         access_log off; 
         expires max; 
      } 

      location ~ \.php$ { 
         include fastcgi.conf; 
         fastcgi_index index.php;
         ###Using http://library.linode.com/lemp-guides Howto###
         #fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock; 
         fastcgi_pass 127.0.0.1:9000; 
         ##fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name
         fastcgi_param HTTPS on; 
      } 
   }

REFERENCES
http://forum.linode.com/viewtopic.php?t=7666

Tuesday, November 1, 2011

Solution for 504 Gateway Time-out when installing magento

— SkyHi @ Tuesday, November 01, 2011
Have you tried installing magento and then its suddenly stop and display 504 Gateway Time-out on your screen? Last day my task was to install magento on my client's server and this problem occured.
I've googled this to solve my problem but unfortunately, I found nothing, maybe because this problem wasn't often to happen. So I've tried to solve it by myself and guess what? I've successfully installed the magento on my client's host!

Its just a simple trick, here's what I did.
  1. Delete all the tables created by magento in your database first;
  2. then install magento on the server where this problem will not occur, probably in your localhost server (I've install it in my localhost)
  3. then after the successful installation in your server. go to your phpmyadmin and export the tables created by the magento installation
  4. and then the last part is importing those tables to your server(the one who had a problem)

================== UPDATE ==================
After doing the steps above, probably your wondering why you are redirected to your localhost... Here's the missing step.
open the core_config_data table and change the value of web/unsecure/base_url and web/secure/base_url into your site address the only different is in secure/base_url its should be https


Now try to view your site... you will see your magento site is up and ready!

NOTE: I don't use SSL on the configuration file.


REFERENCES

Thursday, September 29, 2011

nginx and phpmyadmin alias

— SkyHi @ Thursday, September 29, 2011
Default Ubuntu nginx root:

### download the raw source code .tar.gz
location /phpmyadmin {
      #Default Ubuntu nginx root
      root /usr/share/nginx/www;
      index index.php;
        }


    location ~ ^/phpmyadmin.+.php$ {
      #Default Ubuntu nginx root
      root /usr/share/nginx/www;
      fastcgi_pass   127.0.0.1:9000;
      fastcgi_index  index.php;
      fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
      include        fastcgi_params;
        }


Configure nginx.conf to add the subdomains:

#sudo apt-get install phpmyadmin

server {
    listen    80;
    server_name     phpmyadmin.domain1.com phpmyadmin.domain2.com;
 
    location / {
         root /usr/share/phpmyadmin;
         index index.php;
    }
 
    location ~ .php$ {
      fastcgi_pass   127.0.0.1:49232; #this must point to the socket spawn_fcgi is running on.
      fastcgi_index  index.php;
      fastcgi_param  SCRIPT_FILENAME /usr/share/phpmyadmin/$fastcgi_script_name;  # same path as above
      include /etc/nginx/fastcgi_params;
    }
 }


Restart nginx to test the subdomain.

sudo /etc/init.d/nginx restart

REFERENCES

http://www.base-10.net/blog/2009/11/06/nginx-and-non-document-root-phpmyadmin/

http://blog.rubynginx.com/index.php/2010_01_25/setup-awstats-phpmyadmin-phppgadmin-with-nginx-on-ubuntu/

Wednesday, September 21, 2011

Hardening guide for Nginx 0.7.65 on RedHat 5.4 (64bit edition)

— SkyHi @ Wednesday, September 21, 2011
1..Login to the server using Root account.
 
2. Create a new account:
groupadd nginx
useradd -g nginx -d /dev/null -s /sbin/nologin nginx

 
3.Mount RHEL 5.4 DVD, and move to the RPM folder:
mount /dev/hdc /media
cd /media/Server

4.Before compiling the Nginx environment, install the following RPM:
rpm -ivh kernel-headers-2.6.18-164.el5.x86_64.rpm
rpm -ivh glibc-headers-2.5-42.x86_64.rpm
rpm -ivh glibc-devel-2.5-42.x86_64.rpm
rpm -ivh gmp-4.1.4-10.el5.x86_64.rpm
rpm -ivh libgomp-4.4.0-6.el5.x86_64.rpm
rpm -ivh gcc-4.1.2-46.el5.x86_64.rpm
rpm -ivh pcre-devel-6.6-2.el5_1.7.x86_64.rpm
rpm -ivh e2fsprogs-devel-1.39-23.el5.x86_64.rpm
rpm -ivh keyutils-libs-devel-1.2-1.el5.x86_64.rpm
rpm -ivh libsepol-devel-1.15.2-2.el5.x86_64.rpm
rpm -ivh libselinux-devel-1.33.4-5.5.el5.x86_64.rpm
rpm -ivh krb5-devel-1.6.1-36.el5.x86_64.rpm
rpm -ivh zlib-devel-1.2.3-3.x86_64.rpm
rpm -ivh openssl-devel-0.9.8e-12.el5.x86_64.rpm

 5.Download Nginx 0.7.65 from:
http://wiki.nginx.org/NginxInstall
 
6.Copy the Nginx 0.7.65 source files using PSCP (or SCP) into /tmp
 
7.Move to /tmp
cd /tmp

8.Extract the nginx-0.7.65.tar.gz file:
tar -zxvf nginx-0.7.65.tar.gz

9.Move to the Nginx source folder:
cd /tmp/nginx-0.7.65

10.Edit using VI, the file /tmp/nginx-0.7.65/src/http/ngx_http_header_filter_module.c and replace the following section, from:
static char ngx_http_server_string[] = "Server: nginx" CRLF;
static char ngx_http_server_full_string[] = "Server: " NGINX_VER CRLF;
To: 
static char ngx_http_server_string[] = "Server: Secure Web Server" CRLF;
static char ngx_http_server_full_string[] = "Server: Secure Web Server" CRLF;

11.Run the commands bellow to compile the Nginx environment:
./configure --with-http_ssl_module --without-http_autoindex_module --without-http_ssi_module
make

make install

12.Remove the Nginx source files:
rm -rf /tmp/nginx-0.7.65
rm -f /tmp/nginx-0.7.65.tar.gz

13.Remove Default Content
rm -rf /usr/local/nginx/html

14.Updating Ownership and Permissions on Nginx folders:
chown -R root:root /usr/local/nginx
chmod 750 /usr/local/nginx/sbin/nginx
chmod -R 640 /usr/local/nginx/conf
chmod -R 770 /usr/local/nginx/logs

15.Create folder for the web content:
mkdir -p /www
 
16.Updating Ownership and Permissions on the web content folder:
chown -R root /www
chmod -R 775 /www

 
17.Edit using VI the file /usr/local/nginx/conf/nginx.conf and change the following settings:
From:
#user nobody;To:
user nginx nginx;
From:
#error_log logs/error.log notice;To:
error_log logs/error.log notice;

From:
server_name localhost;To:
server_name Server_FQDN;

From:
root html;To:
root /www;
 
18.Add the following sections to the end of the /usr/local/nginx/conf/nginx.conf file:
server_tokens off;
client_body_buffer_size 1K;
client_header_buffer_size 1k;
client_max_body_size 1k;
large_client_header_buffers 2 1k;
client_body_timeout 10;
client_header_timeout 10;
send_timeout 10;

19.Create using VI, the file /etc/init.d/nginx with the following content:
#!/bin/sh
#
# nginx - this script starts and stops the nginx daemon
#
# chkconfig: - 85 15
# description: Nginx is an HTTP(S) server, HTTP(S) reverse \
# proxy and IMAP/POP3 proxy server
# processname: nginx
# config: /etc/nginx/nginx.conf
# config: /etc/sysconfig/nginx
# pidfile: /var/run/nginx.pid

# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0

nginx="/usr/local/nginx/sbin/nginx"
prog=$(basename $nginx)

NGINX_CONF_FILE="/usr/local/nginx/conf/nginx.conf"

[ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx

lockfile=/var/lock/subsys/nginx

start() {
[ -x $nginx ] exit 5
[ -f $NGINX_CONF_FILE ] exit 6
echo -n $"Starting $prog: "
daemon $nginx -c $NGINX_CONF_FILE
retval=$?
echo
[ $retval -eq 0 ] && touch $lockfile
return $retval
}

stop() {
echo -n $"Stopping $prog: "
killproc $prog -QUIT
retval=$?
echo
[ $retval -eq 0 ] && rm -f $lockfile
return $retval
}

restart() {
configtest return $?
stop
sleep 1
start
}

reload() {
configtest return $?
echo -n $"Reloading $prog: "
killproc $nginx -HUP
RETVAL=$?
echo
}

force_reload() {
restart
}

configtest() {
$nginx -t -c $NGINX_CONF_FILE
}

rh_status() {
status $prog
}

rh_status_q() {
rh_status >/dev/null 2>&1
}

case "$1" in
start)
rh_status_q && exit 0
$1
;;
stop)
rh_status_q exit 0
$1
;;
restartconfigtest)
$1
;;
reload)
rh_status_q exit 7
$1
;;
force-reload)
force_reload
;;
status)
rh_status
;;
condrestarttry-restart)
rh_status_q exit 0
;;
*)
echo $"Usage: $0 {startstopstatusrestartcondrestarttry-restartreloadforce-reloadconfigtest}"
exit 2
esac

20.Change the permissions of the file /etc/init.d/nginx
chmod +x /etc/init.d/nginx
 
21.To start Nginx service at server start-up, run the command:
chkconfig nginx on

22.To manually start the Nginx service, use the command:
/etc/init.d/nginx start

23.Uninstall the following RPM:
rpm -e gcc-4.1.2-46.el5
rpm -e libgomp-4.4.0-6.el5
rpm -e gmp-4.1.4-10.el5
rpm -e glibc-devel-2.5-42
rpm -e glibc-headers-2.5-42
rpm -e kernel-headers-2.6.18-164.el5



REFERENCES
http://security-24-7.com/hardening-guide-for-nginx-0-7-65-on-redhat-5-4-64bit-edition/
http://www.howtoforge.com/install-nginx-on-centos-5.5-with-ssl-pcre-geoip-zlib-gzip-and-dav-support

Saturday, June 18, 2011

A Django setup using Nginx and Gunicorn

— SkyHi @ Saturday, June 18, 2011
This is a howto on setting up Django on a Linux (Ubuntu) system using Nginx as a reverse proxy and Gunicorn as a Django service.


Django, Gunicorn, Nginx

The conventional way to run Django in production these days is using Apache2 and mod_wsgi. While there’s nothing wrong with that approach, I prefer Nginx. I also like to be able to control Django server separately from the web server.

There are several production-ready servers for Django. The best seem to be Gunicorn and uWSGI, and Gunicorn seems the best supported and most active project.

When running Django server separately from the web server, we need a way to start, stop and restart the Django server. A popular way for doing it in Django world is Supervisor, altough, for Ubuntu users, Upstart might be less hassle.

You probably already have a Django project you want to deploy, but for completenes’ sake, the steps here will use an empty toy “Hello World” Django project:
Preparation

First things first – you are using virtualenv, right? If not, you should.

virtualenv --no-site-packages test
cd test
source bin/activate
pip install gunicorn django
django-admin.py createproject hello
cd hello
# to test the base setup works
python manage.py runserver 0.0.0.0:8000

Gunicorn

Testing Django with Gunicorn is as simple as:

gunicorn_django -b 0.0.0.0:8000

For production, we might want a bit more options, and we want to make sure the server is executing in the correct environment. The easiest way is to create a shell script to set it all up:

#!/bin/bash
set -e
LOGFILE=/var/log/gunicorn/hello.log
NUM_WORKERS=3
# user/group to run as
USER=your_unix_user
GROUP=your_unix_group
cd /path/to/test/hello
source ../../bin/activate
exec /path/to/test/bin/gunicorn_django -w $NUM_WORKERS \
--user=$USER --group=$GROUP --log-level=debug \
--log-file=$LOGFILE 2>>$LOGFILE

The number of workers is number of worker processes that will serve requests. You can set it as low as 1 if you’re on a small VPS. A popular formula is 1 + 2 * number_of_cpus on the machine (the logic being, half of the processess will be waiting for I/O, such as database). YMMV.

Don’t forget to mark the script as executable (chmod ug+x script.sh). You can run it from the command line for testing. Note that Gunicorn by default uses 127.0.0.1:8000 address (the same as Django debug server), which is fine if Nginx is on the same machine – you usually don’t want to have it wide open to anyone, and instead let Nginx handle incoming connections.

If you want to run several Django servers on the same machine, just make sure each uses a different port number.
Supervisor

Supervisor has extensive documentation, and this blog post is big already, so I’ll just point you to the official docs. The config file for running our server (/etc/supervisor/cont.d/hello.conf on Debian/Ubuntu) should look like this:

[program:hello]
directory = /path/to/test/hello/
user = your_unix_user
command = /path/to/test/hello/script.sh
stdout_logfile = /path/to/logfile.log
stderr_logfile = /path/to/logfile.log

Test it with supervisortcl {start,status,stop} hello (as root).
Upstart

Ubuntu alternative is Upstart, which has a similar config file (/etc/init/hello.conf). An example:

description "Test Django instance"
start on runlevel [2345]
stop on runlevel [06]
respawn
respawn limit 10 5
exec /path/to/test/hello/script.sh

Test it with service hello {start,status,stop} (as root).
Nginx

If you don’t have it set up, you should also install Nginx. The install procedure varies from system to system. On Debian and Ubuntu systems, it’s as simple as apt-get install nginx, and other Linux distributions usually have equivalent commands.

Nginx is mostly a drop-in replacement for Apache for serving static files, though there are some things to set up if you need to run PHP code as well.

For our setup, we need Nginx to serve as the reverse proxy for the upstream server(s). To do so, we add a server section to the config file:

server {
listen 80;
server_name example.com;
# no security problem here, since / is alway passed to upstream
root /path/to/test/hello;
# serve directly - analogous for static/staticfiles
location /media/ {
# if asset versioning is used
if ($query_string) {
expires max;
}
}
location /admin/media/ {
# this changes depending on your python version
root /path/to/test/lib/python2.6/site-packages/django/contrib;
}
location / {
proxy_pass_header Server;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Scheme $scheme;
proxy_connect_timeout 10;
proxy_read_timeout 10;
proxy_pass http://localhost:8000/;
}
# what to serve if upstream is not available or crashes
error_page 500 502 503 504 /media/50x.html;
}

Ubuntu and Debian systems keep Nginx config files in same layout as for Apache, so the above cold be added to /etc/nginx/sites-available/hello (and enabled by symlinking from sites-enabled directory). Use nginx -t for config test and nginx -s reload to reload the configuration.
That’s it

And that’s it. The services are really quite simple to set up once you know what goes where, the setup is flexible and performant, and the server environments are isolated so it’s possible to host many different services with varying requirements on the same machine.

REFERENCES
http://senko.net/en/django-nginx-gunicorn/

Monday, May 30, 2011

How to handle 1000′s of concurrent users on a 360MB VPS

— SkyHi @ Monday, May 30, 2011
There has been some recent confusion about how much memory you need in a web server to handle a huge number of concurrent requests. I also made a performance claim on the STS list that got me an unusual number of private emails.

Here’s how you run a highly concurrent website on a shoe-string budget:
The first thing you’ll do is get a Linode server because they have the fastest CPU and disk.
Install Apache with your web application running under mod_php, mod_perl or some other persistence engine for your language. Then you get famous and start getting emails about people not being able to access your website.

You increase the number of Apache threads or processes (depending on which Apache MPM you’re using) until you can’t anymore because you only have 360MB of memory in your server.
Then you’ll lower the KeepaliveTimeout and eventually disable Keepalive so that more users can access your website without tying up your Apache processes. Your users will slow down a little because they now have to re-establish a new connection for every piece of your website they want to fetch, but you’ll be able to serve more of them.

But as you scale up you will get a few more emails about your server being down. Even though  you’ve disabled keepalive it still takes time for each Apache child to send data to users, especially if they’re on slow connections or connections with high latency. Here’s what you do next:

Install Nginx on your new Linode box and get it to listen on Port 80. Then reconfigure Apache so that it listens on another port – say port 81 – and can only be accessed from the local machine. Configure Nginx as a reverse proxy to Apache listening on port 81 so that it sits in front of Apache like so:

YourVisitor <—–> Nginx:Port80 <—–> Apache:Port81
Enable Keepalive on Nginx and set the Keepalive timeout as high as you’d like. Disable Keepalive on Apache – this is just-in-case because Nginx’s proxy engine doesn’t support Keepalive to the back-end servers anyway.

The 10 or so Apache children you’re running will be getting requests from a client (Nginx) that is running locally. Because there is zero latency and a huge amount of bandwidth (it’s a loopback request), the only time Apache takes to handle the request is the amount of CPU time it actually takes to handle the request. Apache children are no longer tied up with clients on slow connections. So each request is handled in a few microseconds, freeing up each child to do a hell of a lot more work.

Nginx will occupy about 5 to 10 Megs of Memory. You’ll see thousands of users concurrently connected to it. If you have Munin loaded on your server check out the netstat graph. Bitchin isn’t it? You’ll also notice that Nginx uses very little CPU – almost nothing in fact. That’s because Nginx is designed using a single threaded model where one thread handles a huge number of connections. It can do this with little CPU usage because it uses a feature in the Linux kernel called epoll().

Footnotes:
Lack of time forced me to leave out all explanations on how to install and configure Nginx (I’m assuming you know Apache already) – but the Nginx Wiki is excellent, even if the Russain translation is a little rough.
I’ve also purposely left out all references to solving disk bottlenecks (as I’ve left out a discussion about browser caching) because there has been a lot written about this and depending on what app or app-server you’re running, there are some very standard ways to solve IO problems already. e.g. Memcached, the InnoDB cache for MySQL, PHP’s Alternative PHP Cache, perstence engines that keep your compiled code in memory, etc..etc..

This technique works to speed up any back-end application server that uses a one-thread-per-connection model. It doesn’t matter if it’s Ruby via FastCGI, Mod_Perl on Apache or some crappy little Bash script spitting out data on a socket.

This is a very standard config for most high traffic websites today. It’s how they are able to leave keepalive enabled and handle a huge number of concurrent users with a relatively small app server cluster.  Lighttpd and Nginx are the two most popular free FSM/epoll web servers out there and Nginx is the fastest growing, best designed (IMHO) and the one I use to serve 400 requests per second on a small Apache cluster. It’s also what guys like WordPress.com use.


Very high performance web servers

Have you ever tried to get Apache to handle 10,000 concurrent connections? For example, you have a very busy website and you enable keepalive on your web server. Then you set the timeout to something high like 300 seconds for ridiculously slow clients (sounds crazy but I think that’s Apache’s default). All of a sudden when you run netstat it tells you that you have thousands of clients with established connections to your machine.

Apache can’t handle 10,000 connections efficiently because it uses a one-thread-per-connection model (or if you’re using prefork then one process per connection).
If you want to allow your clients to use keepalive on your very busy website you need to use a server that uses an event notification model. That means that you have a single thread or process that manages thousands of sockets or connections. The sockets don’t block the execution of the thread but instead sit quietly until something happens and then have a way of notifying the thread that something happened and it better come take a look.

Most of us use Linux these days – of course there are the BSD die hards but whatever. The linux kernel 2.6 introduced something called epoll that is an event notification system for applications that want to manage lots of file descriptors without blocking execution and be notified when something changes.
Both lighttpd and nginx are two very fast web servers that use epoll and a non-blocking event notification model to manage thousands of connections with a single thread and just a few megs of ram (ram consumption is the real reason you can’t use apache for high concurrency). You can also spawn more than one thread on both servers if you’d like to have them use more than one processor or cpu core.

I used to use lighttpd 1.4.x but it’s configuration really sucks because it’s so inflexible. I love nginx’s configuration because it’s very intuitive and very flexible. It also has some very cool modules including an experimental embedded perl module. The performance I’m getting out of it is nothing short of spectacular. I run 8 worker processes and each process consumes about 7 megs of RAM with a few modules loaded.
So my config looks like:
request ==> nginx_with_keepalive –> apache/appserver_nokeepalive

If you’d like to read more about server models for handling huge numbers of clients, check out Dan Kegel’s page on the so called c10k problem where he documents a few other event models for servers and has a history lesson on event driven IO.
Also, if you’re planning on running a high traffic server with high concurrency you should probably optimize your IP stack – here are a few suggestions I made a while back on how to do that.

REFERENCES
http://markmaunder.com/2009/how-to-handle-1000s-of-concurrent-users-on-a-360mb-vps/
http://news.ycombinator.com/item?id=2594050 
http://markmaunder.com/category/scaling/

Friday, April 8, 2011

Setting up PHP-FastCGI and nginx? Don’t trust the tutorials: check your configuration!

— SkyHi @ Friday, April 08, 2011
Summary

Several days ago, I had to deal with a compromised web application: an attacker had somehow managed to upload PHP backdoor scripts onto the application’s server. Thanks to some log file sleuthing and Google searches, I was quickly able to identify what had allowed the attack: a misconfigured nginx server can allow non-PHP files to be executed as PHP. As I researched the vulnerability a bit more, however, I realized that many of the nginx / PHP setup tutorials found on the Internet suggest that people use vulnerable configurations.
The misconfiguration

As I mentioned, the attack was made possible by a very simple misconfiguration between nginx and php-fastcgi. Consider the configuration block below, taken from a tutorial at http://library.linode.com/web-servers/nginx/php-fastcgi/fedora-14:

server {
   listen 80;
   server_name www.bambookites.com bambookites.com;
   access_log /srv/www/www.bambookites.com/logs/access.log;
   error_log /srv/www/www.bambookites.com/logs/error.log;
   root /srv/www/www.bambookites.com/public_html;
 
   location / {
       index  index.html index.htm index.php;
   }
 
   location ~ \.php$ {
       include /etc/nginx/fastcgi_params;
       fastcgi_pass  127.0.0.1:9000;
       fastcgi_index index.php;
       fastcgi_param  SCRIPT_FILENAME /srv/www/www.bambookites.com/public_html$fastcgi_script_name;
   }
}

It may not be immediately clear, but this configuration block allows for arbitrary code execution under certain circumstances (and I don’t just mean if an attacker can upload a file ending in .php: that kind of vulnerability is independent of the web server used).

Consider a situation where remote users can upload their own pictures to the site. Lets say that an attacker uploads an image to http://www.bambookites.com/uploads/random.gif. What happens, given the server block above, if the attacker then browses to http://www.bambookites.com/uploads/random.gif/somefilename.php?

1. nginx will look at the URL, see that it ends in .php, and pass the path along to the PHP fastcgi handler.
2. PHP will look at the path, find the .gif file in the filesystem, and store /somefilename.php in $_SERVER['PATH_INFO'], executing the contents of the GIF as PHP.

Since GIFs and other image types can contain arbitrary content within them, it’s possible to craft a malicious image that contains valid PHP. That is how the attacker was able to compromise the server: he or she uploaded a malicious image containing PHP code to the site, then browsed to the file in a way that caused it to be parsed as PHP.

This issue was first discovered almost a year ago. The original report can be found in Chinese at http://www.80sec.com/nginx-securit.html. There is also a discussion about it on the nginx forums.

This issue can be mitigated in a number of ways, but there are downsides associated with each of the possibilities:

1. Set cgi.fix_pathinfo to false in php.ini (it’s set to true by default). This change appears to break any software that relies on PATH_INFO being set properly (eg: WordPress).
2. Add try_files $uri =404; to the location block in your nginx config. This only works when nginx and the php-fcgi workers are on the same physical server.
3. Add a new location block that tries to detect malicious URLs. Unfortunately, detecting based on the URL alone is impossible: files don’t necessarily need to have extensions (eg: README, INSTALL, etc).
4. Explicitly exclude upload directories using an if statement in your location block. The disadvantage here is the use of a blacklist: you have to keep updating your nginx configuration every time you install a new application that allows uploads.
5. Don’t store uploads on the same server as your PHP. The content is static anyway: serve it up from a separate (sub)domain. Of course, this is easier said than done: not all web applications make this easy to do.

[Note: If anyone is aware of other possible solutions (or workarounds to improve the effectiveness of these solutions), please let me know and I'll add them here!]
Tutorials

Now, the configuration file for the compromised server wasn’t written by hand. When the server was set up, the configuration was created based on suggestions found on the Internet. I assume that other people use tutorials and walkthroughs for setting up their servers as well. Unfortunately, most of the documentation for configuring nginx and php-fastcgi still encourages people to set up their servers in a vulnerable way.

1. The default configuration file for nginx suggests the use of an insecure location block (source).
2. The nginx wiki supplies potentially dangerous examples as well. To be fair, some pages do encourage users to explicitly prevent PHP execution in upload directories [Edit: and in the Pitfalls document, which everyone should read before configuring nginx]. However, other pages ignore the issue entirely.
3. The Linode Library has an extensive collection of documents, including a number that talk about setting up nginx and PHP on various OSes. Unfortunately, all of those tutorials suggest using a vulnerable configuration for PHP. I’ve contacted the documentation team at Linode and I’m waiting to hear back from them.
4. Howto Forge has several tutorials (1, 2) which show up when searching Google for “nginx php setup.” These tutorials also suggest the use of a vulnerable configuration.
5. People have written many tutorials on blogs and other sites (ie: 1, 2). A number of these tutorials encourage using the same vulnerable configuration.

In contrast, codex.wordpress.org provides an excellent configuration example that warns people about and mitigates the vulnerability. I’ve reproduced the relevant portion below:

# Pass all .php files onto a php-fpm/php-fcgi server.
location ~ \.php$ {
   # Zero-day exploit defense.
   # http://forum.nginx.org/read.php?2,88845,page=3
   # Won't work properly (404 error) if the file is not stored on this
server, which is entirely possible with php-fpm/php-fcgi.
   # Comment the 'try_files' line out if you set up php-fpm/php-fcgi on
another machine.  And then cross your fingers that you won't get hacked.
   try_files $uri =404;
 
   fastcgi_split_path_info ^(.+\.php)(/.+)$;
   include fastcgi_params;
   fastcgi_index index.php;
   fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
#    fastcgi_intercept_errors on;
   fastcgi_pass php;
}

Conclusion

1.If you run PHP on an nginx web server, check your configuration and update if necessary.
2.If you’re doing a security audit on a PHP application running on an nginx web server, remember to test for this configuration.
3. If you run across a tutorial that is out of date, please point the author to this post.
4.If you know of a way to better secure nginx / php-fastcgi, let me know!

================================================================================
Passing Every ~ \.php$ request to to PHP

It is common with Nginx to pass every URI ending in .php to the PHP parser, if using a default PHP build this might lead to security issues. Nginx is a reverse proxy and as such does not have a concept of file unless you specifically tell it to. So if your configuration looks like this.

location ~* \.php$ {
fastcgi_pass backend;
}

Then you are probably vulnerable. The issue is that PHP when configured incorrectly tries to guess which file you want to execute if the full path does not lead to a file. Say you have the URI /forum/avatar/1232.jpg/index.php. The File does not exist but /forum/avatar/1232.jpg does, Nginx does not care and gladly passes the request to PHP as you have instructed it to, PHP sees the file does not exist and that /forum/avatar/1232.jpg does and chooses to execute this. If this file is a user upload it might contain embedded PHP code and you are now vulnerable to arbitrary code execution.

The solution is to set cgi.fix_pathinfo=0 in the php.ini file, this causes PHP to try the literal path given and will thus not execute the jpg file. If for backwards compatibility reasons you cannot change this setting you need to ensure that Nginx is passing PHP an actual file or specifically disable PHP access to any directory containing user uploads.

REFERENCES
https://nealpoole.com/blog/2011/04/setting-up-php-fastcgi-and-nginx-dont-trust-the-tutorials-check-your-configuration/

http://wiki.nginx.org/Pitfalls#Passing_Every_.7E_.5C.php.24_request_to_to_PHP

Monday, March 7, 2011

An Nginx load balancing, caching, reverse proxy

— SkyHi @ Monday, March 07, 2011
Continuing the evaluation of clustering our main website on Linux KVM virtual machines, below is our test nginx reverse proxy cache config.

The back end is 2 Apache servers, one on the local host and one on a remote host.

The main site files live on NFS. We set up the cache file system in tmpfs. Our site is dynamic using PHP for most pages. The caching appears to eliminate most of the PHP overhead and keeps the number of Apache processes at bay, reducing overall RAM needed on the VM's. We think this configuration will allow us to use 2 VM's and still end up with fewer resources needed than our old dual CPU 3GB RAM physical web server.

Our nginx disk cache file system was set to 50 Meg for testing.

/etc/fstab:

tmpfs /var/lib/nginx tmpfs size=50M,uid=33 0 0

We used the main nginx config file to define default caching parameters.

/etc/nginx/nginx.conf:

# Two processes work well for a single CPU
  user www-data;
  worker_processes  2;

  error_log  /var/log/nginx/error.log;
  pid        /var/run/nginx.pid;

  events {
     worker_connections  1024;
     use epoll;
  }

  http {
    include       /etc/nginx/mime.types;

    # Nginx does the logging
    access_log /var/log/nginx/access.log;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;
    tcp_nodelay        on;

    server_names_hash_bucket_size 64;

    # Have nginx do the compression, turn off Apache's mod_deflate
    gzip                on;
    gzip_comp_level     1;
    gzip_disable        msie6;
    gzip_proxied        any;

    # text/html mime type is automatically included for gzip, have to add the rest
    gzip_types          text/plain text/css application/x-javascript text/xml application/xml application/rss+xml text/javascript;

    # Default cache parameters for use by virtual hosts
    # Set the cache path to tmpfs mounted disk, and the zone name
    # Set the maximum size of the on disk cache to less than the tmpfs file system size
    proxy_cache_path  /var/lib/nginx/cache  levels=1:2  keys_zone=adams:10m max_size=45m;
    proxy_temp_path   /var/lib/nginx/proxy;

    # Putting the host name in the cache key allows different virtual hosts to share the same cache zone
    proxy_cache_key "$scheme://$host$request_uri";
    proxy_redirect off;

    # Pass some client identification headers back to Apache  
    proxy_set_header        Host            $host;
    proxy_set_header        X-Real-IP       $remote_addr;
    proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;

    # Cache different return codes for different lengths of time 
    # We cached normal pages for 10 minutes
    proxy_cache_valid 200 302  10m;
    proxy_cache_valid 404      1m;

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
  }


Following is an nginx virtual host config with the reverse proxy cache enabled. The host name of the server is megalon-test, the website virtual host name is adams-bal. The proxy also handles SSL, and can selectively decide what to cache and for how long.

/etc/nginx/sites-enabled/adams-bal:
# The Apache load balancing proxy targets for port 80 traffic
  upstream adams-bal {
    server 127.0.0.1;
    server 192.156.134.101;
  }
  # Proxies for port 443 traffic
  upstream sadams-bal {
    server 127.0.0.1:443;
    server 192.156.134.101:443;
  }

  # Virtual host definition 
  server {
    listen megalon-test.adams.edu:80;
    server_name adams-bal.adams.edu;
    error_page 404 = /about/searchasc/notfound.php;

    # The default location definition, we do some rewrites via nginx as well
    location / {
      # We do some rewrites via nginx as well
      include adams-rewrite;

      # Do caching using the adams zone, with the settings defined in /etc/nginx.conf   
      proxy_cache adams;

      # If it's not in the cache pass back to the adams-bal load balanced targets defined above 
      proxy_pass  http://adams-bal$request_uri;
    }

    # Serve static files directly via nginx, set an expires header for the browser 
    location ~* \.(pdf|css|js|png|gif|jpg|ico|swf|mov|doc|pdf|xls|ppt|docx|pptx|xlsx)$ {
      root /home/www/adams;
      expires max;
    }
  }

  # The SSL virtual host definition, setting up the SSL proxy end to middle to end.
  # client -> SSL -> nginx -> SSL -> Apache
  server {
    listen megalon-test.adams.edu:443;
    server_name adams-bal.adams.edu;

    # We use a domain wild card cert, under nginx the intermediate lives
    # in the same file as the domain cert
    ssl  on;
    ssl_certificate  adams.edu_wildcard_chain.crt;
    ssl_certificate_key  adams.edu_wildcard.key;
    ssl_session_timeout  5m;
    ssl_protocols  SSLv2 SSLv3 TLSv1;
    ssl_ciphers  ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
    ssl_prefer_server_ciphers   on;

    # Don't cache ssl pages, just proxy them
    location / {
      proxy_pass  https://sadams-bal$request_uri;
    }
  }


The Apache back end configuration on Ubuntu uses a couple of files, here are configs for the localhost server, running on the same VM as nginx.

/etc/apache2/ports.conf:
# Set up name virtual host for localhost port 80
  NameVirtualHost 127.0.0.1:80
  Listen 127.0.0.1:80

  # Set up server for SSL
  
  # SSL name based virtual hosts are not yet supported, therefore no
  # NameVirtualHost statement here

    # SSL for adams-bal
    Listen 127.0.0.1:443

    # SSL for another virtual host through nginx
    Listen 127.0.0.2:443
  


The Apache virtual host definition.

/etc/apache2/sites-enabled/adams-bal:
# For port 80, server name the same as nginx
  
    DocumentRoot /home/www/adams
    ServerName adams-bal.adams.edu
  

  
    Options -Indexes FollowSymLinks
    AllowOverride AuthConfig Limit 
    
      Order allow,deny
      Allow from all
     
  

  # For SSL, notice Apache requires the intermediate cert in a separate file 
  
    DocumentRoot /home/www/adams
    ServerName adams-bal.adams.edu
    SSLEngine on
    SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP
    SSLCertificateFile /etc/nginx/adams.edu_wildcard.crt
    SSLCertificateKeyFile /etc/nginx/adams.edu_wildcard.key
    SSLCertificateChainFile /etc/nginx/GoDaddy_Intermediate.crt
 


The Apache configs on the remote host are almost identical, using the actual server IP address rather than localhost. One can envision a swarm of VM's talking to the proxy through a virtual network on private IP's...

The performance and resource usage is very good due to the ram disk caching. We did notice a slow down when the nginx cache filled during a site crawl from a search engine, so make sure there is enough cache to cover the site. Some sites may need a mix of on disk and ram disk caches.


REFERENCES:
http://staff.adams.edu/~cdmiller/posts/nginx-reverse-proxy-cache/

load balancer http and https with Nginx

— SkyHi @ Monday, March 07, 2011
So lets say that you want to make your own simple load balancer, to round robin requests between multiple servers; those servers will be running their own web server software which will be doing a reverse proxy to load balance rails requests amongst mongrel, thin, ebb etc. (if its a rails app).
The requirements are that the main load balancer needs to handle HTTP and HTTPS requests and it should automatically add or remove cluster nodes from the server pool as they become available, or unavailable. We can accomplish this by using the Nginx webserver.
We setup Nginx as you normally would perhaps using 6 or 7 workers, and you can setup the load balancing in the vhost config file. Instead of creating server pools of backend mongrels as you may have seen before, just make the items in the pool each point to a different server. In this example we actually store the IP locations in our /etc/hosts file.


upstream backend {
  server web1:80;
  server web2:80;
  server web3:80;
  server web4:80;
  server web5:80;
}

upstream secure {
  server web1:443;
  server web2:443;
  server web3:443;
  server web4:443;
  server web5:443;
}



server {

  listen 80;

  server_name www.domain.com domain.com;

  location / {

    # needed to forward user's IP address to rails
    proxy_set_header  X-Real-IP  $remote_addr;

    # needed for HTTPS
    proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect false;
    proxy_max_temp_file_size 0;

    proxy_pass http://backend;

  } #end location

} #end server



server {

  listen 443;

  ssl on;
  ssl_certificate /etc/ssl/ssl.pem/www.domain.com.pem;
  ssl_certificate_key /etc/ssl/ssl.key/www.domain.com.key;

  server_name www.domain.com domain.com;

  location / {

    # needed to forward user's IP address to rails
    proxy_set_header  X-Real-IP  $remote_addr;

    # needed for HTTPS
    #proxy_set_header X_FORWARDED_PROTO https;

    proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect false;
    proxy_max_temp_file_size 0;

    proxy_pass https://secure;

  } #end location


} #end server

Thats all there is to it, now this box will act as a front end load balancer in front of a number of other servers, adding a server is just 1 entry in each of the pools.

Note, be sure your log levels for Nginx are set to error only, since this Nginx instance will be handling a lot of traffic the logs can fill up really fast.


REFERENCES
http://parkersmithsoftware.com/blog/post/14-create-a-simple-load-balancer-with-nginx
http://serverfault.com/questions/10854/nginx-https-serving-with-same-config-as-http

Using Nginx as a load balancer

— SkyHi @ Monday, March 07, 2011
Here’s a look at how nginx does basic load balancing :
upstream  yoursite  {
   server   yoursite1.yoursite.com;
   server   yoursite2.yoursite.com;
}

server {
   server_name www.yoursite.com;
   location / {
      proxy_pass  http://yoursite;
   }
}
This configuration will send 50% of the requests for www.yoursite.com to yoursite1.yoursite.com and the other 50% to yoursite2.yoursite.com.

ip_hash

You can specify the ip_hash directive that guarantees the client request will always be transferred to the same server.
If this server is considered inoperative, then the request of this client will be transferred to another server.
upstream  yoursite  {
   ip_hash;
   server   yoursite1.yoursite.com;
   server   yoursite2.yoursite.com;
}

down

If one of the servers must be removed for some time, you must mark that server as down.
upstream  yoursite  {
   ip_hash;
   server   yoursite1.yoursite.com down;
   server   yoursite2.yoursite.com;
}

weight

If you add a weight tag onto the end of the server definition you can modify the percentages of the requests send to the servers.
When there’s no weight set, the weight is equal to one.
upstream  yoursite  {
   server   yoursite1.yoursite.com weight=4;
   server   yoursite2.yoursite.com;
}
This configuration will send 80% of the requests to yoursite1.yoursite.com and the other 20% to yoursite2.yoursite.com.
note: It’s not possible to combine ip_hash and weight directives.

max_fails and fail_timeout

max_fails is a directive defining the number of unsuccessful attempts in the time period defined by fail_timeout before the server is considered inoperative. If not set, the number of attempts is one. A value of 0 turns off this check.
If fail_timeout is not set the time is 10 seconds.
upstream  yoursite  {
   server   yoursite1.yoursite.com;
   server   yoursite2.yoursite.com max_fails=3  fail_timeout=30s;
}
In this configuration nginx will consider yoursite2.yoursite.com as inoperative if a request fails 3 times with a 30s timeout.

backup

If the non-backup servers are all down or busy, the server(s) with the backup directive will be used.
upstream  yoursite  {
   server   yoursite1.yoursite.com max_fails=3;
   server   yoursite2.yoursite.com max_fails=3;
   server   yoursite3.yoursite.com backup;
}
This configuration will send 50% of the requests for www.yoursite.com to yoursite1.yoursite.com and the other 50% to yoursite2.yoursite.com.
If yoursite1.yoursite.com and yoursite2.yoursite.com both fails 3 times the requests will be send to yoursite3.yoursite.com.

REFERENCES
http://mickeyben.com/2009/12/30/using-nginx-as-a-load-balancer.html

CentOS / Redhat Linux: Install Keepalived To Provide IP Failover For Web Cluster

— SkyHi @ Monday, March 07, 2011
Keepalived provides a strong and robust health checking for LVS clusters. It implements a framework of health checking on multiple layers for server failover, and VRRPv2 stack to handle director failover. How do I install and configure Keepalived for reverse proxy server such as nginx or lighttpd?

If your are using a LVS director to loadbalance a server pool in a production environment, you may want to have a robust solution for healthcheck & failover. This will also work with reverse proxy server such as nginx.

Our Sample Setup

Internet--
         |
    =============
    | ISP Router|
    =============
         |
         |
         |      |eth0 -> 192.168.1.11 (connected to lan)
         |-lb0==|
         |      |eth1 -> 202.54.1.1 (vip master)
         |
         |      |eth0 -> 192.168.1.10 (connected to lan)
         |-lb1==|
                |eth1 -> 202.54.1.1 (vip backup)
Where,
  • lb0 - Linux box directly connected to the Internet via eth1. This is master load balancer.
  • lb1 - Linux box directly connected to the Internet via eth1. This is backup load balancer. This will become active if master networking failed.
  • 202.54.1.1 - This ip moves between lb0 and lb1 server. It is called virtual IP address and it is managed by keepalived.
  • eth0 is connected to LAN and all other backend software such as Apache, MySQL and so on.
You need to install the following softwares on both lb0 and lb1:
  • keepalived for IP failover.
  • iptables to filter traffic
  • nginx or lighttpd revers proxy server.
DNS settings should be as follows:
  1. nixcraft.in - Our sample domain name.
  2. lb0.nixcraft.in - 202.54.1.11 (real ip assigned to eth1)
  3. lb1.nixcraft.in - 202.54.1.12 (real ip assigned to eth1)
  4. www.nixcraft.in - 202.54.1.1 (VIP for web server) do not assign this IP to any interface.

Install Keepalived

Visit keepalived.org to grab latest source code. You can use the wget command to download the same (you need to install keepalived on both lb0 and lb1):
# cd /opt
# wget http://www.keepalived.org/software/keepalived-1.1.19.tar.gz
# tar -zxvf keepalived-1.1.19.tar.gz
# cd keepalived-1.1.19

Install Kernel Headers

You need to install the following packages:
  1. Kernel-headers - includes the C header files that specify the interface between the Linux kernel and userspace libraries and programs. The header files define structures and constants that are needed for building most standard programs and are also needed for rebuilding the glibc package.
  2. kernel-devel - this package provides kernel headers and makefiles sufficient to build modules against the kernel package.
Make sure kernel-headers and kernel-devel packages are installed. If not type the following install the same:
# yum -y install kernel-headers kernel-devel

Compile keepalived

Type the following command:
# ./configure --with-kernel-dir=/lib/modules/$(uname -r)/build
Sample outputs:
checking for gcc... gcc
checking for C compiler default output file name... a.out
checking whether the C compiler works... yes
checking whether we are cross compiling... no
checking for suffix of executables...
checking for suffix of object files... o
...
.....
..
config.status: creating keepalived/check/Makefile
config.status: creating keepalived/libipvs-2.6/Makefile

Keepalived configuration
------------------------
Keepalived version       : 1.1.19
Compiler                 : gcc
Compiler flags           : -g -O2
Extra Lib                : -lpopt -lssl -lcrypto
Use IPVS Framework       : Yes
IPVS sync daemon support : Yes
Use VRRP Framework       : Yes
Use Debug flags          : No
Compile and install the same:
# make && make install

Create Required Softlinks

Type the following commands to create service and run it at RHEL / CentOS run level #3 :
# cd /etc/sysconfig
# ln -s /usr/local/etc/sysconfig/keepalived .
# cd /etc/rc3.d/
# ln -s /usr/local/etc/rc.d/init.d/keepalived S100keepalived
# cd /etc/init.d/
# ln -s /usr/local/etc/rc.d/init.d/keepalived .

Configuration

Your main configuration directory is located at /usr/local/etc/keepalived and configuration file name is keepalived.conf. First, make backup of existing configuration:
# cd /usr/local/etc/keepalived
# cp keepalived.conf keepalived.conf.bak

Edit keepalived.conf as follows on lb0:
vrrp_instance VI_1 {
        interface eth0
        state MASTER
        virtual_router_id 51
        priority 101
        authentication {
            auth_type PASS
            auth_pass Add-Your-Password-Here
        }
        virtual_ipaddress {
                202.54.1.1/29 dev eth1
        }
}
Edit keepalived.conf as follows on lb1 (note priority set to 100 i.e. backup load balancer):
vrrp_instance VI_1 {
        interface eth0
        state MASTER
        virtual_router_id 51
        priority 100
        authentication {
            auth_type PASS
            auth_pass Add-Your-Password-Here
        }
        virtual_ipaddress {
                202.54.1.1/29 dev eth1
        }
}
Save and close the file. Finally start keepalived on both lb0 and lb1 as follows:
# /etc/init.d/keepalived start

Verify: Keepalived Working Or Not

/var/log/messages will keep track of VIP:
# tail -f /var/log/messages
Sample outputs:
Feb 21 04:06:15 lb0 Keepalived_vrrp: Netlink reflector reports IP 202.54.1.1 added
Feb 21 04:06:20 lb0 Keepalived_vrrp: VRRP_Instance(VI_1) Sending gratuitous ARPs on eth1 for 202.54.1.1
Verify that VIP assigned to eth1:
# ip addr show eth1
Sample outputs:
3: eth1:  mtu 1500 qdisc pfifo_fast qlen 10000
    link/ether 00:30:48:30:30:a3 brd ff:ff:ff:ff:ff:ff
    inet 202.54.1.11/29 brd 202.54.1.254 scope global eth1
    inet 202.54.1.1/29 scope global secondary eth1

ping failover test

Open UNIX / Linux / OS X desktop terminal and type the following command to ping to VIP:
# ping 202.54.1.1
Login to lb0 and halt the server or take down networking:
# halt
Within seconds VIP should move from lb0 to lb1 and you should not see any drops in ping. On lb1 you should get the following in /var/log/messages:
Feb 21 04:10:07 lb1 Keepalived_vrrp: VRRP_Instance(VI_1) forcing a new MASTER election
Feb 21 04:10:08 lb1 Keepalived_vrrp: VRRP_Instance(VI_1) Transition to MASTER STATE
Feb 21 04:10:09 lb1 Keepalived_vrrp: VRRP_Instance(VI_1) Entering MASTER STATE
Feb 21 04:10:09 lb1 Keepalived_vrrp: VRRP_Instance(VI_1) setting protocol VIPs.
Feb 21 04:10:09 lb1 Keepalived_healthcheckers: Netlink reflector reports IP 202.54.1.1 added
Feb 21 04:10:09 lb1 Keepalived_vrrp: VRRP_Instance(VI_1) Sending gratuitous ARPs on eth1 for 202.54.1.1

Conclusion

Your server is now configured with IP failover. However, you need to install and configure the following software in order to configure webserver and security:
  1. nginx or lighttpd
  2. iptables
Stay tuned, for more information on above configuration.
This FAQ entry is 1 of 7 in the "CentOS / RHEL nginx Reverse Proxy Tutorial" series. Keep reading the rest of the series:

REFERENCES
http://www.cyberciti.biz/faq/rhel-centos-fedora-keepalived-lvs-cluster-configuration/

Friday, September 10, 2010

Top 20 Nginx WebServer Best Security Practices

— SkyHi @ Friday, September 10, 2010
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'
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,

1. client_body_buffer_size 1k - (default is 8k or 16k) The directive specifies the client request body buffer size.
2. 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).
3. 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.
4. 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 ##


1. 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.
2. 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).
3. 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").
4. 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 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 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 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:

1. Sample PF firewall script.
2. 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.
References:

* HowTo: Setup nginx reverse proxy and HA cluser with the help of keepalived.
* nginx wiki - The official nginx wiki.
* OpenBSD specific Nginx installation and security how to.


REFERENCES
http://www.cyberciti.biz/tips/linux-unix-bsd-nginx-webserver-security.html