Linux Server Security

An apple a day keeps the doctor  away 🙂

Whenever  i login to my servers i will execute  the following simple commands before starting any other works.

a) “ w “ to check server load , server uptime and the users who are logged in

b) “df -h “ to confirm none of the drives diskspace are critical

  1. top -c “ ( shift +m will sort the process memory wise and shift+ p will sort the process cpu usage wise ) and confirm no strange process are running.
  1. check /tmp using “ ls -la “ and confirm no suspicious files are present

As we you might see , the above task will take less than 5 minutes and the result will be worth the effort.

Prevention is always better than cure

Linux is secure , but its a tedious job for an admin to keep his/her server safe and secure always. Every day we are facing new new threats and vulnerabilities.  If we are concerned about your server security then it should be mandatory to do atleast the following tweaks in your server .

Phase 1 : Installations

1) Install and configure Firewall + LFD (CSF)

http://www.configserver.com/cp/csf.html

Feataures :-

  • Easy Installation and Configuration
  • Brute Force Attack Prevention
  • Server Security Checks
  • Port scan prevention and blocking
  • Intrusion detection system
  • IP Blocking and more..

Installation and configuration :-

# cd /etc

# wget http://www.configserver.com/free/csf.tgz

# tar zxf csf.tar.gz

# sh csf/install.sh

( Specify which ports you want to allow )

# vi /etc/csf/csf.conf

# Allow incoming TCP ports

TCP_IN = “20,21,22,25,53,80,110,143,443,465,953,993,995,3306,3434”

# Allow outgoing TCP ports

TCP_OUT = “20,21,22,25,37,43,53,80,110,113,443,587,873,953,3306,3434”

# Allow incoming UDP ports

UDP_IN = “20,21,53,953”

# Allow outgoing UDP ports

# To allow outgoing traceroute add 33434:33523 to this list

UDP_OUT = “20,21,53,113,123,873,953”

#If you are happy with the setting then we can change the testing mode as follows

#Disable the Testing Mode and Start the Firewall

TESTING = “0”

Save the file and restart the firewall!

# csf -r


2 ) Install and configure rootkit detection software – Rkhunter

rkhunter (Rootkit Hunter) is a unix based tool that scans for rootkits ,backdoors and possible local exploits. It does this by comparing SHA hashes of important files with known good ones in online database, searching for default directories (of rootkits), wrong permissions, hidden files, suspicious strings in kernel modules, and special tests for Linux and Freebsd.

Login to your server via SSH as root then Type

# cd /usr/local/src

Download the latest Version of RKHunter

http://sourceforge.net/projects/rkhunter/

# tar -xzf rkhunter-tar.gz

# cd rkhunter-1.3.6

# ./installer.sh –layout /usr/local –install

# rkhunter -c will scan the server for known rootkits.

Lets setup RKHunter to e-mail you daily scan reports.

# vi /etc/cron.daily/rkhunter.sh

Add The Following:

#!/bin/bash

/usr/local/bin/rkhunter -c –cronjob 2>&1 | mail -s “RKhunter Scan Details”  alerts[at]adminlogs.info


3) Scan and harden /tmp /var/tmp directories

Its always better to create a separate partition for /tmp, Also we need to confirm /tmp is clean. To know more about linux /tmp hack , click here : /tmp hack

# dd if=/dev/zero of=/dev/tmpFS bs=1M count=1500
The above will create a file with 1.5Gb size ,we can change the size of the file as per our need.

# /sbin/mkfs.ext3 /dev/tmpFS

will create a ext3 partition

# take the back up of current /tmp
cp -Rpf /tmp /tmpbackup

# mount the newly created file system as no exec and nosuid
mount -o loop,noexec,nosuid,rw /dev/tmpFS /tmp

# apply stikybit permission to /tmp
chmod 1777 /tmp

# Restore the old /tmp
cp -Rpf /tmpbackup/* /tmp/

For securing /dev/shm mount it as follows in /etc/fstab
# vi /etc/fstab

tmpfs /dev/shm tmpfs defaults,nosuid,noexec,rw 0 0

/var/tmpMnt /tmp ext2 loop,noexec,nosuid,nodev,rw 0 0

# mount -o remount /dev/shm

We should do the same for /var/tmp also , because some applications will use /var/tmp as temporary folder and its also a public place.

# mv /var/tmp /var/tmp.bkp

# ln -s /tmp /var/tmp

NB :- we should restart the services like mysql and clamd which are using /tmp or /var/tmp for socket file creation

 

4) Install Mod_security apache module with latest custom rules

ModSecurity is a free opensource web application firewall which can help you to guard against LFI (local file inclusion attacks) and SQL injection vulnerabilities.

# cp -pr /etc/httpd/conf /etc/htpd/conf.bkp

# yum install libxml2 libxml2-devel httpd-devel

# Download latest verstion of mod_secuirty module

wget http://www.modsecurity.org/download/modsecurity-apache_2.*.tar.gx

# tar zxf modsecurity-apache_2.*.tar.gz
# cd modsecurity-apache_2.*
# cd apache2

# ./configure

# make & make install

# vi /etc/httpd/conf/httpd.conf

LoadModule unique_id_module modules/mod_unique_id.so
LoadFile /usr/lib/libxml2.so
LoadModule security2_module modules/mod_security2.so
Include conf/modsecurity/*.conf

# /etc/init.d/httpd restart

NB :- I will prefer to compile apche as DSO and this will help us to install additional modules using the tool apxs ( Apache extented services )
For example
download the mod_security module and untar
# cd mod_security
# <apache-home>/bin/apxs -cia mod_security.c
the above will do all the above with out effecting the currently running apache.


5) Install Antivirus toolkit ClamAV

Clam AntiVirus is an open source (GPL) anti-virus toolkit for UNIX, designed especially for e-mail scanning on mail gateways. It provides a number of utilities including a flexible and scalable multi-threaded daemon, a command line scanner and advanced tool for automatic database updates. The core of the package is an anti-virus engine available in a form of shared library.

Here is a list of the main features:

  • command-line scanner
  • fast, multi-threaded daemon with support for on-access scanning
  • milter interface for sendmail
  • advanced database updater with support for scripted updates and digital signatures
  • virus scanner C library
  • on-access scanning (Linux® and FreeBSD®)
  • virus database updated multiple times per day (see home page for total number of signatures)
  • built-in support for various archive formats, including Zip, RAR, Tar, Gzip, Bzip2, OLE2, Cabinet, CHM, BinHex, SIS and others
  • built-in support for almost all mail file formats
  • built-in support for ELF executables and Portable Executable files compressed with UPX, FSG, Petite, NsPack, wwpack32, MEW, Upack and obfuscated with SUE, Y0da Cryptor and others

# create a user for clamav to use:
useradd clamav
Some OS’s require you to add the group as well:
groupadd clamav
Don’t worry if the user and/or group already exist.

# Download the latest stable ClamAV distribution from http://www.clamav.net
Note: If you are running Fedora Core 4 or earlier, you cannot install any version of ClamAV later than 0.91.2 because of a broken gcc.

# Expand the distribution and cd into the resultant directory and build ClamAV using:
tar -xzf clamav-*
cd clamav*
./configure –disable-zlib-vcheck
make
make install

# vi  /usr/local/etc/freshclam.conf
Comment out the line (put a # as the first character on the line) near the top that says simply:
Example

# vi  /usr/local/etc/clamd.conf
Comment out the line (put a # as the first character on the line) near the top that says simply:
Example

# vi  /usr/local/etc/clamd.conf
Change the following line:
#LocalSocket /tmp/clamd.socket
to this:
LocalSocket /tmp/clamd

# Run ldconfig to create the necessary links and cache to most recent shared libraries
ldconfig

# Run freshclam to download the latest definitions:
freshclam

# To scan the folder

clamscan -r /home

Note: The following will no longer work as ClamAV has decided not to include the init examples in their latest version. You will have to create your own init script to start clamd or download an old version of ClamAV (pre-v0.95) and get the init script from there.

/bin/cp -fv contrib/init/RedHat/clamd /etc/init.d/clamd
chown root:root /etc/init.d/clamd
chmod +x /etc/init.d/clamd
chkconfig clamd on
service clamd restart


6) Install and configure mod_evasive

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 etc. mod_evasive can stand up to even large attacks. Its features will prevent you from wasting bandwidth or having a few thousand CGI scripts running as a result of an attack.

Login too your server and execute

# cd /usr/local/src
# wget http://www.sfr-fresh.com/unix/privat/mod_evasive_1.10.1.tar.gz
# tar -xzvf mod_evasive_1.10.1.tar.gz
# cd mod_evasive
# cd apache 2.0.x
# /usr/sbin/apxs -cia mod_evasive20.c

Then add add this too httpd.conf
<IfModule mod_evasive20.c>
DOSHashTableSize 3097
DOSPageCount 6
DOSSiteCount 100
DOSPageInterval 2
DOSSiteInterval 2
DOSBlockingPeriod 600
</IfModule>

# Restart apache


Phase 2 : Make Changes

 

1) Secure root login : Disable root login and only allow wheel group members to use switch user option ( su – )

# vi /etc/ssh/sshd_config

( Enable protocol 2 and disable PermitRoot login as follows )

Protocol 2

PermitRootLogin No
# save the file and restart sshd service

Create a new user as a member of wheel group ( root user is a member of wheel group )
# useradd -G  wheel  serveradmin
# passwd serveradmin (Give a strong password )

Restrict the user to su
# vi /etc/pam.d/su
# Uncomment the following line to require a user to be in the “wheel” group.
auth            required        pam_wheel.so use_uid

Now only the users in wheel group can use ” su – ”

# Add the following line in ”  /root/.bash_profile ” , which will send an alert if anyone logged as root.

   
echo 'CRITICAL ALERT - Logged as Root on:' `date` `who` | mail -s "Alert: Logged as Root on Server `hostname` from `who | awk '{print $6}'`" your_full_email_address

 

2) Extended Binary Hardening Chmod dangerous files . It could be a good idea to restrict some commands to be executed by users that do not have root privileges and thus having your system more secure.

3) Inetd hardening Disable Telnet

#  mv /etc/xinetd.d/telnet /etc/xinetd.d/telnet.bkp
# /etc/rc.d/init.d/xinetd restart

4) Host.conf & Sysctl Hardening – Sysctl.conf is used to harden your kernel. The purpose of hardening this is to avoid DOS and Spoofing attacks to your system.

# cp -p /etc/host.conf  /etc/host.conf.bkp
# vi /etc/host.conf
multi on
nospoof on

Syctl Hardening : –

# cp -p /etc/sysctl.conf /etc/sysctl.conf.bkp
# >  /etc/sysctl.conf
# Vi  /etc/sysctl.conf
### paste the following and save the file
# 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 = 0
net.ipv4.conf.lo.log_martians = 0
net.ipv4.conf.eth0.log_martians = 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
# 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 TCP SYN Cookie Protection
net.ipv4.tcp_syncookies = 1
# Enable ignoring broadcasts request
net.ipv4.icmp_echo_ignore_broadcasts = 1
# Enable bad error message Protection
net.ipv4.icmp_ignore_bogus_error_responses = 1
# Log Spoofed Packets, Source Routed Packets, Redirect Packets
net.ipv4.conf.all.log_martians = 1
# Increases the size of the socket queue (effectively, q0).
net.ipv4.tcp_max_syn_backlog = 1024
# 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

Run the following commands to enable the above changes without  rebooting the server.
# /sbin/sysctl -p
# sysctl -w net.ipv4.route.flush=1

5) Hide Apache Information – You should hide apache banner information from being displayed so the attackers are not aware of what version of Apache version you are running and thus making it more difficult for them to exploit any system holes and thus making vulnerability scanners work harder and in some cases impossible without knowing banner information.
How To:
Modify /etc/httpd/conf/httpd.conf
Change the ServerSignature line to: ServerSignature Off
Change the ServerTokens line to: ServerTokens Prod

Restart Apache: /sbin/service httpd restart

6) Hide PHP Information – You should hide php banner information from being displayed so the attackers are not aware of what version of PHP version you are running and thus making it more difficult for them to exploit any system holes and thus making vulnerability scanners work harder and in some cases impossible without knowing banner information.
How To:
Modify php.ini
Change the expose_php line to: expose_php=Off
Notice: You may need to restart Apache.

7) Disable PHP dangerous function
How To:
Locate your php.ini and then edit:
1) whereis php.ini
2) vi /usr/local/lib/php.ini
Edit the line:
disable_functions = “” to
disable_functions =
“symlink,shell_exec,exec,proc_close,proc_open,popen,system,dl,passthru,escapeshellarg,
escapeshellcmd”

3) restart httpd

8 ) Remove Unwanted Services/daemons

#chkconfig gpm off
#chkconfig haldaemon off
#chkconfig lm_sensors off
#chkconfig mcstrans off
#chkconfig multipathd off
#chkconfig named off ( if you are not using named )
#chkconfig netfs off
#chkconfig netplugd off
#chkconfig nscd off
#chkconfig portmap off
#chkconfig rdisc off
#chkconfig syslauthd off
#chkconfig sendmail off ( if you are using sendmail as mail server  , then its needed )
#chkconfig smb off
#chkconfig snmpd off  ( if you are using cacti , then its needed )
#chkconfig snmptrapd off
#chkconfig winbind off

OPTIONAL

Securing History It would be a good idea to secure .bash_history to avoid deletion or redirection to /dev/null from the user so he cant clean or delete his last typed commands into the system.
How To:
chattr +a .bash_history (append)
chattr +i .bash_history

I know its not completing here , but its just a start !!!!!

I spent hours to make this doc , I am happy to include your suggestions and modification