DirectAdmin + Nginx/Reverse Proxy

DirectAdmin + Nginx (Reverse Proxy)

DirectAdmin is a Control panel for web hosting companies running Red Hat 7.x, 8.x, 9.x, Red Hat Enterprise and FreeBSD.

Nginx is a free, open-source, high-performance HTTP server and reverse proxy, as well as an IMAP/POP3 proxy server.

This tutorial,Will show how to Install Nginx and Configure Nginx for DirectAdmin Server
* Note for those not use DirectAdmin, you can also follow/refer this tutorial.

a. Install Nginx

1. Download latest Nginx:


2. Extract tar file and move into the newly created directory:

tar -zxvf nginx-1.0.4.tar.gz
cd nginx-1.0.4

3. Configure:

./configure --sbin-path=/usr/local/sbin --with-http_ssl_module
make install

4. Test Run (Default) :


5. Open Browser and you will see “Welcome to nginx!”


b. Configure Nginx as Reverse Proxy

0. Before we continue, make sure you kill the current nginx process

killall nginx

1. Move to Nginx configuration dir

cd /usr/local/nginx/conf

2. Make backup current conf file

mv nginx.conf nginx.conf.bak

3. Create new nginx.conf

nano -w nginx.conf

4. Paste this configuration to your nginx.conf :

user  apache; # make sure you use right user , apache or nobody.
# no need for more workers in the proxy mode
worker_processes  2;
error_log  /var/log/nginx/error.log info;
worker_rlimit_nofile 20480;
events {
 worker_connections 5120; # increase for busier servers
 use epoll; # you should use epoll here for Linux kernels 2.6.x
http {
 server_name_in_redirect off;
 server_names_hash_max_size 10240;
 server_names_hash_bucket_size 1024;
 include    mime.types;
 default_type  application/octet-stream;
 server_tokens off;
 sendfile on;
 tcp_nopush on;
 tcp_nodelay on;
 keepalive_timeout  5;
 gzip on;
 gzip_vary on;
 gzip_disable "MSIE [1-6]\.";
 gzip_proxied any;
 gzip_http_version 1.1;
 gzip_min_length  1000;
 gzip_comp_level  6;
 gzip_buffers  16 8k;
# You can remove image/png image/x-icon image/gif image/jpeg if you have slow CPU
 gzip_types    text/plain text/xml text/css application/x-javascript application/xml image/png image/x-icon image/gif image/jpeg application/xml+rss text/javascript application/atom+xml;
 ignore_invalid_headers on;
 client_header_timeout  3m;
 client_body_timeout 3m;
 send_timeout     3m;
 reset_timedout_connection on;
 connection_pool_size  256;
 client_header_buffer_size 256k;
 large_client_header_buffers 4 256k;
 client_max_body_size 200M; 
 client_body_buffer_size 128k;
 request_pool_size  32k;
 output_buffers   4 32k;
 postpone_output  1460;
 proxy_temp_path  /tmp/nginx_proxy/;
 client_body_in_file_only on;
 log_format bytes_log "$msec $bytes_sent .";
# This dir must create for reverse proxy purpose 
include "/usr/local/nginx/vhosts/*"; # This dir must create for reverse proxy purpose

5. Create vhost dir

mkdir /usr/local/nginx/vhosts

6. Move to vhost dir

cd /usr/local/nginx/vhosts

7. Create vhosts file ( You can change to your own domain name/name )

pico -w

8. Paste this configuration ( **IP** : Please change to your server IP ):

server {
          error_log /var/log/nginx/vhost-error_log warn;
          listen **IP**:80;
          access_log /var/log/httpd/domains/ bytes_log;
          access_log /var/log/httpd/domains/ combined;
          root /home/lowkey/public_html;
          location / {
          location ~.*\.(3gp|gif|jpg|jpeg|png|ico|wmv|avi|asf|asx|mpg|mpeg|mp4|pls|mp3|mid|wav|swf|flv|html|htm|txt|js|css|exe|zip|tar|rar|gz|tgz|bz2|uha|7z|doc|docx|xls|xlsx|pdf|iso)$ {
          expires 7d;
          try_files $uri @backend;
          error_page 405 = @backend;
          add_header X-Cache "HIT from Backend";
          proxy_pass http://**IP**:8081;
          include; # Refer step 9
          location @backend {
          proxy_pass http://**IP**:8081;
          include; # Refer step 9
          location ~ .*\.(php|jsp|cgi|pl|py)?$ {
          proxy_pass http://**IP**:8081;
          include; # Refer step 9
          location ~ /\.ht {
          deny all;

9. Create

touch /usr/local/nginx/conf/
cd /usr/local/nginx/conf/
pico -w

Paste this configuration :

proxy_connect_timeout 59s;
proxy_send_timeout   600;
proxy_read_timeout   600;
proxy_buffer_size    64k;
proxy_buffers     16 32k;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 64k;
proxy_pass_header Set-Cookie;
proxy_redirect     off;
proxy_hide_header  Vary;
proxy_set_header   Accept-Encoding '';
proxy_ignore_headers Cache-Control Expires;
proxy_set_header   Referer $http_referer;
proxy_set_header   Host   $host;
proxy_set_header   Cookie $http_cookie;
proxy_set_header   X-Real-IP  $remote_addr;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

10. Finish Configure as reverse proxy

c. Change Apache port 80 to 8081

We already configure Nginx listen to port 80 and now we need Apache listen to 8081

1. Locate and Edit httpd.conf

find / -name httpd.conf

Here, I need reconfigure two httpd.conf files.

2. First httpd.conf

pico /etc/httpd/conf/httpd.conf
Change Listen 80 To Listen 8081

3. Second httpd.conf

pico /usr/local/directadmin/data/users/lowkey/httpd.conf
Change VirtualHost **IP**:80 To VirtualHost **IP**:8081

4. Restart Apache

service httpd restart

5. Now your Apache listen to port 8081

6. Finish change port to 8081

d. Run Nginx

Now, everything is ready.

1. Run Nginx

/usr/local/sbin/nginx -c /usr/local/nginx/conf/nginx.conf 

2. Done!

Now You’re done.

SSH Honeypot with Kippo

Kippo on Linux

Kippo is a medium interaction SSH honeypot designed to log brute force attacks and, most importantly, the entire shell interaction performed by the attacker.
Kippo is inspired, but not based on Kojoney.

I’ve tested Kippo on a CentOS 5.6, and the installation is quite easy.

Here my machine current release :

#cat /etc/redhat-release 
CentOS release 5.6 (Final)

My python version :

#python -V
Python 2.4.3

NOTE :Kippo only working on latest python (Python 2.6)

URL for download Python 2.6 :

(or wherever you prefer).

What we need is :
Zope Interface

Step-by-Step Solution :

Add geekymedia repo for install Python 2.6

#cd /etc/yum.repos.d
#yum install python26
#yum install python26-devel

Call your Python 2.6

 #python26 -V
Python 2.6

Seems it’s working! and get ready to compile Kippo’s dependencies ;)

Go to :

#cd /usr/local/src

Install Twisted :

#tar -xvf Twisted-11.0.0.tar.bz2
#cd Twisted-11.0.0
#python26 install

Install Zope Interface :

#tar -xvf zope.interface-3.3.0.tar.gz
#cd zope.interface-3.3.0
#python26 install

Install Pycrypto

#tar -xvf pycrypto-2.0.1.tar.gz
#cd pycrypto-2.0.1
#python26 install

Install pyasn1

#tar -xvf pyasn1-0.0.13b.tar.gz 
#cd pyasn1-0.0.13b
#python26 install

NOTE: Remember to use python26 as the binary when calling

Kippo doesnt run under root user! So we must create a regular user.

useradd kippouser

Download Kippo Source Package

#su - kippouser
#tar -xvf kippo-0.5.tar.gz
#cd kippo-0.5

Configure Kippo

vi kippo.cfg
# Kippo configuration file (kippo.cfg)
# IP addresses to listen for incoming SSH connections.
# (default: = any address
#ssh_addr =
# Port to listen for incoming SSH connections.
# (default: 2222)
ssh_port = 2222
# Hostname for the honeypot. Displayed by the shell prompt of the virtual
# environment.
# (default: sales)
hostname = sales
# Directory where to save log files in.
# (default: log)
log_path = log
# Directory where to save downloaded (malware) files in.
# (default: dl)
download_path = dl
# Directory where virtual file contents are kept in.
# This is only used by commands like 'cat' to display the contents of files.
# Adding files here is not enough for them to appear in the honeypot - the
# actual virtual filesystem is kept in filesystem_file (see below)
# (default: honeyfs)
contents_path = honeyfs
# File in the python pickle format containing the virtual filesystem. 
# This includes the filenames, paths, permissions for the whole filesystem,
# but not the file contents. This is created by the utility from
# a real template linux installation.
# (default: fs.pickle)
filesystem_file = fs.pickle
# Directory for miscellaneous data files, such as the password database.
# (default: data_path)
data_path = data
# Directory for creating simple commands that only output text.
# The command must be placed under this directory with the proper path, such
# as:
#   txtcmds/usr/bin/vi
# The contents of the file will be the output of the command when run inside
# the honeypot.
# In addition to this, the file must exist in the virtual
# filesystem {filesystem_file}
# (default: txtcmds)
txtcmds_path = txtcmds
# Public and private SSH key files. If these don't exist, they are created
# automatically.
# (defaults: public.key and private.key)
public_key = public.key
private_key = private.key
# Initial root password. Future passwords will be stored in
# {data_path}/pass.db
# (default: 123456)
password = 123456
# IP address to bind to when opening outgoing connections. Used exclusively by
# the wget command.
# (default: not specified)
#out_addr =
# Sensor name use to identify this honeypot instance. Used by the database
# logging modules such as mysql.
# If not specified, the logging modules will instead use the IP address of the
# connection as the sensor name.
# (default: not specified)
# Fake address displayed as the address of the incoming connection.
# This doesn't affect logging, and is only used by honeypot commands such as
# 'w' and 'last'
# If not specified, the actual IP address is displayed instead (default
# behaviour).
# (default: not specified)
#fake_addr =
# MySQL logging module
# Database structure for this module is supplied in doc/sql/mysql.sql
# To enable this module, remove the comments below, including the
# [database_mysql] line.
#host = localhost
#database = kippo
#username = kippo
#password = secret

Start Kippo


Log File

To see the Kippo logging data use the following command:
#tail -f log/kippo.log 

Make Kippo Accessible To The World
By default,Kippo is running on port 2222. If its running on Windows, port 22 is usually free and it’s ok to run kippo on that port. On linux, port 22 is restricted for root only, except if you do this (quote from #twisted):

iptables -t nat -A PREROUTING -i IN_IFACE -p tcp --dport 22 -j REDIRECT --to-port 2222

Connect to the Kippo server on port 2222 by using root as username and 123456 as password.

ssh -p 2222 -l root

You must see the following banner after successful login:


The Honeynet Project:
Kippo Project:
Iran Honeynet Project:

How to Update OpenSSH on Red Hat / Fedora

Here howto update OpenSSH on Red Hat / Fedora.

Here we go, firstly

1) Open your fav terminal ( eg. i use iTerm )

2) Enter command :

*replace the username and domain with your own details) 

3) If you see a message like: “Are you sure you want to continue connecting (yes/no)?”

Type “yes” and hit Enter

4) Enter your system password

5) Enter command :

# su - (This will take you to the root)

6) Enter command :

# sshd -v (To see the current version of OpenSSH on your server).
You may see a message like:
OpenSSH_4.5p1, OpenSSL 0.9.8b 04 May 2006

STOP:his guide can be considered dangerous as if the directions are not followed exactly and all steps completed you may loose access to your server completely. Use this with caution!

7) Enter command :

# wget 
( Check on for the latest version number)

8 ) Enter command :

# tar -xvzf openssh-5.4p1.tar.gz (This will unarchive the file)

9) Enter command :

# ./configure –prefix=/usr –sysconfdir=/etc/ssh –with-pam
(The configure command bellow will enable the pluggable authentication module,
PAM and set the configuration path for SSH.)

STOP: This guide can be considered dangerous as if the directions are not followed exactly and all steps completed you may loose access to your server completely. Use this with caution!

10) Enter command :

# ./configure
# make
# make install

11) Enter command :

# /etc/init.d/sshd restart
(To restart openssh. You may see messages like this:)
Stopping sshd: [ OK ]
Starting sshd: [ OK ]

12) Enter command :

# su - (To back to root)

13) Enter command :

# sshd -v 
(To check version to see if upgrade is successful. You may see messages like this:)
sshd: illegal option -- v
OpenSSH_5.8p1, OpenSSL 0.9.8e-fips-rhel5 01 Jul 2008

14) Reboot server

Secure and resize /tmp

Secure /tmp

This will cover securing /tmp /var/tmp and /dev/shm

Secure /tmp:

Step 1: Backup your /etc/fstab file

cp /etc/fstab /etc/fstab.bak

Step 2: Make a 3GB file for /tmp parition and an ext3 filesystem for tmp:

dd if=/dev/zero of=/var/tempFS bs=1024 count=3072000
/sbin/mkfs.ext3 /var/tempFS

*Change the count= to something higher if you need more space*

Step 3: Create a backup copy of your current /tmp drive:

cp -Rpf /tmp /tmpbackup

Step 4: Mount our new tmp parition and change permissions:

mount -o loop,noexec,nosuid,rw /var/tempFS /tmp
chmod 1777 /tmp

Step 5: Copy the old data:

cp -Rpf /tmpbackup/* /tmp/

* If your /tmp was empty earlier, you might get this error : cp: cannot stat `/tmp.bak/*’: No such file or directory

Step 6: Edit /etc/fstab and add this:

nano -w /etc/fstab

And ADD this line:

/var/tempFS /tmp ext3 loop,nosuid,noexec,rw 0 0

Step 7: Test your fstab entry:

mount -o remount /tmp

Step 8: Verify that your /tmp mount is working:

df -h

Should look something like this:

/var/tempFS           962M   18M  896M   2% /tmp

Secure /var/tmp:

Step 1: Use /tmp as /var/tmp.

mv /var/tmp /var/vartmp
ln -s /tmp /var/tmp

Step 2: Copy the old data back

cp /var/vartmp/* /tmp/

* If your /var/tmp was empty earlier, you might get this error : cp: cannot stat `/var/vartmp/*’: No such file or directory

Secure /dev/shm:

Step 1: Edit your /etc/fstab:

nano -w /etc/fstab


none /dev/shm tmpfs defaults,rw 0 0

Change it to:
none /dev/shm tmpfs defaults,nosuid,noexec,rw 0 0

Step 2: Remount /dev/shm:

mount -o remount /dev/shm

You should restart services that uses /tmp partition



This will help but as mentioned in previous posts, with a VPS you do not have access to your kernal. That is good in some ways, because if you don’t have access to it, neither to hackers or spammers (which limits what they can do). Its bad in ways, because you lose control and if you secure your box as much as possible, you are still at risk because you cannot control your kernal.

At any rate, here are some helpful hints :)

Checking for formmail

Form mail is used by hackers to send out spam email, by relay and injection methods. If you are using matts script or a version of it, you may be in jeopardy.

Command to find pesky form mails:
find / -name “[Ff]orm[mM]ai*”

CGIemail is also a security risk:
find / -name “[Cc]giemai*”

Command to disable form mails:
chmod a-rwx /path/to/filename
(a-rwx translates to all types, no read, write or execute permissions).

(this disables all form mail)

If a client or someone on your vps installs form mail, you will have to let them know you are disabling their script and give them an alternative.

Root kit checker – (

Check for root kits and even set a root kit on a cron job. This will show you if anyone has compromised your root. Always update chrootkit to get the latest root kit checker. Hackers and spammers will try to find insecure upload forms on your box and then with injection methods, try to upload the root kit on your server. If he can run it, it will modify *alot* of files, possibly causing you to have to reinstall.

To install chrootkit, SSH into server and login as root.
At command prompt type:

cd /root/
tar xvzf chkrootkit.tar.gz
cd chkrootkit-0.44
make sense

To run chkrootkit

At command prompt type:

Make sure you run it on a regular basis, perhaps including it in a cron job.


I use these three commands the most.
./chkrootkit -q
./chkrootkit -x | more

Install a root breach DETECTOR and EMAIL WARNING

If someone does happen to get root, be warned quickly by installing a detector and warning at your box. You will at least get the hackers/spammers ip address and be warned someone is in there.

Server e-mail everytime someone logs in as root

To have the server e-mail you everytime someone logs in as root, SSH into server and login as root.

At command prompt type:
pico .bash_profile

Scroll down to the end of the file and add the following line:

echo ‘ALERT – Root Shell Access on:’ `date` `who` | mail -s “Alert: Root Access from `who | awk ‘{print $6}’`”

Save and exit.

Set an SSH Legal Message

To an SSH legal message, SSH into server and login as root.

At command prompt type:
pico /etc/motd

Enter your message, save and exit.
Note: I use the following message…

ALERT! You are entering a secured area! Your IP and login information
have been recorded. System administration has been notified.
This system is restricted to authorized access only. All activities on
this system are recorded and logged. Unauthorized access will be fully
investigated and reported to the appropriate law enforcement agencies.

Web Host manager and CPANEL mods.

These are items inside of WHM/Cpanel that should be changed to secure your server.

Goto Server Setup =>> Tweak Settings
Check the following items…

Under Domains
Prevent users from parking/adding on common internet domains. (ie,

Under Mail
Attempt to prevent pop3 connection floods
Default catch-all/default address behavior for new accounts – blackhole
(according to ELIX – set this to FAIL, which is what I am going to do to reduce server load)

Under System
Use jailshell as the default shell for all new accounts and modified accounts

Goto Server Setup =>> Tweak Security
Enable php open_basedir Protection
Enable mod_userdir Protection
Disabled Compilers for unprivileged users.

Goto Server Setup =>> Manage Wheel Group Users
Remove all users except for root and your main account from the wheel group.

Goto Server Setup =>> Shell Fork Bomb Protection
Enable Shell Fork Bomb/Memory Protection

When setting up Feature Limits for resellers in Resellers =>> Reseller Center, under Privileges always disable Allow Creation of Packages with Shell Access and enable Never allow creation of accounts with shell access; under Root Access disable All Features.

Goto Service Configuration =>> FTP Configuration
Disable Anonymous FTP

Goto Account Functions =>> Manage Shell Access
Disable Shell Access for all users (except yourself)

Goto Mysql =>> MySQL Root Password
Change root password for MySQL

Goto Security and run Quick Security Scan and Scan for Trojan Horses often. The following and similar items are not Trojans:

More Security Measures

These are measures that can be taken to secure your server, with SSH access.

Update OS, Apache and CPanel to the latest stable versions.
This can be done from WHM/CPanel.

Restrict SSH Access
To restrict and secure SSH access, bind sshd to a single IP that is different than the main IP to the server, and on a different port than port 22.

SSH into server and login as root.
Note: You can download Putty by Clicking Here ( It’s a clean running application that will not require installation on Windows-boxes.

At command prompt type:
pico /etc/ssh/sshd_config

Scroll down to the section of the file that looks like this:
#Port 22
#Protocol 2, 1
#ListenAddress ::

Uncomment and change
#Port 22
to look like
Port 5678 (choose your own 4 to 5 digit port number (49151 is the highest port number AND do not use 5678 :) lol )

Uncomment and change
#Protocol 2, 1
to look like
Protocol 2

Uncomment and change
to look like
ListenAddress (use one of your own IP Addresses that has been assigned to your server)

Note 1: If you would like to disable direct Root Login, scroll down until you find
#PermitRootLogin yes
and uncomment it and make it look like
PermitRootLogin no

Save by pressing Ctrl o on your keyboard, and then exit by pressing Ctrl x on your keyboard.

Note 2: You can also create a custome nameserver specifically for your new SSH IP address. Just create one called something like or whatever. Be sure to add an A address to your zone file for the new nameserver.

Now restart SSH
At command prompt type:
/etc/rc.d/init.d/sshd restart

Exit out of SSH, and then re-login to SSH using the new IP or nameserver, and the new port.

Note: If you should have any problems, just Telnet into your server, fix the problem, then SSH in again. Telnet is a very unsecure protocol, so change your root password after you use it.

After SSH has been redirected, disable telnet.

Disable Telnet
To disable telnet, SSH into server and login as root.
At command prompt type: pico -w /etc/xinetd.d/telnet
change disable = no to disable = yes
Save and Exit
At command prompt type: /etc/init.d/xinetd restart

Disable Shell Accounts
To disable any shell accounts hosted on your server SSH into server and login as root.
At command prompt type: locate shell.php
Also check for:
locate irc
locate eggdrop
locate bnc
locate BNC
locate ptlink
locate BitchX
locate guardservices
locate psyBNC
locate .rhosts

Note: There will be several listings that will be OS/CPanel related. Examples are

Disable identification output for Apache

(do this to hide version numbers from potentional hackers)

To disable the version output for proftp, SSH into server and login as root.
At command prompt type: pico /etc/httpd/conf/httpd.conf

Scroll (way) down and change the following line to
ServerSignature Off

Restart Apache
At command prompt type: /etc/rc.d/init.d/httpd restart

Install BFD (Brute Force Detection – optional)

To install BFD, SSH into server and login as root.

At command prompt type:
cd /root/
tar -xvzf bfd-current.tar.gz
cd bfd-0.4

After BFD has been installed, you need to edit the configuration file.

At command prompt type:
pico /usr/local/bfd/conf.bfd

Under Enable brute force hack attempt alerts:
and change it to

and change it to

Save the changes then exit.

To start BFD

At command prompt type:
/usr/local/sbin/bfd -s

Modify LogWatch
Logwatch is a customizable log analysis system. It parses through your system’s logs for a given period of time and creates a report analyzing areas that you specify, in as much detail as you require. Logwatch is already installed on most CPanel servers.

To modify LogWatch, SSH into server and login as root.

At command prompt type:
pico -w /etc/log.d/conf/logwatch.conf

Scroll down to
MailTo = root
and change to
Mailto =
Note: Set the e-mail address to an offsite account incase you get hacked.

Now scroll down to
Detail = Low
Change that to Medium, or High…
Detail = 5 or Detail = 10
Note: High will give you more detailed logs with all actions.

Save and exit.

A number of suggestions to improve system security. Some of this is specific to CPanel, but much can be applied to most Linux systems.
Use The Latest Software
Keep the OS and 3rd party software up to date. Always!
CPanel itself can be updated from the root WHM.
Change Passwords
Change the root passwords at least once a month and try to make them hard to guess. Yes it’s a pain to have to keep remembering them, but it’s better than being hacked.

Set Up A More Secure SSH Environment As described here.
Disable Telnet
1. Type: pico -w /etc/xinetd.d/telnet
2. Change the disable = no line to disable = yes.
3. Hit CTRL+X press y and then enter to save the file.
4. Restart xinted with: /etc/rc.d/init.d/xinetd restart
Also, add the following line to /etc/deny.hosts to flag Telnet access attempts as ‘emergency’ messages.

in.telnetd : ALL : severity emerg

Disable Unnecessary Ports (optional)
First backup the file that contains your list of ports with:
cp /etc/services /etc/services.original
Now configure /etc/services so that it only has the ports you need in it. This will match the ports enabled in your firewall.
On a typical CPanel system it would look something like this:
tcpmux 1/tcp # TCP port service multiplexer
echo 7/tcp
echo 7/udp
ftp-data 20/tcp
ftp 21/tcp
ssh 22/tcp # SSH Remote Login Protocol
smtp 25/tcp mail
domain 53/tcp # name-domain server
domain 53/udp
http 80/tcp www www-http # WorldWideWeb HTTP
pop3 110/tcp pop-3 # POP version 3
imap 143/tcp imap2 # Interim Mail Access Proto v2
https 443/tcp # MCom
smtps 465/tcp # SMTP over SSL (TLS)
syslog 514/udp
rndc 953/tcp # rndc control sockets (BIND 9)
rndc 953/udp # rndc control sockets (BIND 9)
imaps 993/tcp # IMAP over SSL
pop3s 995/tcp # POP-3 over SSL
cpanel 2082/tcp
cpanels 2083/tcp
whm 2086/tcp
whms 2087/tcp
webmail 2095/tcp
webmails 2096/tcp
mysql 3306/tcp # MySQL
Additional ports are controlled by /etc/rpc. These aren’t generally needed, so get shot of that file with: mv /etc/rpc /etc/rpc-moved
Watch The Logs
Install something like logwatch to keep an eye on your system logs. This will extract anything ‘interesting’ from the logs and e-mail to you on a daily basis.
Logwatch can be found at: (
Install instructions here.
Avoid CPanel Demo Mode
Switch it off via WHM Account Functions => Disable or Enable Demo Mode.
Jail All Users
Via WHM Account Functions => Manage Shell Access => Jail All Users.
Better still never allow shell access to anyone – no exceptions.
Immediate Notification Of Specific Attackers
If you need immediate notification of a specific attacker (TCPWrapped services only), add the following to /etc/hosts.deny

ALL : nnn.nnn.nnn.nnn : spawn /bin/ ‘date’ %c %d | mail -s”Access attempt by nnn.nnn.nnn.nnn on for hostname”
Replacing nnn.nnn.nnn.nnn with the attacker’s IP address.
Replacing hostname with your hostname.
Replacing with your e-mail address.
This will deny access to the attacker and e-mail the sysadmin about the access attempt.
Check Open Ports
From time to time it’s worth checking which ports are open to the outside world. This can be done with:
nmap -sT -O localhost
If nmap isn’t installed, it can be selected from root WHM’s Install an RPM option.
Set The MySQL Root Password
This can be done in CPanel from the root WHM Server Setup -> Set MySQL Root Password.
Make it different to your root password!
Tweak Security (CPanel)
From the root WHM, Server Setup -> Tweak Security, you will most likely want to enable:
- php open_basedir Tweak.
- SMTP tweak.
You may want to enable:
- mod_userdir Tweak. But that will disable domain preview.
Use SuExec (CPanel)
From root WHM, Server Setup -> Enable/Disable SuExec. This is CPanel’s decription of what it does:
“suexec allows cgi scripts to run with the user’s id. It will also make it easier to track which user has sent out an email. If suexec is not enabled, all cgi scripts will run as nobody. ”
Even if you don’t use phpsuexec (which often causes more problems), SuExec should be considered.
Use PHPSuExec (CPanel)
This needs to built into Apache (Software -> Update Apache from the root WHM) and does the same as SuExec but for PHP scripts.
Wisth PHPSuExec enabled, you users will have to make sure that all their PHP files have permissions no greater than 0755 and that their htaccess files contain no PHP directives.
Disable Compilers
This will prevent hackers from compiling worms, root kits and the like on your machine.
To disable them, do the following:

chmod 000 /usr/bin/perlcc
chmod 000 /usr/bin/byacc
chmod 000 /usr/bin/yacc
chmod 000 /usr/bin/bcc
chmod 000 /usr/bin/kgcc
chmod 000 /usr/bin/cc
chmod 000 /usr/bin/gcc
chmod 000 /usr/bin/i386*cc
chmod 000 /usr/bin/*c++
chmod 000 /usr/bin/*g++
chmod 000 /usr/lib/bcc /usr/lib/bcc/bcc-cc1
chmod 000 /usr/i386-glibc21-linux/lib/gcc-lib/i386-redhat-linux/2.96/cc1

You will need to enable them again when you need to perform system updates. To do this, run:

chmod 755 /usr/bin/perlcc
chmod 755 /usr/bin/byacc
chmod 755 /usr/bin/yacc
chmod 755 /usr/bin/bcc
chmod 755 /usr/bin/kgcc
chmod 755 /usr/bin/cc
chmod 755 /usr/bin/gcc
chmod 755 /usr/bin/i386*cc
chmod 755 /usr/bin/*c++
chmod 755 /usr/bin/*g++
chmod 755 /usr/lib/bcc /usr/lib/bcc/bcc-cc1
chmod 755 /usr/i386-glibc21-linux/lib/gcc-lib/i386-redhat-linux/2.96/cc1

Obfuscate The Apache Version Number
1. Type: pico /etc/httpd/conf/httpd.conf
2. Change the line that begins ServerSignature to:

ServerSignature Off

3. Add a line underneath that which reads:

ServerTokens ProductOnly

4. Hit CTRL+X, they y, the enter to save the file.
5. Restart Apache with: /etc/rc.d/init.d/httpd restart

System Information
List the users logged in on the machine. –

rwho -a
List all users logged in on your network. The rwho service must be enabled for this command to work.

finger user_name
System info about a user. Try: finger root last. This lists the users last logged-in on your system.

history | more
Show the last (1000 or so) commands executed from the command line on the current account. The | more causes the display to stop after each screen fill.

Print working directory, i.e. display the name of your current directory on the screen.

Print the name of the local host (the machine on which you are working).

Print your login name.

id username
Print user id (uid) and his/her group id (gid), effective id (if different than the real id) and the supplementary groups.

Print or change the operating system date and time. E.g., change the date and time to 2000-12-31 23:57 using this command

date 123123572000
To set the hardware clock from the system clock, use the command (as root)

Determine the amount of time that it takes for a process to complete+ other info. Don’t confuse it with date command. For e.g. we can find out how long it takes to display a directory content using time ls

Amount of time since the last reboot

List the processes that are have been run by the current user.

ps aux | more
List all the processes currently running, even those without the controlling terminal, together with the name of the user that owns each process.

Keep listing the currently running processes, sorted by cpu usage (top users first).

uname -a
Info on your server.

Memory info (in kilobytes).

df -h
Print disk info about all the file systems in a human-readable form.

du / -bh | more
Print detailed disk usage for each subdirectory starting at root (in a human readable form).

(as root. Use /sbin/lsmod to execute this command when you are a non-root user.) Show the kernel modules currently loaded.

Show the current user environment.

echo $PATH
Show the content of the environment variable PATH. This command can be used to show other environment variables as well. Use set to see the full environment.

dmesg | less
Print kernel messages (the current content of the so-called kernel ring buffer). Press q to quit less. Use less /var/log/dmesg to see what dmesg dumped into the file right after bootup. – only works on dedciated systems

Commands for Process control
Display the list of currently running processes with their process IDs (PID) numbers. Use ps aux to see all processes currently running on your system (also those of other users or without a controlling terminal),
each with the name of the owner. Use top to keep listing the processes currently running.

PID Bring a background or stopped process to the foreground.

PID Send the process to the background. This is the opposite of fg. The same can be accomplished with Ctrl z

any_command &
Run any command in the background (the symbol ‘&’ means run the command in the background?).

kill PID
Force a process shutdown. First determine the PID of the process to kill using ps.

killall -9 program_name
Kill program(s) by name.

(in an xwindow terminal) Kill a GUI-based program with mouse. (Point with your mouse cursor at the window of the process you want to kill and click.)

(as root) Check and control the printer(s). Type ??? to see the list of available commands.

Show the content of the printer queue.

lprm job_number
Remove a printing job job_number from the queue.

nice program_name
Run program_name adjusting its priority. Since the priority is not specified in this example, it will be adjusted by 10 (the process will run slower), from the default value (usually 0). The lower the number (of niceness to other users on the system), the higher the priority. The priority value may be in the range -20 to 19. Only root may specify negative values. Use top to display the priorities of the running processes.

renice -1 PID
(as root) Change the priority of a running process to -1. Normal users can only adjust processes they own, and only up from the current value (make them run slower).

Optimizing your VPS server (help it run more efficiently)

VPSes are really hard to use with the memory restrictions and CPU limitations…but with some optimization they can definitely serve your websites fast!

MySQL Optimization
Here are my suggested settings for the my.cnf file. This should work well for a VPS with 256-512MB RAM.

max_connections = 400
key_buffer = 16M
myisam_sort_buffer_size = 32M
join_buffer_size = 1M
read_buffer_size = 1M
sort_buffer_size = 2M
table_cache = 1024
thread_cache_size = 286
interactive_timeout = 25
wait_timeout = 1000
connect_timeout = 10
max_allowed_packet = 16M
max_connect_errors = 10
query_cache_limit = 1M
query_cache_size = 16M
query_cache_type = 1
tmp_table_size = 16M

open_files_limit = 8192

max_allowed_packet = 16M

key_buffer = 32M
sort_buffer = 32M
read_buffer = 16M
write_buffer = 16M
In order to make things even faster, you can customize these settings specifically for your VPSs’ usage. There’s a great howto on InterWorx’s forum for this –>

Lastly, I recommend installing mytop to help you monitor your usage…
tar -zxvf mytop-1.4.tar.gz
cd mytop-1.4
perl Makefile.PL
make test
make install
Once that’s done, just enter in “mytop” .

PHP & Apache Optimization
I strongly recommend installing eAccelerator. There’s an easy to follow howto here: If you use the default cache dir for eAccelerator (/tmp/eaccelerator) make sure you check it reguarily and clean it every once and a while. (it can really get quite large from my experience)

For httpd.conf I suggest:
Timeout 200
KeepAlive On
maxKeepAliveRequests 100
KeepAliveTimeout 3
MinSpareServers 10
MaxSpareServers 20
StartServers 15
MaxClients 250
MaxRequestsPerChild 0
HostnameLookups Off

You can use ab to benchmark your Apache before and after you make changes.

ab -c 5 -n 20

I suggest doing 2 or 3 tests like that to get an average.

If you want to check the Apache error log, try this –>
cat /usr/local/apache/logs/error_log

Monitoring Usage
On a Virtuozzo VPS you can use cat /proc/usr_beancounters to output your usage of the VZ parameters. You should pay most attention to oomguarpages and privmpages. (although anything with a failure is generally bad)

You can find the amount of connections to Apache with this command:
netstat -nt | grep :80 | wc -l

To find the amount of Apache processes use this command:
ps -A | grep httpd | wc -l (this will show the process count)
ps -aux | grep httpd (this will show the actual processes)

To find the amount of MySQL processes use this command:
ps -A | grep mysql | wc -l (this will show the process count)
ps -aux | grep mysql (this will show the actual processes)

Just simply using top (standard view) or top -c (will show the actual command being used and/or location of each process as opposed to just the name) can help you monitor your VPS usage very wel.

To see your disk space usage, try using this command –> df -h

Mitigating (D)DOS
If you’re being DDOS’d or DOS’d you can use this command:
netstat -ntu | awk ‘{print $5}’ | cut -d: -f1 | sort | uniq -c | sort -n

That will help you see how many connections each IP address has in total to your server.

There’s a very decent script you can use to automate the banning of IP addresses available here –>

Although I haven’t tried it myself, I suggest you take a look at Scrutinizer as well which sounds very useful –>

Spam Assassin
Spam Assassin can take up a lot of memory and make it really hard to host just a few sites on a VPS, but there is a way around this…

Login to WHM as root, scroll down to “cPanel 10.8.1-R15? (it may be slightly different depending on what version you are using) then goto “Addon Modules” and install “spamdconf”. Once it’s done, refresh the WHM page, scroll down to “Add-ons” on the nav bar and then click on ‘Setup Spamd Startup Configuration”. Set “Maximum Children” to “2?. Then hit Submit. Wait a few seconds (15-30, but usually less) for exim to restart and you’re done .

cPanel Tweak Setings
Login to WHM as root, and under “Server Configuration” on the nav bar hit “Tweak Settings”.

Here are some suggested settings:
Default catch-all/default address behavior for new accounts. fail will generally save the most CPU time.
- Use “FAIL”. If you already have some accounts setup not to use “FAIL” (by default it will not) then run this command to convert to FAIL from BLACKHOLE –> perl -pi -e “s/:blackhole:/:fail:/g;” /etc/valiases/*

- Mailman tends to use a lot of resources, so if you don’t need cpanel mailing lists then uncheck this.

Number of minutes between mail server queue runs (default is 60).:
- You may want to set this to 180 to reduce load.

Track the origin of messages sent though the mail server by adding the X-Source headers (exim 4.34+ required)
- This is just generally a good idea. So check this.

Analog Stats
- I find this useless, so uncheck this. If you want to delete the existing analog stats files just run this command –> rm -rf /home/*/tmp/analog/*

Awstats Reverse Dns Resolution
- Make sure this is unchecked, I find it pretty much useless for most users.

Awstats Stats
- You can check this if you need a robust stats software that integrates with cPanel, if you don’t need it, then don’t check it. *Note most hosting clients will want to use this. If you want to delete the existing awstats stats files just run this command –> rm -rf /home/*/tmp/awstats/*

Webalizer Stats
- Not many hosting clients will want to use this so, you can uncheck this to reduce load. If you want to delete the existing webalizer stats files just run this command –> rm -rf /home/*/tmp/webalizer/*

Delete each domain’s access logs after stats run
- Make sure this is checked, otherwise disk space usage can really rack up!

That’s about it for now, I may do some more later….

Exim configuration error in line 571

Problem :

Exim configuration error in line 571 of /etc/exim.conf:
group daemon was not found

Solution :

as root chmod file group to 644

chmod 644 /etc/group


How to install CSF firewall on centos linux

Product Name: CSF (ConfigServer Security & Firewall)
Product Version: 5.12 (using download link, will give you the latest version)
Description: Advanced Policy Firewall (APF) is an iptables(netfilter) based firewall system designed around the essential needs of todays Internet deployed servers and the unique needs of custom deployed Linux installations. The configuration of APF is designed to be very informative and present the user with an easy to follow process, from top to bottom of the configuration file. The management of APF on a day-to-day basis is conducted from the command line with the apf command, which includes detailed usage information and all the features one would expect from a current and forward thinking firewall solution.

Pre Setup: Make sure perl modules are installed

yum install -y perl-libwww-perl

Step 1: Download, unpack, install of APF from source.

cd /usr/local/src
tar -zxvf csf.tgz
cd csf

Step 1.1: Cleanup source install files.

rm -Rf /usr/local/src/csf* && cd

Step 2: Backup orginal CSF config

cp /etc/csf/csf.conf /etc/csf/csf.conf.bak

Step 3: Edit current CSF config

nano -w /etc/csf/csf.conf

Webmin Module Installation/Upgrade

To install or upgrade the csf webmin module:

Install csf as above
Install the csf webmin module in:

  Webmin > Webmin Configuration > Webmin Modules >
  From local file > /etc/csf/csfwebmin.tgz > Install Module

How to clean the Exim Mail Server Queue

Sometimes it is necessary to clean out the mail queue on your server. Emails being stuck cause the complete mail flow to stop or to dramatically slow down. Customers will complain and the server performance goes down hill. Time to look at the mail queue a little closer.

To flush the exim queue from the command line do the following:

Login to your dedicated server via ssh and switch to the root user.

To print a list of the messages in the queue, enter:

exim -bp

To remove a message from the queue, enter:

exim -Mrm {message-id}

To remove all messages from the queue, enter:

exim -bp | awk '/^ *[0-9]+[mhd]/{print "exim -Mrm " $3}' | bash

Another Tips

To check the no. of mails in the queue use the command

exim -bpc

To check the list of pending mails use

exim -bp

To deliver the mails use

exim -qf -d


Problem :

Have you been remove about 1200821 queue ?
it wont work with "exim -bp | exiqgrep -i | xargs exim -Mrm"
(I tried to wait until 24hours, it get my swap until 0 free)

Solutions :

This for with include dir

for dir in /var/spool/exim/input/*; do cd $dir; ls | xargs rm -f; done

Of course, if your intention is to simply remove all files (not directories)
underneath /var/spool/exim/input, that process can be simplified as follows:

find /var/spool/exim/input -type f -exec rm -f {} +

How to create a self-signed SSL Certificate


The Secure Socket Layer is used to encrypt the data stream between the web server and the web client (the browser).

Step 1: Generate a Private Key
The openssl toolkit is used to generate an RSA Private Key and CSR (Certificate Signing Request). It can also be used to generate self-signed certificates which can be used for testing purposes or internal usage.

The first step is to create your RSA Private Key. This key is a 1024 bit RSA key which is encrypted using Triple-DES and stored in a PEM format so that it is readable as ASCII text.

openssl genrsa -des3 -out server.key 1024

Generating RSA private key, 1024 bit long modulus
e is 65537 (0x10001)
Enter PEM pass phrase:
Verifying password - Enter PEM pass phrase:

Step 2: Generate a CSR (Certificate Signing Request)
Once the private key is generated a Certificate Signing Request can be generated.

openssl req -new -key server.key -out server.csr

Country Name (2 letter code) [GB]:MY
State or Province Name (full name) [Berkshire]:Kuala Lumpur
Locality Name (eg, city) [Newbury]:Bangsar
Organization Name (eg, company) [My Company Ltd]:GB Net
Organizational Unit Name (eg, section) []:Information Technology
Common Name (eg, your name or your server's hostname) []
Email Address []:admin at gbnet dot my
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []: * No need to put password , just enter *
An optional company name []: * No need to put company name , just enter *

Step 3: Remove Passphrase from Key
It is possible to remove the Triple-DES encryption from the key, thereby no longer needing to type in a pass-phrase.

cp server.key
openssl rsa -in -out server.key

The newly created server.key file has no more passphrase in it.

-rw-r--r-- 1 root root 745 Dec 2 12:19 server.csr
-rw-r--r-- 1 root root 891 Dec 2 13:22 server.key
-rw-r--r-- 1 root root 963 Dec 2 13:22 

Step 4: Generating a Self-Signed Certificate
To generate a temporary certificate which is good for 365 days, issue the following command:

openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

Signature ok
subject=/C=CH/ST=Bern/L=Oberdiessbach/O=Akadia AG/OU=Information
Technology/ dot zahn at akadia dot ch
Getting Private key 

How to install VSFTPD (Very Secure FTP Daemon)

Name : vsftpd – Very Secure FTP Daemon
Info : The “Very Secure FTPD” is a *nix (Unix, Linux) FTP Server

How to install :

Login as root and do

yum install vsftpd

Start the vsftpd

service vsftpd start

set it run automatically after reboot via chkconfig

chkconfig vsftpd on

Troubleshooting :

530 Permission denied
If you get that error , you need to check ftpusers & user_list files at /etc/vsftpd

In my case :
I want to allow root login via ftp

pico /etc/vsftpd/ftpusers
# Users that are not allowed to login via ftp
#root < --- comment out this line for allow root login via ftp

And also user_list

pico /etc/vsftpd/user_list
# vsftpd userlist
# If userlist_deny=NO, only allow users in this file
# If userlist_deny=YES (default), never allow users in this file, and
# do not even prompt for a password.
# Note that the default vsftpd pam config also checks /etc/vsftpd/ftpusers
# for users that are denied.
#root < --- comment out this line

That all ,

Have nice day ;)