Centos is an enterprise class Linux distribution that is built from the sources of Red Hat . It performs very well as a server as well as a workstation. This guide will show you how to quickly install and configure Centos as a server with Apache 2, Qmail and Proftpd on an x86 (32 bit) system.
This quick configuration guide assumes that you know how to perform an initial Red Hat/Centos installation. If not, then do read the installation guide first before proceeding.
First Steps
After a basic install of Centos 4.3, the first thing that we do is to configure a firewall (iptables). To do this easily, navigate here and then select the relevant options. The important ones are to open port 80 for HTTP, port 21 for FTP, port 22 for SSH (if you are installing and configuring a remote server), port 25 for SMTP, port 110 for POP3 and port 783 for SpamAssassin. The other ports that you can open out optionally are port 443 for HTTPS, port 143 for IMAP, port 993 for IMAPS (Secure IMAP) and port 995 for POP3S (Secure POP3). Save the generated file as /etc/init.d/iptables (as root). Make it executable by executing the command: chmod +x /etc/init.d/iptables/ (as root) and start iptables by executing the command: /etc/init.d/iptables start (as root). Your firewall is now in place.
Next, disable selinux (as it interferes with the proper execution of Qmail) by editing /etc/selinux/config/ (as root) and changing the line: SELINUX=enforcing to SELINUX=disabled. Save the file and reboot the system to enforce the change.
Next set the hostname of your server, by executing the commands [as root]:
echo [server hostname] > /etc/hostname
/bin/hostname -F /etc/hostname
Be sure to replace server hostname with the actual hostname of your server.
Hardening and Optimizing Sysctl
Sysctl is the system call interface to the kernel. Using it many kernel parameters can be fine tuned. We adjust several kernel parameters to make the system more secure and perform better.
First back up the existing sysctl.conf. Execute the following commands as root:
cd /etc
mv sysctl.conf sysctl.conf.bak
Now, create a new file called sysctl.conf with your favourite text editor (vi, pico, nano etc) and paste in the following content:
# For binary values, 0 is disabled, 1 is enabled. See sysctl(8) and
# sysctl.conf(5) for more details.
# Controls the System Request debugging functionality of the kernel
kernel.sysrq = 0
# Controls whether core dumps will append the PID to the core filename.
# Useful for debugging multi-threaded applications.
kernel.core_uses_pid = 1
#Prevent SYN attack
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_max_syn_backlog = 2048
net.ipv4.tcp_synack_retries = 2
# Disables packet forwarding
net.ipv4.ip_forward=0
# Disables IP source routing
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.lo.accept_source_route = 0
net.ipv4.conf.eth0.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0
# Enable IP spoofing protection, turn on source route verification
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.lo.rp_filter = 1
net.ipv4.conf.eth0.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
# Disable ICMP Redirect Acceptance
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.lo.accept_redirects = 0
net.ipv4.conf.eth0.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
# Enable Log Spoofed Packets, Source Routed Packets, Redirect Packets
net.ipv4.conf.all.log_martians = 1
net.ipv4.conf.lo.log_martians = 1
net.ipv4.conf.eth0.log_martians = 1
# Disables the magic-sysrq key
kernel.sysrq = 0
# Decrease the time default value for tcp_fin_timeout connection
net.ipv4.tcp_fin_timeout = 15
# Decrease the time default value for tcp_keepalive_time connection
net.ipv4.tcp_keepalive_time = 1800
# Turn off the tcp_window_scaling
net.ipv4.tcp_window_scaling = 0
# Turn off the tcp_sack
net.ipv4.tcp_sack = 0
# Turn off the tcp_timestamps
net.ipv4.tcp_timestamps = 0
# Enable ignoring broadcasts request
net.ipv4.icmp_echo_ignore_broadcasts = 1
# Enable bad error message Protection
net.ipv4.icmp_ignore_bogus_error_responses = 1
# Set maximum amount of memory allocated to shm to 256MB
kernel.shmmax = 268435456
# Improve file system performance
vm.bdflush = 100 1200 128 512 15 5000 500 1884 2
# Improve virtual memory performance
vm.buffermem = 90 10 60
# Increase the maximum total TCP buffer-space allocatable
net.ipv4.tcp_mem = 3129344 3137536 3145728
# Increase the maximum TCP write-buffer-space allocatable
net.ipv4.tcp_wmem = 65536 1398080 2796160
# Increase the maximum TCP read-buffer space allocatable
net.ipv4.tcp_rmem = 65536 1398080 2796160
# Increase the maximum and default receive socket buffer size
net.core.rmem_max = 2097136
net.core.rmem_default = 1048560
# Increase the maximum and default send socket buffer size
net.core.wmem_max = 2097136
net.core.wmem_default = 1048560
# Increase the tcp-time-wait buckets pool size
net.ipv4.tcp_max_tw_buckets = 1440000
# Allowed local port range
net.ipv4.ip_local_port_range = 16384 65536
# Increase the maximum memory used to reassemble IP fragments
net.ipv4.ipfrag_high_thresh = 512000
net.ipv4.ipfrag_low_thresh = 446464
# Increase the maximum amount of option memory buffers
net.core.optmem_max = 163840
# Increase the maximum number of skb-heads to be cached
net.core.hot_list_length = 1024
Sysctl is now hardened. To make the changes effective without rebooting, execute the command: /sbin/sysctl -p as root.
Installing Apache
To install the Apache webserver, execute the command: yum install httpd httpd-suexec (as root). This will install Apache along with the suexec extension (/usr/sbin/suexec) that allows the apache server to run CGI programs (and any programs executed by SSI pages) as a user other than the apache user.
Replace the contents of /etc/httpd/conf/httpd.conf as root with this. I have made changes that secure Apache.
To start Apache, execute the command: /sbin/service httpd start (as root). Navigate to http://www.yourdomain.com/ and you should see the default Centos Apache page.
Installing MySQL
To install the MySQL database , execute the command: yum install mysql mysql-server mysql-bench (as root). Start MySQL by executing the command: /etc/init.d/mysqld start (as root). MySQL should start and be listening on port 3306. To verify this, execute the command: nmap -a localhost | grep mysql. The command should return the output: 3306/tcp open mysql.
Set a password for the MySQL server using the command: mysqladmin -u root password [passwd] (as root), as otherwise your database is open to anyone who wishes to access it.
Let us optimise MYSQL to make it perform better. First backup the existing configuration file by executing the command:mv /etc/my.cf /etc/my.cnf.bak as root.
Next, as root, create a file /etc/my.cnf with the following contents:
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
skip-locking
skip-innodb
query_cache_limit=8M
query_cache_size=256M
query_cache_type=1
max_connections=500
max_user_connections=10
interactive_timeout=20
wait_timeout=20
connect_timeout=6
thread_cache_size=128
key_buffer=16M
join_buffer=1M
max_allowed_packet=16M
table_cache=1024
record_buffer=1M
sort_buffer_size=2M
read_buffer_size=2M
max_connect_errors=10
# Try number of CPU’s*2 for thread_concurrency
thread_concurrency=4
myisam_sort_buffer_size=64M
#log-bin
server-id=1
[mysql.server]
user=mysql
basedir=/var/lib
[safe_mysqld]
err-log=/var/log/mysqld.log
pid-file=/var/lib/mysql/mysql.pid
open_files_limit=8192
[mysqldump]
quick
max_allowed_packet=16M
[mysql]
no-auto-rehash
#safe-updates
[isamchk]
key_buffer=32M
sort_buffer=32M
read_buffer=16M
write_buffer=16M
[myisamchk]
key_buffer=32M
sort_buffer=32M
read_buffer=16M
write_buffer=16M
Restart MYSQL by exexuting the command:/sbin/service mysqld restart as root. MYSQL is now optimised and should perform better. Refer to the MYSQL documentation to know more about these settings.
Next, let us drop the test database. To do this execute the command: mysql -u root -p as root and then enter the mysql password. Then enter the command: drop database test; at the mysql prompt and then exit to exit the mysql prompt.
Installing Qmail
Qmail is a very secure, fast and efficient mail transfer agent like Postfix . To install Qmail easily along with its bells and whistles (Clamav , SpamAssassin ), follow the wonderful qmail toaster .
At the end of it, you should have an excellent Qmail server handling your mail.
Let us add some RBLs to qmail. Replace the line in /var/qmail/control/blacklists as root with:
-r sbl.spamhaus.org -r sbl-xbl.spamhaus.org -r bl.spamcop.net -r relays.ordb.org
Next, let us mask the SMTP greeting such that no one knows the mailer we are using. Replace the line in /var/qmail/control/smtpgreeting as root with:
[Mail Server Name (e.g. technofury.info)] ESMTP NO UCE/SPAM on this server
Restart qmail by executing the command: qmailctl restart to make the changes effective.
To fine tune SpamAssassin, edit /etc/mail/spamassassin/local.cf (as root) and adjust the parameters to your liking. An easy way to set the parameters is to navigate here , make your selection and replace the local.cf file with the generated one. I changed the line: ok_languages all to ok_languages en fr to tell SpamAssassin that the only languages in which I receive legitimate mails are English and French. SpamAssassin will automatically consider mails in all other languages as spam. Fine tune the settings to your liking, and then execute the command: qmailctl restart (as root) to restart Qmail with the new SpamAssassin settings.
SpamAssassin comes with a basic set of rules. To get more rules, visit this site. Download the rules that you like to /etc/mail/spamassassin. The rules that I use are here. Execute the following commands (as root) to install the rules from this file:
cd /etc/mail/spamassassin
wget http://www.technichristian.net/CENTOS/spamrules.zip
unzip spamrules.zip
mv SPAM/* .
rm -rf SPAM/
rm -rf spamrules.zip
To make sure these rules work (they do work for me), execute the command: spamassassin –lint -D. The last line of the output should not return any warnings.
Next, execute the command: qmailctl restart (as root) to restart Qmail with the new SpamAssassin rules. Your Qmail server is now well fortified against spam.
To do a security test of your mail server (check whether it is an open relay or not), navigate here , enter the name of your mail server [if you follow the qmail-toaster, it is always the name of your domain (mine is technichristian.net)] and then click Test for relay. The result should state that no relays were accepted.
Note: The Qmail installation will also automatically install and configure PHP for Apache along with a web based front end for mail – Squirrelmail.
Replace the contents of /etc/php.ini as root with this. I have made changes to secure PHP.
Installing Proftpd
Proftpd is a secure and feature rich FTP client. Get the rpm [Dag Wieers repository] and execute the command: rpm -Uvh proftpd-1.2.10-10.2.el4.rf.i386.rpm (as root) to install it. This package has root login to the FTP server disabled and is a good thing. Start Proftpd by executing the command: /etc/init.d/proftpd start (as root) and then login as your regular non-root user using your favorite FTP client.
If you really want to fiddle around with the FTP settings, the relevant file to tweak is /etc/proftpd.conf.
Disable Core Dumps
Core dumps most often consume large amounts of disk space and contain sensitive data. They are useful in debugging a program and have no place on a production server. To disable core dumps, edit the file /etc/security/limits.conf as root, and add the following lines to it:
* soft core 0
* hard core 0
Installing Awffull
Awffull is a web statistics package similar to Webalizer . Get the rpm [Dag Wieers respository ] and execute the command: rpm -Uvh awffull-3.4.3-1.el4.rf.i386.rpm (as root) to install it. Next get this configuration file and save it in /etc/ as root. Execute the command: awffull (as root) to generate the statistics. Navigate to http://www.yourdomain.com/usage/ to view the statistics.
Next, create a cron job to let Awffull update the web statistics automatically. Execute the command: crontab -e (as root) and add the cron entry: 0 * * * * /usr/bin/awffull. Save the cron entry. Awffull should update the web statistics every hour. Feel free to adjust the cron timing to suit your needs.
Awffull looks as follows:
Let us secure Awffull that only authorised people can see the statistics. First, generate the password by executing the command: htpasswd -c /usr/local/awffullpass [name of the authorised user]. Enter the desired password twice. The password is generated and stored.
Edit /etc/httpd/conf/httpd.conf and add the following:
[Directory /var/www/html/usage/]
AuthType Basic
AuthName “Private Access”
AuthUserFile /usr/local/awffullpass
Require user [name of the authorised user]
[/Directory]
Note: Change the square brackets to angle brackets.
Restart Apache by executing the command: /sbin/service httpd restart. Navigate to http://www.yourdomain.com/usage/, enter the username and password and view the statistics.
Installing Modsecurity
Modsecurity is an open source web application firewall for the Apache server that helps to keep the malicious people at bay. To install Modsecurity, first install the package: httpd-devel (yum install httpd-devel) [as root]. Next, execute the following commands (as root) to install and configure Modsecurity:
cd /root
wget http://www.modsecurity.org/download/modsecurity-apache_1.9.4.tar.gz
tar -xvzf modsecurity-apache_1.9.4.tar.gz
cd modsecurity-apache_1.9.4/apache2/
/usr/sbin/apxs -cia mod_security.c
The last line of the compilation should read: activating module ‘security’ in /etc/httpd/conf/httpd.conf, indcating that modsecurity is successfully built and installed.
Delete the downloaded package by executing the commands [as root]:
cd /root
rm -rf modsecurity*
Next, get the Modsecurity rulesets and install them. Execute the following commands to fetch and install the rulesets [as root]:
cd /etc/httpd/conf.d/
wget http://www.modsecurity.org/download/rules/modsecurity-general.conf
wget http://www.modsecurity.org/download/rules/modsecurity-php.conf
wget http://www.modsecurity.org/download/rules/modsecurity-output.conf
wget http://www.gotroot.com/downloads/ftp/mod_security/apache2/apache2-gotrootrules-latest.tar.gz
tar -xvzf apache2-gotrootrules-latest.tar.gz
mv apache2/* .
rm -rf apache2/
wget http://www.technichristian.net/CENTOS/modsec-start.conf
chmod 640 *.conf
chown root.apache *.conf
rm -rf apache2-gotrootrules-latest.tar.gz
Next, restart Apache to read the new rules. Execute the command: /sbin/service httpd restart (as root) to restart Apache.
The rules are updated very frequently, so keep updating them to get the latest protection.
Installing Modevasive
mod_evasive is an evasive maneuvers module for Apache to provide evasive action in the event of an HTTP DoS or DDoS attack or brute force attack. It is also designed to be a detection tool, and can be easily configured to talk to ipchains, firewalls, routers, and etcetera. Execute the following commands to install it:
cd /root
wget http://www.zdziarski.com/projects/mod_evasive/mod_evasive_1.10.1.tar.gz
tar -zxf mod_evasive_1.10.1.tar.gz
cd mod_evasive
/usr/sbin/apxs -cia mod_evasive20.c
rm -rf /root/mod_evasive*
Next, edit /etc/httpd/conf/httpd.conf and uncomment (remove the # in front of each line) the following:
[IfModule mod_evasive.c]
DOSHashTableSize 3097
DOSPageCount 5
DOSSiteCount 100
DOSPageInterval 2
DOSSiteInterval 2
DOSBlockingPeriod 600
[/IfModule]
Note: Replace the square brackets with angle brackets.
Restart Apache by executing the command: /sbin/service httpd restart as root.
Installing Chkrootkit
Chkrootkit is a tool that checks for signs of a rootkit on your server. To install Chkrootkit, do the following: First download chkrootkit [Dag Wieers repository]. Then execute the command: rpm -ivh chkrootkit-0.46a-2.2.el4.rf.i386.rpm (as root).
Run Chkrootkit by executing the command: chkrootkit (as root). The output should be indicate that nothing is infected.
If there is anything that is infected or found,then wipe and reinstall the server. Your server has been owned. Next, add a cron job for Chkrootkit such that it automatically executes and sends the output to a designated email address. Execute crontab -e (as root) and add the following line: 0 2 * * * /usr/bin/chkrootkit | /bin/mail -s “Daily chkrootkit report”
. Substitute the relevant email address for user@domain.com. The daily reports will be mailed at 2 AM everyday. Feel free to change the timing.
Installing RKHUNTER
RKHUNTER is a scanning tool that ensures you’re clean of nasty tools. This tool scans for rootkits, backdoors and local exploits. To install RKHUNTER, execute the following commands (as root):
wget http://downloads.rootkit.nl/rkhunter-1.2.8.tar.gz
md5sum rkhunter-1.2.8.tar.gz | cut -d ‘ ‘ -f1
The md5sum should be 41122193b5006b617e03c637a17ae982. If not then delete the file and download again.
Continue as follows:
tar -zxvf rkhunter-1.2.8.tar.gz
cd rkhunter
./installer.sh
cd ..
rm -rf rkhunter*
RKHUNTER is now installed. Next, we need to update the RKHUNTER databases. To do this, execute the command: /usr/local/bin/rkhunter –update.
Let us add RKHUNTER to a cron job such that it automatically updates itself and sends the results of the scan to a specified email address.
Execute crontab -e (as root) and add the following line: 0 3 * * * /usr/local/bin/rkhunter –update && /usr/local/bin/rkhunter -c -sk –cronjob 2>&1 | mail -s “Daily RKHUNTER Report”
. Substitute the relevant email address for user@domain.com. The daily reports will be mailed at 3 AM everyday. Feel free to change the timing.
Installing LSM
LSM is a network socket monitor. It is designed to track changes to Network sockets and Unix domain sockets.
A comprehensive alert system, simple program usage & installation make LSM ideal for deployment in any linux environment (geared for web servers). Using a rather simple yet logical structure, LSM identifies changes in both Network Sockets and Unix Domain Sockets. By recording a base set of what sockets should be active then comparing the currently active socket information to that of the base comparison files, we highlight otherwise unknown services.
To install LSM, execute the following commands (as root):
wget http://www.r-fx.ca/downloads/lsm-current.tar.gz
md5sum lsm-current.tar.gz | cut -d ‘ ‘ -f1
The md5sum should be d35ff3171cba48b5ed3127c7bb8dd1f0. If not, then delete the file and download again.
Continue as follows:
tar -zxvf lsm-current.tar.gz
cd lsm-0.6
./installer.sh
cd ..
rm -rf lsm*
LSM is now installed. Next, we need to update the LSM base comparison files. To do this, execute the command: /usr/local/sbin/lsm -g.
Next, edit /usr/local/lsm/conf.lsm as root. Find the line that reads:USER=”root” and change it to USER=”[Fill in the email address to which LSM reports must be sent: For e.g.
]“. Save the file and exit the editor.
Next, check for changes in sockets by executing the command: /usr/local/sbin/lsm -c as root. LSM will check for unwanted sockets and send a report to the specified email address, if any are found.
The LSM installer automatically installs a cron job that runs every 10 minutes to check for changes in sockets and notifies you accordingly.
Installing PRM
PRM monitors the process table on a given system and matches process id’s with set resource limits in the config file or per-process based rules. Process id’s that match or exceed the set limits are logged and killed; includes e-mail alerts, kernel logging routine and more…
To install PRM, execute the following commands (as root):
wget http://www.r-fx.ca/downloads/prm-current.tar.gz
md5sum prm-current.tar.gz | cut -d ‘ ‘ -f1
The md5sum should be bdc2f0a5e67b10b91690d19ef3889a98. If not, then delete the file and download again.
Continue as follows:
tar -zxvf prm-current.tar.gz
cd prm-0.5
./installer.sh
cd ..
rm -rf prm*
PRM is now installed. Next, we need to edit the PRM configuration file. To do this, edit the contents of the file /usr/local/prm/conf.prm as root, such that it looks like the following:
#
# PRM 0.5 [prm@r-fx.org]
###
# Copyright (C) 1999-2003, R-fx Networks
# Copyright (C) 2003, Ryan MacDonald
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
###
#
# NOTE: This file should be edited with word/line wrapping off,
# if your using pico please start it with the -w switch.
# (e.g: pico -w filename)
#
#
# [ Main config ]
#
# installation path
INSPATH=”/usr/local/prm”
# string based ignore file
IGNORE=”$INSPATH/ignore”
# directory path to process rules
PRULES=”$INSPATH/rules”
# enable kernel logging [0=disabled,1=enabled]
USE_KLOG=”1″
# path to kernel log
KLOG=”/var/log/messages”
# enable user e-mail alerts [0=disabled,1=enabled]
USR_ALERT=”1″
# e-mail address for alerts
USR_ADDR=”[Enter the email address to which the reports must be sent]“
# path to user e-mail message file
USR_MSG=”$INSPATH/usr.msg”
# subject of e-mail alerts
SUBJ=”Process status report from $HOSTNAME”
# check 5,10,15 minute load average. [1,2,3 respective of 5,10,15]
LC=”1″
# min load level required to run (decimal values unsupported)
MIN_LOAD=”1″
# seconds to wait before rechecking a flaged pid (pid’s noted resource
# intensive but not yet killed).
WAIT=”12″
# counter limit that a process must reach prior to kill. the counter value
# increases for a process flaged resource intensive on rechecks.
KILL_TRIG=”3″
# argument to pass onto kill commands
KARG=”9″
# Max CPU usage readout for a process – % of all cpu resources (decimal values unsupported)
MAXCPU=”40″
# Max MEM usage readout for a process – % of system total memory (decimal values unsupported)
MAXMEM=”20″
# Max processes for a given command – this is not max processes for user but rather the executable
MAXPS=”25″
# [ Misc. config ]
#
# temp file for proc listing
PROCLS_TMP=”$INSPATH/.procls”
# data directory for kill info files
KSP=”$INSPATH/killed”
# main log file
LOG=”$INSPATH/prm_log”
# misc temp file
TMP=”$INSPATH/.tmp”
# app name as seen in logs
APPN=”prm”
# unix time for lock tracking
UTIME=`date +”%s”`
# lock file path
LOCK=”$INSPATH/lock.utime”
# lock file timeout in seconds
LOCK_TIMEOUT=”180″
To create custom rules for a process, create a file with the process name in /usr/local/prm/rules and fill in the appropriate rules. For e.g. let us create some custom rules for a process named awffull. We will set the wait time to 16 and the maximum CPU usage to 20.
Create a file called awffull in the /usr/local/prm/rules directory with the following contents:
WAIT=”16″
MAXCPU=”20″
When PRM checks the awffull process, it will use these custom values in addition to the other standard values.
Next, run the program by executing the command: /usr/local/sbin/prm -s as root. PRM will first check for the system load and if the system load exceeds the specified limit, it will kill all processes that exceed the set limits.
The PRM installer automatically installs a cron job that runs every 5 minutes to check for process limits and notifies you accordingly.
Installing NSIV
NSIV is a rule based utility intended to aid in the validation of inodes against each LISTEN socket on a system. The nature for this app is such that rouge binaries can easily hijack a user, program privileges, or work space; and utilize such to kill the old service & execute a new service on the known port they crashed.
To install NSIV, execute the following commands (as root):
wget http://www.r-fx.ca/downloads/nsiv-current.tar.gz
md5sum nsiv-current.tar.gz | cut -d ‘ ‘ -f1
The md5sum should be ec40699e3a0244b9e0dbfd8e4fcfd533. If not, then delete the file and download again.
Continue as follows:
tar -zxvf nsiv-current.tar.gz
cd nsiv-0.3
./installer.sh
cd ..
rm -rf nsiv*
NSIV is now installed. Next, edit /usr/local/sbin/nsiv as root. Find the line that reads:bin_lsof and change it to bin_lsof=/usr/sbin/lsof. Save the file and exit the editor.
Edit /usr/local/nsiv/conf.nsiv as root. Find the line that reads ALERT=”root” and change it to ALERT=”[Fill in the email address to which the reports must be sent]“. Save the file and exit the editor. NSIV will send its reports to the specified email address.
Run NSIV by executing the command: /usr/local/sbin/nsiv -s. NSIV will check the running processes for rouge binaries and kill them.
The NSIV installer automatically installs a cron job that runs every 5 minutes to check for rouge binaries and notifies you accordingly.
Installing SPRI
SPRI is a utility designed to queue different processes with different priority levels based on 3 class levels of importance (high,med,low).
The problem? Linux has priority levels to thread all tasks at, these prio’s are ranged from -20 to +19 (negative = high prio, positive = low prio) with 0 as the default for all processes. So this being the fact, with everything operating at prio 0 you got fights between services as to who gets what resources first.
Solution? Very simply, que different processes at different priority levels to effectively discipline the system on who gets what resource access first.
The average load level of a server can be substantialy decreased by using SPRI, by as much as 5-20%, of course results may vary.
To install SPRI, execute the following commands (as root):
wget http://www.r-fx.ca/downloads/spri-current.tar.gz
md5sum spri-current.tar.gz | cut -d ‘ ‘ -f1
The md5sum should be bb04c53265ac374269050cacef3d8146. If not, then delete the file and download again.
Continue as follows:
tar -zxvf spri-current.tar.gz
cd spri-0.5
./installer.sh
cd ..
rm -rf spri*
SPRI is now installed. Next, edit the set of files at /usr/local/spri/prios/. These set of files define the priority of different processes. For e.g. /usr/local/spri/prios/high contains a single entry – httpd. This indicates that httpd (Apache server) will be run with the highest priority.
The changes we need to make are as follows (done as root):
Edit /usr/local/spri/prios/med and ensure that it contains the processes qmail, MailScanner and spamd [one per line].
Edit /usr/local/spri/prios/med-high and ensure that it contains the processes mysqld and mysqld-max [one per line].
Edit /usr/local/spri/prios/low and ensure that it contains the processes awffull, clamav, clamdscan, freshclam and python2.2 [one per line].
Edit /usr/local/spri/prios/low-med and ensure that it contains the processes php, php-script and proftpd [one per line].
If you are running any other applications, experiment and see which is the right priority with which you want the application to run, and add it to one of these files accordingly.
Run SPRI by executing the command: /usr/local/sbin/spri -v. SPRI will set the priorities of the processes defined and ensure they are run at their set priorities.
The SPRI installer automatically installs a cron job that runs every 45 minutes to check whether the priorities of the processes are as defined and set them accordingly if they are changed.
Installing SIM
SIM is a system and services monitor for SysVinit systems.
It works by consistently verifying that services are online, load averages are in check, and log files are at reasonable sizes. Many other SIM modules sport different and in-depth features to bring a well rounded tool to your disposal to stop otherwise common issues daunting internet hosts.
To install SIM, execute the following commands (as root):
wget http://www.r-fx.ca/downloads/sim-current.tar.gz
md5sum sim-current.tar.gz | cut -d ‘ ‘ -f1
The md5sum should be 6c1cece6f3af87598c4bdb09cabcb3cc. If not, then delete the file and download again.
Continue as follows:
tar -zxvf sim-current.tar.gz
cd sim-2.5-3
Run the installer by executing the command: ./setup -i. This will start the setup with the auto configuration option. First the GPL will be displayed. Next, the SIM readme is displayed. The binaries are then installed and the auto configuration section is started next.
Press ENTER to accept the default values till the question: “Where should alerts be emailed to?” is displayed. For this, fill in the email address to which SIM should send its reports and alerts. For e.g. I filled in mine as support@technofury.info
Again, press ENTER to accept the default values till the question: “Enable FTP service monitoring?” is displayed. For this, answer with the value: true.
Leave the answers to the other FTP questions at their defaults by pressing ENTER.
For the question: “Enable HTTP service monitoring?” answer with the value: true.
Leave the answers to the other HTTP questions at their defaults by pressing ENTER.
For the question: “Enable DNS service monitoring?”, answer with the value: true if you are running a DNS service on the server. Else, answer as false.
For the question: “Enable SSH service monitoring?”, answer with the value: true.
For the question: “Enable MYSQL service monitoring?”, answer with the value: true.
For the question: “Enable SMTP service monitoring?”, answer with the value: true.
For the question: “Enable XINET service monitoring?”, answer with the value: false.
For the question: “Enable ENSIM service monitoring?”, answer with the value: false.
For the question: “Enable PGSQL service monitoring?”, answer with the value: false.
For the question: “Enable semaphore cleanup?”, answer with the value: true.
For the question: “Enable URL aware monitoring?”, answer with the value: false.
For the question: “Enable HTTP log monitoring?”, answer with the value: true.
Leave the HTTP log file path at its default. Also, leave the maximum size of the HTTP log file at its default.
For the question: “Enable MYSQL Socket correction?”, answer with the value: true.
Leave the location of the /tmp symlink at its default.
For the question: “Enable NETWORK monitoring?”, answer with the value: true.
Next, fill in the interface to monitor. I have only one network card on my server and so the interface is eth0. If you have two or more cards, fill in the name of the external interface.
For the question: “Enable LOAD monitor?”, answer with the value: true.
Leave the ‘warning’ and ‘critical’ thresholds at their defaults.
For the question: “global (wall) message at status condition ‘warning’ & ‘critical’?” answer with the value: false.
Answer the remaining questions on load monitoring as false.
The configuration is now complete.
NOTE: If you make a mistake while configuring, press CTRL+C to abort. Then, restart the configurator by executing the command: /usr/local/sim/autoconf as root.
Run SIM by executing the command: /usr/local/sbin/sim -v as root. SIM will proceed to check the integrity of the system and then send you its reports and alerts to the designated email address.
Let us add SIM to a cron job such that it does this automatically every 5 minutes. Execute crontab -e (as root) and add the following line: */5 * * * * /usr/local/sim/sim -q >> /dev/null.
Installing PSAD
PSAD (Port Scan Attack Detector) is a collection of three lightweight system daemons written in Perl and C with the Linux Netfilter firewalling code to detect port scans and other suspect traffic. It features a set of highly configurable danger thresholds (with sensible defaults provided), verbose alert messages that include the source, destination, scanned port range, begin and end times, TCP flags and corresponding nmap options, email alerting, DShield reporting, and automatic blocking of offending IP addresses via dynamic configuration of iptables firewall rulesets. In addition, PSAD incorporates many of the TCP, UDP, and ICMP signatures included in Snort to detect highly suspect scans for various backdoor programs (e.g. EvilFTP, GirlFriend, SubSeven), DDoS tools (mstream, shaft), and advanced port scans (SYN, FIN, XMAS) which are easily leveraged against a machine via nmap. PSAD also implements the same passive OS fingerprinting algorithm used by p0f to passively fingerprint remote operating systems from which scans originate.
Get the rpm [RPM Bone] and execute the command rpm -Uvh psad-1.4.6-1.i386.rpm (as root) to install it. Then, you can either edit the configuration files manually or let Bastille do it automatically. I let Bastille do it automatically. If you want to edit the well commented configuration files, the files to tweak are: /etc/psad/psad.conf and /etc/psad/psadwatchd.conf.
Installing Bastille
Bastille is a hardening script for Red Hat. It helps to harden the server and close down potential security holes. Get the bastille rpm and execute the command: rpm -ivh Bastille-3.0.9-1.0.noarch.rpm (as root) to install it. Next, get the perl-Curses rpm and install it, by executing the command: rpm -Uvh perl-Curses-1.12-1.2.el4.rf.i386.rpm as root.
Start Bastille by executing the command: /usr/sbin/bastille -c (as root). Read through the instructions and follow the prompts to make your selections and harden the system.
Here are the choices I made:
- Disable clear text r-protocols – YES
- Password protect the GRUB prompt – NO. This is because I am working on a remote server and cannot boot the server if I password protect it. If you have physical access to the server, then you can set it to YES.
- Disable CRTl-ALT-DEL rebooting – NO
- Password protect single user mode – NO
- Set a default deny on TCP Wrappers and xinetd – NO
- Display “Authorized Use” messages at login time – NO
- Put limits on system resource usage – YES
- Restrict console access – YES
- Accounts that have console access – root michael [substitute with your regular user name]
- Set up process accounting – NO. You can enable this is you are truly paranoid.
- Deactivate HPOJ – YES
- Disable ISDN – YES
- Disable Apache – NO
- Bind Apache to listen only on localhost – NO
- Bind Apache to a particular interface – NO
- Disable user privileges on FTP daemon – NO
- Install TMPDIR/TMP scripts – YES
- Run the packet filtering script – YES
- Advanced Netowrking Services – NO
- DNS Servers – (Leave blank)
- Public Interfaces – eth+
- TCPservices to audit – imap pop3 exec login ssh ftp http
- UDP services to audit – 31337
- ICMP services to audit – echo-request
- TCP services to allow on public interfaces – 80 22 21 20 62000:64000 25 110 783 993 995. Ports 62000:64000 are for passive FTP.
- UDP services to allow on public interfaces. – (Leave blank). However if you are running a DNS server on the system, then open port 53 to allow DNS services.
- Force passive mode (for FTP) – YES
- TCP services to block – 2049 2065:2090 6000:6020 7100. These are the default values that are displayed. It is immaterial what you fill in here, since Centos uses iptables. These values matter only if you are using the older ipchains.
- UDP services to block – 2049 6770. These are the default values that are displayed. It is immaterial what you fill in here, since Centos uses iptables. These values matter only if you are using the older ipchains.
- ICMP allowed types – destination-unreachable echo-reply time-exceeded
- Enable source address verification – YES
- Reject method – DENY
- Interfaces for DHCP queries – eth0. Fill in your public interface here. I have only one network card with a static address and therefore it is eth0. If you are connecting using PPP modem, the your interface might be ppp0 for example.
- NTP servers to query – (Leave blank). This is the default value that is displayed. It is immaterial what you fill in here, since Centos uses iptables. These values matter only if you are using the older ipchains.
- ICMP types to disallow outbound – destination-unreachable time-exceeded
- Should Bastille run the firewall and enable it at boot time – YES
- Would you like to set up PSAD – YES
- PSAD check interval – 15
- Port range scan threshold – 1
- Enable scan persistance – NO
- Scan timeout – 3600
- Show all scan signatures – NO
- Danger levels – 5 50 1000 5000 10000
- Email address – Enter the email address of the person to which the port scan alerts are sent.
- Email alert danger level – 1
- Alert on all new packets – YES
- Enable automatic blocking of scanning IPs – NO
- Enable PSAD at boot time – YES
- Make these changes – YES
Edit /etc/psad/psad.conf (as root), find the line that reads ENABLE_DSHIELD_ALERTS and set it to YES. The line should read: ENABLE_DSHIELD_ALERTS Y;
The scan logs will then be sent to Dshield which tracks the malicious people. Next, execute the command: /usr/sbin/ntsysv (as root), deselct iptables and ensure that both bastille-firewall and psad are selected. Now, the selected services will be automatically started at the next boot. To start these services without rebooting, first execute the command: /etc/init.d/iptables stop to stop iptables. Next execute the commands: /etc/init.d/bastille-firewall start and /etc/init.d/psad start to start bastille-firewall and psad. PSAD will automatically alert you to port scans form now on.
Note: Bastille will throw up a string of warning messages indicating that it has detected Centos as Red Hat 9. This is OK and does not do any damage to the server.
If you want to remove all settings that Bastille has done and revert back to the settings before running Bastille, then execute the command: /usr/sbin/bastille -r (as root) and follow the prompts.
Installing eAccelerator
eAccelerator is a free open-source PHP accelerator, optimizer, encoder and dynamic content cache. It increases the performance of PHP scripts by caching them in their compiled state, so that the overhead of compiling is almost completely eliminated. It also optimizes scripts to speed up their execution. eAccelerator typically reduces server load and increases the speed of your PHP code by 1-10 times.
Get the eAccelerator rpm [Dag Wieers repository ] and execute the command: rpm -Uvh php-eaccelerator-4.3.9_0.9.3-2.2.el4.rf.i386.rpm (as root) to install it.
Replace the eaccelerator.ini file in /etc/php.d with this. Then restart Apache by executing the comand: /sbin/service httpd restart (as root). eAccelerator is now happily caching your PHP scripts.
Installing Mytop
Mytop is a console based top clone for monitoring the threads and overall performance of a MySQL 3.22.x, 3.23.x, and 4.x server.
Download the mytop rpm [Dag Wieers]. Next download perl-Term-ReadKey rpm [Dag Wieers]. Finally download the perl-TimeDate rpm. Install the downloaded packages by executing the command: rpm -Uvh [package name] as root.
Next, create the configuration file by running the command vi /root/.mytop as root with the following contents:
user=root
pass= [Specify the mysql password]
host=localhost [You can change this to a host name or IP in case you have mysql on a different server]
db= [Fill in the database to be monitored]
delay=5
port=3306
socket=/var/lib/mysql/mysql.sock [Leave this blank, if you specify a different hostname in the host field]
batchmode=0
header=1
color=1
idle=1
Start mytop with the command mytop as root and monitor your mysql database. Read this page for the configuration options.
Installing vnStat
vnStat is a network traffic monitor for Linux that keeps a log of daily network traffic for the selected interface(s).
To install vnStat, execute the following commands as root:
cd /root
wget http://humdi.net/vnstat/vnstat-1.4.tar.gz
md5sum vnstat-1.4.tar.gz | cut -d ” ” -f1
The md5sum should be 9184f79b5e60499bc059f670032291e5. If it is not, then delete the file and download again. Continue as follows:
tar -xvzf vnstat-1.4.tar.gz
cd vnstat-1.4
make && make install
vnstat -u -i eth0
Replace eth0 with the interface you wish to monitor. Wait for 5 mins for the initial statistics to be generated. Then run vnstat to view the stats.
Let us add vnStat to a cron job such that it updates the statistics periodically. Execute the command: crontab -e (as root) and add the cron entry: 0-55/5 * * * * vnstat -u. Save the cron entry. vnStat should update the statistics every 5 minutes.
Delete the downloaded files by executing the commands: cd /root and then rm -rf vnstat* as root.
Next, let us install a PHP frontend to vnStat to view the stats easily through a web based interface. Execute the following commands (as root):
cd /var/www/html/
wget http://www.sqweek.com/sqweek/files/vnstat_php_frontend-1.2.1.tar.gz
md5sum vnstat_php_frontend-1.2.1.tar.gz | cut -d ” ” -f1
The md5sum should be f9e6dced64bfc464f8445cad5d5ae891. If it is not, then delete the file and download it again. Continue as follows:
tar -xvzf vnstat_php_frontend-1.2.1.tar.gz
mv vnstat_php_frontend-1.2.1 net-stats
rm -rf vnstat_php_frontend-1.2.1.tar.gz
cd net-stats
Edit config.php. Find the line that reads:
$iface_list = array(‘eth0′, ‘eth1′);
Edit it to your liking. Add in the interfaces that you want to monitor.
Next find the lines that read:
$iface_title['eth0'] = ‘External’;
$iface_title['eth1'] = ‘Internet’;
$iface_title['sixxs'] = ‘SixXS IPv6′;
Edit it to match the interfaces defined in the previous line and name it as per your liking. Next, navigate to http://yourdomain.com/net-stats to view the statistics.
Let us secure vnStat that only authorised people can see the statistics. First, generate the password by executing the command: htpasswd -c /usr/local/vnstatpass [name of the authorised user]. Enter the desired password twice. The password is generated and stored.
Edit /etc/httpd/conf/httpd.conf and add the following:
[Directory /var/www/html/net-stats/]
AuthType Basic
AuthName “Private Access”
AuthUserFile /usr/local/vnstatpass
Require user [name of the authorised user]
[/Directory]
Note: Change the square brackets to angle brackets.
Restart Apache by executing the command: /sbin/service httpd restart. Navigate to http://www.yourdomain.com/net-stats/, enter the username and password and view the statistics.
Final Touches
Edit /etc/httpd/conf/httpd.conf (as root) and comment out all the modules that are not needed. For example, the module block from my server looks like the following:
LoadModule access_module modules/mod_access.so
LoadModule auth_module modules/mod_auth.so
LoadModule auth_anon_module modules/mod_auth_anon.so
LoadModule auth_dbm_module modules/mod_auth_dbm.so
LoadModule auth_digest_module modules/mod_auth_digest.so
#LoadModule ldap_module modules/mod_ldap.so
#LoadModule auth_ldap_module modules/mod_auth_ldap.so
LoadModule include_module modules/mod_include.so
LoadModule log_config_module modules/mod_log_config.so
#LoadModule env_module modules/mod_env.so
LoadModule mime_magic_module modules/mod_mime_magic.so
LoadModule cern_meta_module modules/mod_cern_meta.so
LoadModule expires_module modules/mod_expires.so
LoadModule deflate_module modules/mod_deflate.so
LoadModule headers_module modules/mod_headers.so
LoadModule usertrack_module modules/mod_usertrack.so
LoadModule setenvif_module modules/mod_setenvif.so
LoadModule mime_module modules/mod_mime.so
#LoadModule dav_module modules/mod_dav.so
LoadModule status_module modules/mod_status.so
LoadModule autoindex_module modules/mod_autoindex.so
#LoadModule asis_module modules/mod_asis.so
LoadModule info_module modules/mod_info.so
#LoadModule dav_fs_module modules/mod_dav_fs.so
LoadModule vhost_alias_module modules/mod_vhost_alias.so
LoadModule negotiation_module modules/mod_negotiation.so
LoadModule dir_module modules/mod_dir.so
LoadModule imap_module modules/mod_imap.so
LoadModule actions_module modules/mod_actions.so
#LoadModule speling_module modules/mod_speling.so
LoadModule userdir_module modules/mod_userdir.so
LoadModule alias_module modules/mod_alias.so
#LoadModule rewrite_module modules/mod_rewrite.so
#AddModule mod_rewrite.c
LoadModule rewrite_module modules/mod_rewrite.so
#LoadModule proxy_module modules/mod_proxy.so
#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
#LoadModule proxy_http_module modules/mod_proxy_http.so
#LoadModule proxy_connect_module modules/mod_proxy_connect.so
#LoadModule cache_module modules/mod_cache.so
LoadModule suexec_module modules/mod_suexec.so
#LoadModule disk_cache_module modules/mod_disk_cache.so
#LoadModule file_cache_module modules/mod_file_cache.so
#LoadModule mem_cache_module modules/mod_mem_cache.so
LoadModule cgi_module modules/mod_cgi.so
LoadModule security_module /usr/lib/httpd/modules/mod_security.so
LoadModule evasive20_module /usr/lib/httpd/modules/mod_evasive20.so
#
# Load config files from the config directory “/etc/httpd/conf.d”.
#
Include conf.d/*.conf
Save the file and execute the command: /sbin/service httpd restart (as root) to restart Apache with the changes.
Next, execute the command: /usr/sbin/ntsysv and disable all unwanted services. For example, the services running on my server are the following:
- anacron
- arptables_jf
- crond
- freshclam
- haldaemon
- httpd
- bastille-firewall
- messagebus
- mysqld
- network
- proftpd
- psad
- qmail
- smartd
- sshd
- syslog
Optionally you could secure SSH by doing the following:
Make a backup of the existing SSH configuration file by executing the command: cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
Replace the contents of /etc/ssh/sshd_config with this.
Edit /etc/ssh/sshd_config and change the following lines:
- Find the line that reads:#ListenAddress 0.0.0.0 and change it to the address from which SSH should accept connections. For e.g. if you want SSH to accept connections only from IP 62.131.74.136, then change this line to ListenAddress 62.131.74.136
- Next, configure SSH to allow only certain users to login. For example, if you want only users bob and tim to login to SSH, add the line AllowUsers bob tim.
- Change the port on which SSH runs. The standard port is 22, but you can change it to a higher port (any port above 1024). For example, to allow SSH to run on port 2365, change the line that reads Port 22 to Port 2365. If you do change the port number, be sure to change 22 in the Bastille script above to the chosen SSH port number.
Restart SSH by executing the command: /etc/init.d/sshd restart as root.
To perform additional miscellaneous security tweaks, download this script and execute it as root (sh misc-sec-tweaks).
To secure the temporary partitions, download this script (mk-tmp) and execute it as root (sh mk-tmp).
Add the following line to /etc/host.conf as root:
# Check for IP address spoofing.
nospoof on
This will stop IP spoofing dead in its tracks.
Next, get a list of installed packages (yum list installed) [as root], go through them with a fine comb and remove all unwanted packages. To remove a package, execute the command: yum remove [package name] (as root).
At the end of all this, you should have a fast, secure server. Happy serving.
Handy Reference
Creating a virtual domain in qmail – Execute the command: /home/vpopmail/bin/vadddomain [domain name] [postmaster password].
Deleting a virtual domain in qmail – Execute the command: /home/vpopmail/bin/vdeldomain [domain name].
Adding an email user in qmail: Execute the command: /home/vpopmail/bin/vadduser [user@domainname] [password].
Deleting an email user in qmail: Execute the command: /home/vpopmail/bin/vdeluser [user@domainname].
Accessing the qmail admin page: http://domain.com/admin-toaster/. The username is admin and the temporary password is toaster. Be sure to change the password after logging in.
Accessing squirrelmail: Navigate to http://domain.com/webmail/. Login with the full email address and the password.
Awffull stats are at: http://domain.com/usage/.
vnStats stats are at: http://domain.com/net-stats/.
Written by Michael R.M. David

[...] Faster Pc for You wrote an interesting post today onHere’s a quick excerpt Centos is an enterprise class Linux distribution that is built from the sources of Red Hat . It performs very well as a server as well as a workstation. This guide will show you how to quickly install and configure Centos as a server with Apache 2, Qmail and Proftpd on an x86 (32 bit) system. This quick configuration guide assumes that you know how to perform an initial Red Hat/Centos installation. If not, then do read the installation guide first before proceeding. First Steps After a basic [...]
I really liked the information shared in this blog.It makes me more knowledgable towards it.I am waiting for your next post.
The information provided in this thread is really useful
Very great post. I simply stumbled upon your blog and wanted to say that I’ve really enjoyed browsing your blog posts. After all I’ll be subscribing for your feed and I am hoping you write again very soon!