ProperGander

Security for the masses

Securing Linux Servers

I had started my own server hardening guide but during my research I came across many useful and some comprehensive guides. So instead of re-inventing the wheel I decided to copy verbatim one of the best if not the best guide I came across. Credit for this goes to Matthew Lye and BodhiZazen. Although this guide deals with the Ubuntu distribution, it should not be too difficult to apply this guide to whatever Linux distro you use.

First things first if you just want something quick and fast here are the big three:

Reconfiguring shared memory

Load your favorite text editor, open the file "/etc/fstab" and add the following line of code:
tmpfs /dev/shm tmpfs defaults,ro 0 0

Disabling SSH root login

Load your favorite text editor, open the file "/etc/ssh/sshd_config" and add change the following line of code:
PermitRootLogin yes to PermitRootLogin no

Limiting access to the "su" program (this is done by default in Ubuntu)

*****MAKE SURE YOU ARE PART OF THE ADMIN GROUP****
Open the terminal by clicking "Applications" selecting "Accessories" and choosing "Terminal." From there enter the commands:
sudo chown root:admin /bin/su sudo
chmod 04750 /bin/su

System/Server Hardening Checklist

Here is the larger recommended list (although most are not necessary unless your looking at a server or lab environments).

Disk Partitions and Mounting

1. Separate /home, /tmp, /var/tmp from /root partitions (If only if the machine has frequent access from general user except administrator).

2. Change mount options in /etc/fstab to limit user access on appropriate filesystems.
  • Using noexec instead prevents execution of binaries on a file system
This is not good if you have programs to be executed Data partitions are good for this. Its used often for partitions serving Apache.
  • Using nosuid will prevent the setuid bit from having effect.
SUID stands for Set User ID. This means that if the SUID bit is set for any application then your user ID would be set as that of the owner of application/file rather than the current user, while running that application. That means in case I have an application whose owner is ' root ' and it has its SUID bit set, then when I run this application as a normal user, that application would still run as root. Since the SUID bit tells Linux that the the User ID root is set for this application and whenever this application executes it must execute as if root was executing it (since root owns this file). Disabling this for a drive prevents this operation.
  • The nodev option prevents use of device files on the filesystem.
This option would be recommended for CDs and NTFS file systems generally speaking. But it can have options to lock down a system preventing breaching by simply creating hda1 or sda1 devices that are writable by all.

Physical Security

Typically used in lab environments or where a server in not in a completely secured location.

1. Configure BIOS.
  • Disable booting from CDs/DVDs, floppies, and external devices.
  • Set BIOS password to protect the settings.
2. Set a password for the GRUB bootloader.
  • Generate a password hash using the command / /usr/sbin/grub-md5-crypt. Add the hash to the first line of /boot/grub/menu.lst as follows: password --md5 passwordhash
  • Remove rescue-mode boot section from /boot/grub/menu.lst

System Security

1. Keep Software Up to Date Upgrade through the Ubuntu Repository Network to apply upgrade automatically. Security updates should be applied as soon as possible. Create the file apt.cron, make it executable, place it in /etc/cron.daily or /etc/cron.weekly, and ensure that it reads as follows:

#!/bin/sh
/usr/bin/apt-get update

This can have a side effect of breaking some dependencies.

2. Detecting listening network ports & Closing open ports and services
Detecting listening network ports.
For a list of network ports that are open you can use the following commands:

# netstat -tulp or lsof -i -n | egrep 'COMMAND|LISTEN|UDP' or just a port scanner (nmap) 9

3. Closing open ports and services
To get a list of running services you can execute the following command:
sysv-rc-conf --list | grep on
To disable a running service you can execute the command: sysv-rc-conf service name off and then you should stop this service from running by executing: /etc/init.d/service stop.

4. Disable SUID and SGID Binaries
To find SUID and SGID files on the system, use the following command:

# find / \( -perm -4000 -o -perm -2000 \) –print

SUID or SGID bits safely disabled (using chmod -s filename) unless required for other program.

5. Configure and Use TCP Wrapper
Configure the TCP Wrapper library to protect network daemons that support its use by adding appropriate rules to /etc/hosts.allow and /etc/hosts.deny. For more info and examples I recommend This

NOTE: tcp wrappers only works for services that inetd starts. Sendmail, apache, and named do not use inetd, and so they are not protected via tcp wrappers.

6. Configure and Use AppArmor
AppArmor is installed and loaded by default in Hardy. Some packages will install their own enforcing profiles. Active profiles for LAMP Server:
  • usr.sbin.mysqld
  • usr.sbin.apache2
All activity will be logged by audited and saved to /var/log/audit/audit.log (/var/log/messages on ubuntu)
Some excellent advice on this is available here.

7. Rdate or NTP (To keep your server date up to date)
Create the file /etc/cron.d/rdate with the following line:
15 * * * * root /usr/sbin/rdate -s content

for NTP
Create the file /etc/cron.d/ntp with the following line:
15 * * * * root /usr/sbin/ntpdate server

8. Configure or Disable SSH
- Disable it when not required.
- If SSH is required, ensure the SSH configuration includes the following lines:
  • PermitRootLogin no
  • Protocol 2
- If possible, limit SSH access to a subset of users. Create a group called sshusers and only add the users that need remote access. Then, add the following line to /etc/ssh/sshd_config:

AllowGroups sshusers

Edit /etc/group find sshusers and add allowed users.

If you run a ssh server, consider running a service such as denyhosts. Denyhosts is in the Ubuntu repositories and here are some links to get started:
howtoforge denyhosts
ubuntu geek

9. Disable IPv6
Disable it when not required.
Edit the following line from /etc/modprobe.d/aliases:
  • Find the line: alias net-pf-10 ipv6
  • Edit this to: alias net-pf-10 off ipv6
  • Save the file and reboot
10. Disable Compile
Add compiler group: /usr/sbin/groupadd compiler
Move to correct directory: cd /usr/bin
Make most common compilers part of the compiler group
  • chgrp compiler *cc*
  • chgrp compiler *++*
  • chgrp compiler ld
  • chgrp compiler as
11. Set access on mysqlaccess
chgrp root mysqlaccess
Set permissions
  • chmod 750 *cc*
  • chmod 750 *++*
  • chmod 750 ld
  • chmod 750 as
  • chmod 755 mysqlaccess
To add users to the group, modify /etc/group and change compiler [Mad] :123: to compiler [Mad] :123:username1,username2 ('123' will be different on your installation)

12. Root Notification
Edit .bashrc under /root to get notified by email when someone logs in as root and add the following:
echo 'ALERT - Root Shell Access (Server Name) on:' `date` `who` | mail -s "Alert: Root Access from `who | cut -d"(" -f2 | cut -d")" -f1`"

13. Securing History
chattr +a .bash_history (append)
chattr +I .bash_history

14. Using Welcome Message
Edit /etc/motd and put the following banner to be displayed:

WARNING !!!
This computer system including all related equipment, network devices (specifically including Internet access), are provided only for authorized use.
Unauthorized use may subject you to criminal prosecution. By accessing this system, you have agreed to the term and condition of use and your actions will be monitored and recorded.

15. Chmod dangerous files
chmod 700 /bin/ping
chmod 700 /usr/bin/who
chmod 700 /usr/bin/w
chmod 700 /usr/bin/locate
chmod 700 /usr/bin/whereis
chmod 700 /sbin/ifconfig
chmod 700 /bin/nano
chmod 700 /usr/bin/vi
chmod 700 /usr/bin/which
chmod 700 /usr/bin/gcc
chmod 700 /usr/bin/make
chmod 700 /usr/bin/apt-get
chmod 700 /usr/bin/aptitude

16. Specify TTY Devices Root is allowed
vi /etc/securetty
Leave only two connections:
tty1
tty2

17. Choose a secure password
This is generally a good tip, this fix however applies to people using pam to authenticate to LDAP or AD.
vi /etc/pam.d/common-password
change the detail from this:
password requisite pam_unix.so nullok obscure md5
to
password requisite pam_unix.so nullok obscure md5 min=8
Change min=8 with your company password policy length.

18. Checking for Rootkits
Install it from Ubuntu Repository:
# apt-get install chkrootkit
You can run it with the following command: ./chkrootkit
Now we are going to add it to contrab to schedule daily automatic scans in the system:
vi /etc/cron.daily/chkrootkit.sh and type
#!/bin/bash
# Enter the directory where the rootkit is installed
cd /root/chkrootkit/
# Enter your email address where you want to receive the report
./chkrootkit | mail -s "Daily chkrootkit from Server Name" This e-mail address is being protected from spambots. You need JavaScript enabled to view it

Now change the file permissions so we can run it:
chmod 755 /etc/cron.daily/chkrootkit.sh
To give it a try you can run the chkrootkit.sh file manually from /etc/cron.daily directory and you should receive a report to the email account you provided.

19. Hardening your Kernel
UPDATE: This should not be done as using AppArmor makes this process redundant.

Instead of doing this manually use a pre hardened kernel like selinux. Not only is this simpler but you are going to be using a well tested and audited solution that will be much more effective than some simple tweaks.

20. Disable unnecessary PHP variables
Edit /etc/php5/apache2/php.ini and /etc/php5/cli/php.ini

Turn off these variables:

allow_call_time_pass_reference = Off
magic_quotes_gpc = Off
register_long_arrays = Off
register_argc_argv = Off
allow_url_fopen = Off
expose_php = Off
disable_functions = symlink,shell_exec,proc_close,proc_open,dl,passthru,
escapeshellarg,escapeshellcmd,openlog, apache_child_terminate,
apache_get_modules,apache_get_version,
apache_getenv,apache_note,apache_setenv,virtual, phpinfo

21. Apache Hardening
Edit /etc/apache2/apache.conf

Turn off these variables:
TraceEnable off
(Disable apache root access)
[directory\]
Order deny,allow
Deny from all
[/directory]

Enable Module ( /etc/apache2/mods-enable/ ):
alias, auth_basic, authn_file, authz_default, authz_groupfile, authz_host, authz_user, autoindex, dir, env, mime, mod-security2, negotiation, php5, rewrite, setenvif, ssl, unique_id

Edit /etc/php.ini
Find disable functions and edit as below:
disable_functions = exec, passthru, shell_exec, system, proc_open, popen, curl_exec, curl_multi_exec, parse_ini_file, show_source

Hardened Kernel Variables ( /etc/sysctl.conf )

# 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 IP source routing
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.eth0.rp_filter = 1

# Disable ICMP Redirect Acceptance
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.lo.log_martians = 1
net.ipv4.conf.eth0.log_martians = 1

# Disables IP source routing
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.eth0.rp_filter = 1

# Disable ICMP Redirect Acceptance
net.ipv4.conf.lo.accept_redirects = 0
net.ipv4.conf.eth0.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0

# Modify system limits for Ensim WEBppliance
fs.file-max = 65000

# 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 ( Need to turn on for traffic to internet)
#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

# Set maximum amount of memory allocated to shm to 256MB
kernel.shmmax = 268435456

# Increase the maximum total TCP buffer-space allocatable

net.ipv4.tcp_mem = 57344 57344 65536

# Increase the maximum TCP write-buffer-space allocatable
net.ipv4.tcp_wmem = 32768 65536 524288

# Increase the maximum TCP read-buffer space allocatable
net.ipv4.tcp_rmem = 98304 196608 1572864

# Increase the maximum and default receive socket buffer size

net.core.rmem_max = 524280
net.core.rmem_default = 524280

# Increase the maximum and default send socket buffer size
net.core.wmem_max = 524280
net.core.wmem_default = 524280
# 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 = 57344