Server security audit is a continuous process and it is important that the servers are secure from vulnerabilities and hacker. As we know, the security of a server is quite essential as long as it is active. In most cases, a mistake happens during the initial server set up will lead to a disaster at later period of time. In this post I am trying to prepare a check list for the initial server hardening of a cPanel server. Preparing a check list and follow it will ensure the implementation of necessary security settings. Let us see some of the Linux Server security Guidelines.
SSH Security
SSH Warning Message
Enable the default Banner path by modifying the sshd configuration file /etc/ssh/sshd_config . For that open the SSHD configuration file in your favourite editor and then search for the directive “Banner”. By default it will be disabled in most installations, so the entry would look like
#Banner /etc/issue.net
Now remove the comment tag and specify the banner file, by the common practice is to use /etc/issue , however you can use your own file. Now the entry would look like
Banner /etc/issue
Check whether the file exists. If so edit it with the warning message. Otherwise create or open the file /etc/issue add the warning message.
I use the following one. You can use your own content to make the warning
###############################################################
Authorized access only!
# Disconnect IMMEDIATELY if you are not an authorized user!!! #
# All actions Will be monitored and recorded #
# Unauthorized access is forbidden and will be prosecuted by law #
###############################################################
Once the file is saved, we need to restart the service. Use the following command to restart SSHD
/etc/init.d/sshd restart
Once it is restarted, ensure that the message pops up for all SSH access.
Custom SSH port
Changing the SSH port to a custom one will increase security. This can be performed by changing the default value assigned to the directive “Port” in the configuration file /etc/ssh/sshd_config
Port 22666
Once the modification is completed, restart the sshd server and check whether you are able to connect to the new port.
You can check it using the following command
$ telnet 192.168.1.105 22666
Trying 192.168.1.105
Connected to 192.168.1.105
Escape character is ‘^]’.
SSH-2.0-OpenSSH_4.3
Once you are able to connect, login to the server and confirm everything is working. Don’t close the current shell until the modification is confirmed to be working. Otherwise you might get locked out from the server.
Disable Direct root access
Disabling direct root access provides two levels of security. The login needs to be performed as a normal ssh user first and then switch to root user. This necessitates two valid logins and passwords. Also only privileged users are permitted to switch to root, that too provides another level of security.
To disable direct root login, modify the configuration file and disable the corresponding directive to look like the following one
PermitRootLogin no
SSH user creation
Existence of an SSH user who can switch to root is essential when direct root access is disabled. The process is simple, you simply need to create a normal ssh user and then add the user to wheel group . For eg. I have created the user as “admin” and below is the commands I used to complete the process
adduser admin
passwd admin
usermod -g wheel username
Changing the group can be done either through WHM or by editting the /etc/group file. Confirm the process by performing the following test
#grep wheel /etc/group
wheel::10:root,admin
It confirms that the ssh user “admin” is a member of wheel group. Since all wheel group users are privileged to switch to superuser, he can switch to the root account.
Restart the sshd service and once it is done. Try to login to the server as root and it should fail.
Securing /tmp Partition
To protect your server from local and remote exploits being executed from your /tmp folder, we need to mount it using noexec. To mount /tmp and /var/tmp with noexec and nosuid on your server, modify /etc/fstab and put the entry like this
/dev/sda5 /tmp ext3 noexec,nosuid 1 2
On cPanel servers,. there is a script to perform the task. You simply need to execute the following script as root
/scripts/securetmp
Confirm the modification by executing the command “mount” and you should be able to see the options on the result.
Basic Firewall Settings
Firewalls are essential to identify and defend attacks. I am listing a few essential Firewalls to be implemented on a Linux server.
Maldet
Malware detection is quite difficult and demanding on a shared hosting environment.Maldet is a server security audit tool which will help you to identify the infected files and quarantine them. Follow the steps to perform the installation
cd /usr/local/src
wget http://www.rfxn.com/downloads/maldetect-current.tar.gz
tar -xzvf maldetect-current.tar.gz
cd maldetect-*
sh install.sh
Once this is installed, you should be able to perform various tests using the command “maldet ”
CSF & LFD
CSF and LFD is another useful tool in server security audit.It provides network and access level security. Before proceeding with CSF installation, make sure to remove pre existing firewall installations like apf. Having two firewalls running at the same time is a recipe for problems and could make your server unstable or unusable.
CSF and LFD are very easy to install and to configure – especially if you are using a cpanel & WHM server.
cd /usr/local/src
wget http://www.configserver.com/free/csf.tgz
tar -xvzf csf.tgz
cd csf
./install.cpanel.sh
Once the installation is complete, restart CSF in Testing mode
/etc/init.d/csf restart
once it is up, check whether you are able to access the server and other services from outside using another shell.
This
includes ftp, mail (in and out), http, cpanel, whm, etc .Make sure you are able to login to the server using SSH using the port configured. Once everything is confirmed to be of working, disable testing mode
vi /etc/csf/csf.conf
Then locate the directive
TESTING = "1"
change it to
TESTING = "0"
Then restart CSF
/etc/init.d/csf restart
Once CSF installed you can manage CSF firewall from WHM >>CSF Security & Firewall option under “Plugin” section. CSF/LFD comes pre-configured for a cpanel/WHM server and so there is not that much to do after the installation.
Rkhunter
Rootkit detection is difficult because a rootkit may be able to subvert the software that is intended to find it. Identification of root kits is essential if you are working on a hacked machine. There is high possibility that the binaries get altered. Rootkit identification is performed through various applications and Rkhunter is one of the most popular one. Below are the steps to perform the installation
cd /usr/local/src
download the latest version from the URL http://sourceforge.net/projects/rkhunter/files/rkhunter/
here I am using the following one
wget http://sourceforge.net/projects/rkhunter/files/latest/download?source=files
tar -xzvf rkhunter-1.4.0.tar.gz
cd rkhunter-1.4.0
./installer.sh
Once it is installed check for rootkits, using the command
rkhunter -c
cPanel and Service Management
cPanel is the most crucial application on the server and through which we manage all other services. Below are some of setting we commonly use to secure and optimise the server performance.
Upgrade to the latest version
WHM -> Server configuration -> Update preferences -> Cpanel and WHM updates -> select the Release tier to “Release”
All other can be selected to be “Automatic”
Then execute the following from the shell “/scripts/upcp “
After completion of the process check the version on your WHM and compare it with the release version of cPanel
Recompile php and apache
Recompile Apache and php with the required modules using the script /scripts/easyapache . After completion of the process, make sure apache is up and php shows new compilation date and compiled modules.
Disable functions which are known to be threats security, by adding the following line on the corresponding location of php.ini
disable_functions = “show_source, system, shell_exec, passthru, exec, phpinfo, popen, proc_open, symlink,proc_close,proc_open, popen, dl, passthru, escapeshellarg, escapeshellcmd, disk_free_space, disk_total_space, sysInfo, memTotal, memUsed, memFree, memCached, memBuffers, get_memory”
Safe_mode protection
In PHP, safe mode is a security feature that was designed to prevent hackers from being able to use PHP scripts to execute commands at the operating system level (such as Linux shell commands).
Open php.ini and enable the directive safe_mode to acivate it.
php -i | grep php.ini
Configuration File (php.ini) Path => /usr/local/lib
Loaded Configuration File => /usr/local/lib/php.ini
safe_mode = On
Eaccelerator session save path
By default the session files will be stored one /tmp/eaccelerator, this can make /tmp to run out of disk space . To avoid this issue, change the session save path to some other location say /home/eaccelerator. The steps are as follows
Create the directory /home/eaccelerator and modify the corresponding variable in php.ini file
eaccelerator.cache_dir=”/home/eaccelerator”
once the modification is done, restart webserver
Enable SuPHP
Setting up of SuPHP as php handler and enabling apache SuExec, improves security significantly. You can do this directly from WHM under the section “Configure PHP and SuExec” ( Main >> Service Configuration >> Configure PHP and SuExec”)
Select SuPHP from the drop down for “PHP 5 Handler” and save.
Change the permission of folders on the server to 755 to obey suphp guide lines
find /home/*/public_html/ -type d -print0 | xargs -0 chmod 0755
Change the file permissions to 644 using the command
find /home/*/public_html/ -type f -not -name “*.pl” -not -name “*.cgi” -not -name “*.sh” -print0 | xargs -0 chmod 0644
Change the permission for .cgi and .pl files to 755
find /home/*/public_html/ -type f -name “*.cgi” -print0 -o -name “*.pl” -print0 -o -name “*.sh” -print0 | xargs -0 chmod 0755
Change ownership of the files to the users
cat /etc/trueuserdomains | awk {‘print $2’} >> users.txt
for i in `cat users.txt`; do chown -R $i:$i /home/$i/public_html/*; echo $i; done
Mod_Sec installation
Installation of Mod-security is essential for defending attacks through web, particularly sql injections. Modsec is an apache module and it needs to be enabled using /scripts/easyapahce if not install it manually.
Reference URL
http://www.atomicorp.com/wiki/index.php/Atomic_ModSecurity_Rules#Optional_Manual_Installation
Below are steps followed for a quick install
create the necessary directories.
mkdir /etc/httpd/modsecurity.d
mkdir /var/asl
mkdir /var/asl/tmp
mkdir /var/asl/data
mkdir /var/asl/data/msa
mkdir /var/asl/data/audit
mkdir /var/asl/data/suspicious
Change the ownership of directories to that of web server user. Since we use cPanel and the default apache user is “nobody” , the command should be given is
chown nobody.nobody /var/asl/data/msa
chown nobody.nobody /var/asl/data/audit
chown nobody.nobody /var/asl/data/suspicious
Change the permissions for the directories as well
chmod o-rx -R /var/asl/data/*
chmod ug+rwx -R /var/asl/data/*
Create necessary directories for future updates.atomicorp.com
mkdir /var/asl/updates
mkdir /var/asl/rules/
mkdir /var/asl/rules/clamav
Create a file to bypass mod_Sec checks. Domains which needs to be bypassed from mod_Sec checks can be mentioned on this file
mkdir /etc/asl
touch /etc/asl/whitelist
INSTALLATION
cd /usr/local/src
mkdir modsec
cd modsec/
wget http://updates.atomicorp.com/channels/rules/delayed/modsec-2.5-free-latest.tar.gz
tar -xzvf modsec-2.5-free-latest.tar.gz
mkdir /usr/local/apache/conf/modsec_rules
cd modsec
cp * /usr/local/apache/conf/modsec_rules/
cd /usr/local/apache/conf
Take a backup of the existing modsec2.conf
cp -pr modsec2.conf modsec2.conf.bak_ssages
NOTE
The document instructs to make the modification in the user configuration file ie “/usr/local/apache/conf/modsec2.user.conf” to make it permanent or to withstand cPanel and apache updates. But it didn’t work for me, so made the modification in the main configuration file itself ie /usr/local/apache/conf/modsec2.conf
The file would look like
# cat modsec2.conf
LoadFile /opt/xml2/lib/libxml2.so
LoadFile /opt/lua/lib/liblua.so
LoadModule security2_module modules/mod_security2.so
<IfModule mod_security2.c>
SecRuleEngine On
SecRequestBodyAccess On
SecResponseBodyAccess On
SecResponseBodyMimeType (null) text/html text/plain text/xml
SecResponseBodyLimit 2621440
SecServerSignature Apache
SecComponentSignature 200911012341
SecUploadDir /var/asl/data/suspicious
SecUploadKeepFiles Off
SecAuditEngine RelevantOnly
SecAuditLogRelevantStatus “^(?:5|4(?!04))”
SecAuditLogType Concurrent
SecAuditLog logs/audit_log
SecAuditLogParts ABIFHZ
SecArgumentSeparator “&”
SecCookieFormat 0
SecRequestBodyInMemoryLimit 131072
SecDataDir /var/asl/data/msa
SecTmpDir /tmp
SecAuditLogStorageDir /var/asl/data/audit
SecResponseBodyLimitAction ProcessPartial
SecAuditLogDirMode 0770
SecPcreMatchLimit 150000
SecPcreMatchLimitRecursion 150000
Include /usr/local/apache/conf/modsec_rules/10_asl_antimalware.conf
Include /usr/local/apache/conf/modsec_rules/10_asl_rules.conf
Include /usr/local/apache/conf/modsec_rules/20_asl_useragents.conf
Include /usr/local/apache/conf/modsec_rules/30_asl_antispam.conf
Include /usr/local/apache/conf/modsec_rules/50_asl_rootkits.conf
Include /usr/local/apache/conf/modsec_rules/60_asl_recons.conf
Include /usr/local/apache/conf/modsec_rules/99_asl_jitp.conf
</IfModule>
Though there are a lot of custom rules, the mentioned above are sufficient and recommended for a cPanel server. I f you come across the following error
Cpanel Error Messages
Rule execution error – PCRE limits exceeded (-8): (null).
1. Add to your PHP.INI the following:
pcre.backtrack_limit = 150000
pcre.recursion_limit = 150000
2. And make sure your MODSEC2.USER.CONF or /usr/local/apache/conf/modsec2.conf file contains following ( as shown in the sample configuration file above)
SecPcreMatchLimit 150000
SecPcreMatchLimitRecursion 150000
Once everything is configured, check whether there is any syntax errors by using the command
# /usr/local/apache/bin/apachectl configtest
Syntax OK
Then restart the webserver either through cPanel scripts or from the back end scripts
/usr/local/apache/bin/apachectl stop
/usr/local/apache/bin/apachectl startssl
ps aux | grep httpd
Once the webserver is up, we need to ensure that the rules are actually working. For the execute the following command from the shell
wget http://localhost/foo.php?foo=http://www.example.com
If everything is working you should get a 403 error message as given below
# wget http://localhost/foo.php?foo=http://www.example.com
–2012-09-09 18:33:12– http://localhost/foo.php?foo=http://www.example.com
Resolving localhost… 127.0.0.1
Connecting to localhost|127.0.0.1|:80… connected.
HTTP request sent, awaiting response… 403 Forbidden
2012-09-09 18:33:12 ERROR 403: Forbidden.
Now confirm the activity of the rules dynamically by checking the apache error log
# tail -f /usr/local/apache/logs/error_log | grep ModSecurity
[Sun Sep 09 18:34:46 2012] [error] [client 10.11.10.6] ModSecurity: Access denied with code 403 (phase 2). Pattern match “[-_ ]?(?:adipex|suboxone|pseudovent|topamax|trazodone|prevacid|zyrtec|[msg “Atomicorp.com UNSUPPORTED DELAYED Rules: Possible Spam or Restricted content: Pharmacy and/or Drug content detected”] [data ” levitra “] [severity “CRITICAL”] [hostname “kkkkk.com”] [uri “/forum/newthread.php”] [unique_id “UExwxq6Kp9sAAE87RpEAAAAJ”]
Now, you can confirm that everything is configured properly and can proceed to the next step.
WHM Tweaks
Enable the following in Tweak settings
In most cases, the default would be fine. Make sure the following are enabled to avoid spamming
Track email origin via X-Source email headers
Max hourly emails per domain ( default will be unlimited, but a value of 400 would be ideal)
Enable SpamAssassin spam filter
If you plan to provide basic shell access along with all shared account, make sure to restrict it to jailed shell.
Default shell jailed ( if you want to provisde shell access to the clients)
Check for unauthorised wheel group users and remove them if any
Compiler Access – Disable
PHP open_basedir Protection
Shell Fork Bomb Protection
SSH Password Authorization Tweak
Make sure to configure contact details on the cPanel under the section
Server Contacts
Check the following in service configurations. In most cases default sgould be okay , change the following in accordance to your needs
Apache
SSL Cipher Suite – PCI recommended
Trace Enable Off
Server Signature Off
Keep-Alive Off
Exim Service configurations
Log sender rates in the exim mainlog ON
RBL: bl.spamcop.net ON
RBL: zen.spamhaus.org ON
Advanced editor
log_selector +all
Manage Service SSL Certificates – ensure that all are installed and are not expired
Service Manager – make sure to configure critical services to be monitored continuesly
Backup – make sure backup is configured as per the requirement
FTP Tweaks
Use pure_ftp as the default FTP server and disable the following settings
Allow Anonymous Logins
Allow Anonymous Uploads
Allow Logins with Root Password
Broken Clients Compatibility
Defaults should be fine for other values
cPanel – manage plugins
make sure clam av and spamassasin are installed
MySQL optimisation too is required and a general pattern may not work here as it varies according to the needs