Securing your Linux server is important to protect your data, intellectual property, and time, from the hands of crackers (hackers). The system administrator is responsible for security Linux box. In this first part of a Linux server security series, I will provide 20 hardening tips for default installation of Linux system.
#1: Encrypt Data Communication
All data transmitted over a network is open to monitoring. Encrypt transmitted data whenever possible with password or using keys / certificates.
- Use scp, ssh, rsync, or sftp for file transfer. You can also mount remote server file system or your own home directory using special sshfs and fuse tools.
- GnuPG allows to encrypt and sign your data and communication, features a versatile key managment system as well as access modules for all kind of public key directories.
- Fugu is a graphical frontend to the commandline Secure File Transfer application (SFTP). SFTP is similar to FTP, but unlike FTP, the entire session is encrypted, meaning no passwords are sent in cleartext form, and is thus much less vulnerable to third-party interception. Another option is FileZilla – a cross-platform client that supports FTP, FTP over SSL/TLS (FTPS), and SSH File Transfer Protocol (SFTP).
- OpenVPN is a cost-effective, lightweight SSL VPN.
- Lighttpd SSL (Secure Server Layer) Https Configuration And Installation
- Apache SSL (Secure Server Layer) Https (mod_ssl) Configuration And Installation
#1.1: Avoid Using FTP, Telnet, And Rlogin / Rsh
Under most network configurations, user names, passwords, FTP / telnet / rsh commands and transferred files can be captured by anyone on the same network using a packet sniffer. The common solution to this problem is to use either OpenSSH , SFTP, or FTPS (FTP over SSL), which adds SSL or TLS encryption to FTP. Type the following command to delete NIS, rsh and other outdated service:
# yum erase inetd xinetd ypserv tftp-server telnet-server rsh-serve
#2: Minimize Software to Minimize Vulnerability
Do you really need all sort of web services installed? Avoid installing unnecessary software to avoid vulnerabilities in software. Use the RPM package manager such as yum or apt-get and/or dpkg to review all installed set of software packages on a system. Delete all unwanted packages.
# yum list installed
# yum list packageName
# yum remove packageName
OR
# dpkg --list
# dpkg --info packageName
# apt-get remove packageName
#3: One Network Service Per System or VM Instance
Run different network services on separate servers or VM instance. This limits the number of other services that can be compromised. For example, if an attacker able to successfully exploit a software such as Apache flow, he / she will get an access to entire server including other services such as MySQL, e-mail server and so on. See how to install Virtualization software:
- Install and Setup XEN Virtualization Software on CentOS Linux 5
- How To Setup OpenVZ under RHEL / CentOS Linux
#4: Keep Linux Kernel and Software Up to Date
Applying security patches is an important part of maintaining Linux server. Linux provides all necessary tools to keep your system updated, and also allows for easy upgrades between versions. All security update should be reviewed and applied as soon as possible. Again, use the RPM package manager such as yum and/or apt-get and/or dpkg to apply all security updates.
# yum update
OR
# apt-get update && apt-get upgrade
You can configure Red hat / CentOS / Fedora Linux to send yum package update notification via email. Another option is to apply all security updates via a cron job. Under Debian / Ubuntu Linux you can use apticron to send security notifications.
#5: Use Linux Security Extensions
Linux comes with various security patches which can be used to guard against misconfigured or compromised programs. If possible use SELinux and other Linux security extensions to enforce limitations on network and other programs. For example, SELinux provides a variety of security policies for Linux kernel.
#5.1: SELinux
I strongly recommend using SELinux which provides a flexible Mandatory Access Control (MAC). Under standard Linux Discretionary Access Control (DAC), an application or process running as a user (UID or SUID) has the user’s permissions to objects such as files, sockets, and other processes. Running a MAC kernel protects the system from malicious or flawed applications that can damage or destroy the system. See the official Redhat documentation which explains SELinux configuration.
#6: User Accounts and Strong Password Policy
Use the useradd / usermod commands to create and maintain user accounts. Make sure you have a good and strong password policy. For example, a good password includes at least 8 characters long and mixture of alphabets, number, special character, upper & lower alphabets etc. Most important pick a password you can remember. Use tools such as “John the ripper” to find out weak users passwords on your server. Configure pam_cracklib.so to enforce the password policy.
#6.1: Password Aging
The chage command changes the number of days between password changes and the date of the last password change. This information is used by the system to determine when a user must change his/her password. The /etc/login.defs file defines the site-specific configuration for the shadow password suite including password aging configuration. To disable password aging, enter:
chage -M 99999 userName
To get password expiration information, enter:
chage -l userName
Finally, you can also edit the /etc/shadow file in the following fields:
{userName}:{password}:{lastpasswdchanged}:{Minimum_days}:{Maximum_days}:{Warn}:{Inactive}:{Expire}:
Where,
- Minimum_days: The minimum number of days required between password changes i.e. the number of days left before the user is allowed to change his/her password.
- Maximum_days: The maximum number of days the password is valid (after that user is forced to change his/her password).
- Warn : The number of days before password is to expire that user is warned that his/her password must be changed.
- Expire : Days since Jan 1, 1970 that account is disabled i.e. an absolute date specifying when the login may no longer be used.
I recommend chage command instead of editing the /etc/shadow by hand:
# chage -M 60 -m 7 -W 7 userName
Recommend readings:
- Linux: Force Users To Change Their Passwords Upon First Login
- Linux turn On / Off password expiration / aging
- Lock the user password
- Search for all account without password and lock them
- Use Linux groups to enhance security
#6.2: Restricting Use of Previous Passwords
You can prevent all users from using or reuse same old passwords under Linux. The pam_unix module parameter remember can be used to configure the number of previous passwords that cannot be reused.
#6.3: Locking User Accounts After Login Failures
Under Linux you can use the faillog command to display faillog records or to set login failure limits. faillog formats the contents of the failure log from /var/log/faillog database / log file. It also can be used for maintains failure counters and limits.To see failed login attempts, enter:
faillog
To unlock an account after login failures, run:
faillog -r -u userName
Note you can use passwd command to lock and unlock accounts:
# lock account
passwd -l userName
# unlocak account
passwd -u userName
#6.4: How Do I Verify No Accounts Have Empty Passwords?
Type the following command
# awk -F: '($2 == "") {print}' /etc/shadow
Lock all empty password accounts:
# passwd -l accountName
#6.5: Make Sure No Non-Root Accounts Have UID Set To 0
Only root account have UID 0 with full permissions to access the system. Type the following command to display all accounts with UID set to 0:
# awk -F: '($3 == "0") {print}' /etc/passwd
You should only see one line as follows:
root:x:0:0:root:/root:/bin/bash
If you see other lines, delete them or make sure other accounts are authorized by you to use UID 0.
#7: Disable root Login
Never ever login as root user. You should use sudo to execute root level commands as and when required. sudo does greatly enhances the security of the system without sharing root password with other users and admins. sudo provides simple auditing and tracking features too.
#8: Physical Server Security
You must protect Linux servers physical console access. Configure the BIOS and disable the booting from external devices such as DVDs / CDs / USB pen. Set BIOS and grub boot loader password to protect these settings. All production boxes must be locked in IDCs (Internet Data Center) and all persons must pass some sort of security checks before accessing your server. See also:
- 9 Tips To Protect Linux Servers Physical Console Access.
#9: Disable Unwanted Services
Disable all unnecessary services and daemons (services that runs in the background). You need to remove all unwanted services from the system start-up. Type the following command to list all services which are started at boot time in run level # 3:
# chkconfig --list | grep '3:on'
To disable service, enter:
# service serviceName stop
# chkconfig serviceName off
#9.1: Find Listening Network Ports
Use the following command to list all open ports and associated programs:
netstat -tulpn
OR
nmap -sT -O localhost
nmap -sT -O server.example.com
Use iptables to close open ports or stop all unwanted network services using above service and chkconfig commands.
#9.2: See Also
- update-rc.d like command on Redhat Enterprise / CentOS Linux.
- Ubuntu / Debian Linux: Services Configuration Tool to Start / Stop System Services.
- Get Detailed Information About Particular IP address Connections Using netstat Command.
#10: Delete X Windows
X Windows on server is not required. There is no reason to run X Windows on your dedicated mail and Apache web server. You can disable and remove X Windows to improve server security and performance. Edit /etc/inittab and set run level to 3. Finally, remove X Windows system, enter:
# yum groupremove "X Window System"
#11: Configure Iptables and TCPWrappers
Iptables is a user space application program that allows you to configure the firewall (Netfilter) provided by the Linux kernel. Use firewall to filter out traffic and allow only necessary traffic. Also use the TCPWrappers a host-based networking ACL system to filter network access to Internet. You can prevent many denial of service attacks with the help of Iptables:
- Lighttpd Traffic Shaping: Throttle Connections Per Single IP (Rate Limit).
- How to: Linux Iptables block common attack.
- psad: Linux Detect And Block Port Scan Attacks In Real Time.
#12: Linux Kernel /etc/sysctl.conf Hardening
/etc/sysctl.conf file is used to configure kernel parameters at runtime. Linux reads and applies settings from /etc/sysctl.conf at boot time. Sample /etc/sysctl.conf:
# Turn on execshield kernel.exec-shield=1 kernel.randomize_va_space=1 # Enable IP spoofing protection net.ipv4.conf.all.rp_filter=1 # Disable IP source routing net.ipv4.conf.all.accept_source_route=0 # Ignoring broadcasts request net.ipv4.icmp_echo_ignore_broadcasts=1 net.ipv4.icmp_ignore_bogus_error_messages=1 # Make sure spoofed packets get logged net.ipv4.conf.all.log_martians = 1
#13: Separate Disk Partitions
Separation of the operating system files from user files may result into a better and secure system. Make sure the following filesystems are mounted on separate partitions:
- /usr
- /home
- /var and /var/tmp
- /tmp
Create septate partitions for Apache and FTP server roots. Edit /etc/fstab file and make sure you add the following configuration options:
- noexec – Do not set execution of any binaries on this partition (prevents execution of binaries but allows scripts).
- nodev – Do not allow character or special devices on this partition (prevents use of device files such as zero, sda etc).
- nosuid – Do not set SUID/SGID access on this partition (prevent the setuid bit).
Sample /etc/fstab entry to to limit user access on /dev/sda5 (ftp server root directory):
/dev/sda5 /ftpdata ext3 defaults,nosuid,nodev,noexec 1 2
#13.1: Disk Quotas
Make sure disk quota is enabled for all users. To implement disk quotas, use the following steps:
- Enable quotas per file system by modifying the /etc/fstab file.
- Remount the file system(s).
- Create the quota database files and generate the disk usage table.
- Assign quota policies.
- See implementing disk quotas tutorial for further details.
#14: Turn Off IPv6
Internet Protocol version 6 (IPv6) provides a new Internet layer of the TCP/IP protocol suite that replaces Internet Protocol version 4 (IPv4) and provides many benefits. Currently there are no good tools out which are able to check a system over network for IPv6 security issues. Most Linux distro began enabling IPv6 protocol by default. Crackers can send bad traffic via IPv6 as most admins are not monitoring it. Unless network configuration requires it, disable IPv6 or configure Linux IPv6 firewall:
- RedHat / Centos Disable IPv6 Networking.
- Debian / Ubuntu And Other Linux Distros Disable IPv6 Networking.
- Linux IPv6 Howto – Chapter 19. Security.
- Linux IPv6 Firewall configuration and scripts are available here.
#15: Disable Unwanted SUID and SGID Binaries
All SUID/SGID bits enabled file can be misused when the SUID/SGID executable has a security problem or bug. All local or remote user can use such file. It is a good idea to find all such files. Use the find command as follows:
#See all set user id files:
find / -perm +4000
# See all group id files
find / -perm +2000
# Or combine both in a single command
find / ( -perm -4000 -o -perm -2000 ) -print
find / -path -prune -o -type f -perm +6000 -ls
You need to investigate each reported file. See reported file man page for further details.
#15.1: World-Writable Files
Anyone can modify world-writable file resulting into a security issue. Use the following command to find all world writable and sticky bits set files:
find /dir -xdev -type d ( -perm -0002 -a ! -perm -1000 ) -print
You need to investigate each reported file and either set correct user and group permission or remove it.
#15.2: Noowner Files
Files not owned by any user or group can pose a security problem. Just find them with the following command which do not belong to a valid user and a valid group
find /dir -xdev ( -nouser -o -nogroup ) -print
You need to investigate each reported file and either assign it to an appropriate user and group or remove it.
#16: Use A Centralized Authentication Service
Without a centralized authentication system, user auth data becomes inconsistent, which may lead into out-of-date credentials and forgotten accounts which should have been deleted in first place. A centralized authentication service allows you maintaining central control over Linux / UNIX account and authentication data. You can keep auth data synchronized between servers. Do not use the NIS service for centralized authentication. Use OpenLDAP for clients and servers.
#16.1: Kerberos
Kerberos performs authentication as a trusted third party authentication service by using cryptographic shared secret under the assumption that packets traveling along the insecure network can be read, modified, and inserted. Kerberos builds on symmetric-key cryptography and requires a key distribution center. You can make remote login, remote copy, secure inter-system file copying and other high-risk tasks safer and more controllable using Kerberos. So, when users authenticate to network services using Kerberos, unauthorized users attempting to gather passwords by monitoring network traffic are effectively thwarted. See how to setup and use Kerberos.
#17: Logging and Auditing
You need to configure logging and auditing to collect all hacking and cracking attempts. By default syslog stores data in /var/log/ directory. This is also useful to find out software misconfiguration which may open your system to various attacks. See the following logging related articles:
- Linux log file locations.
- How to send logs to a remote loghost.
- How do I rotate log files?.
- man pages syslogd, syslog.conf and logrotate.
#17.1: Monitor Suspicious Log Messages With Logwatch / Logcheck
Read your logs using logwatch or logcheck. These tools make your log reading life easier. You get detailed reporting on unusual items in syslog via email. A sample syslog report:
################### Logwatch 7.3 (03/24/06) #################### Processing Initiated: Fri Oct 30 04:02:03 2009 Date Range Processed: yesterday ( 2009-Oct-29 ) Period is day. Detail Level of Output: 0 Type of Output: unformatted Logfiles for Host: www-52.nixcraft.net.in ################################################################## --------------------- Named Begin ------------------------ **Unmatched Entries** general: info: zone XXXXXX.com/IN: Transfer started.: 3 Time(s) general: info: zone XXXXXX.com/IN: refresh: retry limit for master ttttttttttttttttttt#53 exceeded (source ::#0): 3 Time(s) general: info: zone XXXXXX.com/IN: Transfer started.: 4 Time(s) general: info: zone XXXXXX.com/IN: refresh: retry limit for master ttttttttttttttttttt#53 exceeded (source ::#0): 4 Time(s) ---------------------- Named End ------------------------- --------------------- iptables firewall Begin ------------------------ Logged 87 packets on interface eth0 From 58.y.xxx.ww - 1 packet to tcp(8080) From 59.www.zzz.yyy - 1 packet to tcp(22) From 60.32.nnn.yyy - 2 packets to tcp(45633) From 222.xxx.ttt.zz - 5 packets to tcp(8000,8080,8800) ---------------------- iptables firewall End ------------------------- --------------------- SSHD Begin ------------------------ Users logging in through sshd: root: 123.xxx.ttt.zzz: 6 times ---------------------- SSHD End ------------------------- --------------------- Disk Space Begin ------------------------ Filesystem Size Used Avail Use% Mounted on /dev/sda3 450G 185G 241G 44% / /dev/sda1 99M 35M 60M 37% /boot ---------------------- Disk Space End ------------------------- ###################### Logwatch End #########################
(Note output is truncated)
#17.2: System Accounting with auditd
The auditd is provided for system auditing. It is responsible for writing audit records to the disk. During startup, the rules in /etc/audit.rules are read by this daemon. You can open /etc/audit.rules file and make changes such as setup audit file log location and other option. With auditd you can answers the following questions:
- System startup and shutdown events (reboot / halt).
- Date and time of the event.
- User respoisble for the event (such as trying to access /path/to/topsecret.dat file).
- Type of event (edit, access, delete, write, update file & commands).
- Success or failure of the event.
- Records events that Modify date and time.
- Find out who made changes to modify the system’s network settings.
- Record events that modify user/group information.
- See who made changes to a file etc.
See our quick tutorial which explains enabling and using the auditd service.
#18: Secure OpenSSH Server
The SSH protocol is recommended for remote login and remote file transfer. However, ssh is open to many attacks. See how to secure OpenSSH server:
#19: Install And Use Intrusion Detection System
A network intrusion detection system (NIDS) is an intrusion detection system that tries to detect malicious activity such as denial of service attacks, port scans or even attempts to crack into computers by monitoring network traffic.
It is a good practice to deploy any integrity checking software before system goes online in a production environment. If possible install AIDE software before the system is connected to any network. AIDE is a host-based intrusion detection system (HIDS) it can monitor and analyses the internals of a computing system.
Snort is a software for intrusion detection which is capable of performing packet logging and real-time traffic analysis on IP networks.
#20: Protecting Files, Directories and Email
Linux offers excellent protections against unauthorized data access. File permissions and MAC prevent unauthorized access from accessing data. However, permissions set by the Linux are irrelevant if an attacker has physical access to a computer and can simply move the computer’s hard drive to another system to copy and analyze the sensitive data. You can easily protect files, and partitons under Linux using the following tools:
- To encrypt and decrypt files with a password, use gpg command.
- Linux or UNIX password protect files with openssl and other tools.
- See how to encrypting directories with ecryptfs.
- TrueCrypt is free open-source disk encryption software for Windows 7/Vista/XP, Mac OS X and Linux.
- Howto: Disk and partition encryption in Linux for mobile devices.
- How to setup encrypted Swap on Linux.
#20.1: Securing Email Servers
You can use SSL certificates and gpg keys to secure email communication on both server and client computers:
- Linux Securing Dovecot IMAPS / POP3S Server with SSL Configuration.
- Linux Postfix SMTP (Mail Server) SSL Certificate Installations and Configuration.
- Courier IMAP SSL Server Certificate Installtion and Configuration.
- Configure Sendmail SSL encryption for sending and receiving email.
- Enigmail: Encrypted mail with Mozilla thunderbird.
NU/Linux CentOS server hardening that meets security guidelines.
The document will cover Physical Protection, User Rights, Network Security, Kernel Security and Tamper Resistance
File System Partitioning
File System LVM (So partitions can be shrunk or grown if needs be)
Partitions: (must be journaled FS)
/boot primary
/ primary
Extended
/tmp
/var
/var/log
/usr/local
/opt
/home
swap
CentOS ISO
-Install from clean formatted drive (check md5 sum)
-Use CentOS-ver-arch-minimal (roughly 260MB)
-Custom installations (installation must be done with minimal packages as possible)
Package installs
-The list of apps should be determined by the use of the machine.
-As a base no more than SSH installed, this to allow remote access.
-If we don’t need i386/i686 packages for compatibility purposes, we may want to remove them as well, by using yum remove *.i?86, and then keep them gone by adding exclude = *.i?86 to your /etc/yum.conf
Physical Protection
-Set up BIOS password.
-Place servers in a controlled area.
-Prevent servers from being booted through other medium.
-Servers are to be placed in racks with locking mechanisms.
-Conceal cabling and power outlets.
-Activate password for grub.
-Do not install any auto mount package for mount of external devices such as USB, PCMCI, etc.
-Once installation of server is complete make sure that you’ve logged out from tty (virtual terminal).
-Allow only 2 tty and disable others (there are 6 by default), so make sure that we have only 2 runlevel.
CentOS Hardening
After installing and configuring, further steps have to be taken to ensure operating system hardening.
The minimum procedure that must be followed:
•Accounts (check if passwd files is shadowed)
•Check service and ports (services are background programs that serve as a utility function without being called by a user. This utility may range from maintenance utility or to provide an interface upon request. Most of these services are not useful depending on the UNIX/Linux usage purposes.
•Securing root applications (ensure /sbin and /etc folders are owned by root. By default, normal users can reboot the system by issuing ‘reboot’ command or by pressing Ctrl-Alt-Del combo keys.
•Detecting SUID/SGID apps (a regular user will be able to run a program as root if it is set to SUID root. We should minimize the use of these SUID/GUID apps and disable the programs which are not needed.
•Setup a specific server for repository that can be the only one with access to global internet.
•Install and check patches (verify integrity of patch by md5sum)
•Make sure that the server has no access to global internet.
•The list of apps should be determined by the use of the machine.
•The only service running by default should be SSH
Alert to show when user log on
-SSH banner alert message
——————
W A R N I N G
——————
*************************************************************************************************
NOTICE TO USERS WARNING! The use of this system is restricted to authorized users, unauthorized access is forbidden and will be prosecuted by law. All information and communications on this system are subject to review, monitoring and recording at any time, without notice or permission. Users should have no expectation of privacy.
*************************************************************************************************
Lock down GRUB 2
•Grub 2 has the ability to set password protection on individual menu entries and/or for specific users.
•The username and password will also be required to gain access to the Grub 2 command line and menu editing modes.
•The username and/or password do not have to be the same as the system logon name/password.
•This is basic password security. The name/password are unencrypted; anyone having physical access to the machine and more than an elementary knowledge of how Linux works will be able to access the configuration files and bypass this feature.
•Grub 2 password protection is still evolving. Currently (Grub 1.97beta4) password protection must be assigned to each menu entry. There is a chance the password feature will be revised so that all entries are protected by default. If and when this feature is incorporated in Grub 2, password protection can be eliminated for a specific menu entry by adding “(–unlock)” on the menu entry line.
Setting up password protection:
There are three steps to enabling Grub 2 password protection. The user must set up the authorized users, designate the password(s), and identify the password-protected menu entries in the/etc/grub.d/ scripts.
1. Superuser & password designation (required):
A superuser must be designated. This superuser can access any menu entry, edit the menu entries in the Grub 2 menu by pressing “e”, or invoke the Grub 2 command line mode. Add the following the bottom of /etc/grub.d/00_header
cat << EOF
set superusers=”user1?
password user1 password1
EOF
2. Other users (optional)
Other users can be identified and given a password. A designated user can access unprotected and their own menuentries. Add the following the bottom of /etc/grub.d/00_header
Example:
cat << EOF
set superusers=”sysadmin”
password sysadmin 1234
password user 5678
EOF
3. Designating menu entries for password protection
Once the superuser/other users and their password(s) are established, the entries to be protected must be identified. Currently Grub 2 adds no password protection to any entries upon establishment of a superuser and password in /etc/grub.d/00_header. Each entry must be identified and modified. Scripts can be used to tailor entries for specific menu entries.
Turn on SELinux protection (basic)
-Edit /etc/selinux/config file using “vi” or other text tool
-Update the configuration as follows:
SELINUX=enforcing
SELINUXTYPE=targeted
Remove unnecessary modules
-A simple loop can be used to disable them via a blacklist file in /etc/modprobe.d:
-For example to remove wireless modules perform:
for i in $(find /lib/modules/`uname -r`/kernel/drivers/net/wireless -name “*.ko” -type f) ; do echo blacklist $i >> /etc/modprobe.d/blacklist-wireless ; done
Linux Kernel /etc/sysctl.conf Security Hardening
-Use “vi” to edit /etc/sysctl.conf and setup basic configuration as follows:
oLimit network-transmitted configuration for IPv4
oLimit network-transmitted configuration for IPv6
oTurn on exec shield protection
oPrevent against the common ‘syn flood attack’
oTurn on source IP address verification
oPrevents a cracker from using a spoofing attack against the IP address of the server.
oLogs several types of suspicious packets, such as spoofed packets, source-routed packets, and redirects.
-For example:
net.ipv4.ip_forward = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
net.ipv4.tcp_max_syn_backlog = 1280
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.all.secure_redirects = 0
net.ipv4.conf.all.log_martians = 1
net.ipv4.conf.default.accept_source_route = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.default.secure_redirects = 0
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.icmp_ignore_bogus_error_responses = 1
net.ipv4.tcp_syncookies = 1
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
net.ipv4.tcp_timestamps = 0
Harden password policies
-vi /etc/login.defs then edit PASS_MIN_LEN 5 ==> 8
-Strong passwords should be used. A strong password should have mixed case, special characters, numbers, and be at least 8 characters.
-Password complexity requirements should be in place to enforce strong password usage.
-Passwords should be changed reasonably regularly.
•echo “Passwords expire every 90 days”
•perl -npe ‘s/PASS_MAX_DAYS\s+99999/PASS_MAX_DAYS 90/’ -i /etc/login.defs
-The command below will update your system to use sha512 instead of md5 for password protection.
•authconfig –passalgo=sha512 –update
Time out after 15 minutes of idle time
-echo “Idle users will be removed after 15 minutes”
-echo “readonly TMOUT=900” >> /etc/profile.d/os-security.sh
-echo “readonly HISTFILE” >> /etc/profile.d/os-security.sh
-chmod +x /etc/profile.d/os-security.sh
Remove unwanted base applications
-rpm -ev iptables-ipv6 system-config-securitylevel-tui system-config-network-tui firstboot-tui wireless-tools
-rpm -ev xorg-x11-filesystem cups redhat-lsb rhpl gpm vim-enhanced pcsc-lite ifd-egate ccid coolkey
Ensure that root cannot log on through ssh
-sed “# PermitRootLogin yes/PermitRootLogin no/g” /etc/sshd.conf > /tmp/swap; cp /tmp/swap /etc/sshd.conf
Ensure that root can only log on locally
-Once a server is up and running, root shouldn’t be logging in directly except in emergency situations. These usually require hands at the console, so that’s the only place root should be allowed to log in. To do this, we need to modify /etc/securetty. Additionally, no one other than root should be allowed in root’s home directory. The default settings are close to this, but not quite paranoid enough.
echo “tty1” > /etc/securetty
chmod 700 /root
-Since we have effectively removed root’s ability to log in from anywhere but the local console, it becomes necessary to use su and sudo. This offers a few secondary benefits in a multi-admin environment.
•sudo allows for granular control over privileged actions. This way a website administrator can start, stop and otherwise manage the web server without being able to affect other services.
•You get a much clearer picture of who did what in your logs, since who became root at what time is no longer a mystery.
Blocking “su” to root user
The su (Substitute User) command allows a user to become other existing users on the system. To prevent users from su to root or restrict su command to certain users then add the following two lines to the top of su configuration in the /etc/pam.d directory.
Edit the su file (vi /etc/pam.d/su) and add the following two lines to the top of the file:
-auth sufficient /lib/security/pam_rootok.so debug
-auth required /lib/security/Pam_wheel.so group=wheel
This example provides that only members of the ‘wheel’ group can su to root, which also includes logging.
Securing root apps
Ensure /sbin and /etc folders are owned by root. By default, normal users can reboot the system by issuing ‘reboot’ command or by pressing Ctrl-Alt-Del combo keys.
To disable the reboot command to users, ensure /sbin/halt is owned by root:
# chmod 700 /sbin/halt
To disable Ctrl-Alt-Del, edit /etc/inittab :
# vi /etc/inittab
Add a comment to the line stating, ca::ctrlaltdel:/sbin/shutdown -t3 -r now, so it reads
# ca::ctrlaltdel:/sbin/shutdown -t3 -r now
After making changes issue the command to take effect :
# /sbin/init q
By commenting out the line, restarting using Ctrl-Alt-Del is useless even to root. To shutdown, login as root and use the proper shutdown command :
# /sbin/shutdown –r now
Replace ‘r’ with ‘h’ for powering off the system.
Securing /etc/services file
Securing the “/etc/services” file prevents unauthorized deletion or addition of services. This involves in adding an immutable bit to the file. To secure the “/etc/services” file, use the command:
# chattr +i /etc/services
Hardening the IPTables
IPTables provide customization of rules depending on the user needs. Here are some
recommended IPTables configurations. First general rule is to block everything, and from there rules are added accordingly. An allowed rule, ACCEPT, will bypass a blocking rule, e.g DROP, REJECT.
IPTables consists of chains that control the packet flow. These chains are INPUT, OUTPUT and FORWARD.
Here are some basic configurations:
Rules should be cleared from the beginning.
# iptables -F; iptables -t nat -F; iptables -t mangle –F
To deny everything:
# iptables –A INPUT –j DROP
# iptables –A OUTPUT –j DROP
# iptables –A FORWARD –j DROP
These sample rules make a secure connection by enabling inspection against flowing packets. Only packets with established sessions are allowed through. ‘eth0’ is the interface number of a network card, changes should be applied accordingly:
# iptables -A INPUT -m state –state ESTABLISHED,RELATED -j ACCEPT
# iptables -A INPUT -m state –state NEW -i ! eth0 -j ACCEPT
# iptables -P INPUT DROP
# iptables –A FORWARD –I eth0 –o eth0 –j REJECT
TCP Wrappers
TCP wrapper is used to provide additional security against intrusion by controlling connections to defined services. TCP wrappers are controlled from two files.
– /etc/hosts.allow
-/etc/hosts.deny
The best policy is to deny all hosts by putting “ALL: ALL@ALL, PARANOID” in the “/etc/hosts.deny” file and then explicitly list trusted hosts who are allowed to connect to the machine in the “/etc/hosts.allow” file.
However, advance filtering can be achieved using a built-in utility IPTables.
Hiding the system information
echo ” ” >/etc/issue
echo ” ” >/etc/issue.net
chattr +i /etc/issue
chattr +i /etc/issue.net
Hardening network
-Remove ipv6
cp /etc/sysconfig/network /root/aspf_files/network.aspf
cat > /etc/sysconfig/network <<DELIM
NETWORKING=yes
NETWORKING_IPV6=no
HOSTNAME=<whatever.fine.com>
GATEWAY=<DGW>
DELIM
-Enabled bonding on the network cards, will need to discuss the best algorithm
Enable NTP and sync
-Sort NTP — Should be the router once it works for NTP
cp /etc/ntp.conf /root/aspf_files/ntp.conf.aspf
sed “/[0-1].centos.pool.ntp.org/d” /etc/ntp.conf > /tmp/swap;
sed “s/2.centos.pool.ntp.org/hostname/g” /tmp/swap > /etc/ntp.conf;
ntpdate -d hostname
-Sync everything to the NTP clock before installing any applications — Add to root cron for consistent time stamps
yum install ntp
hwclock; date; ntpdate 10.3.1.1
/usr/sbin/hwclock –systohc
** Add it cron
cat > /tmp/crontab.txt <<DELIM
*/10 * * * * /usr/sbin/hwclock –systohc
DELIM
crontab /tmp/crontab.txt; rm -f /tmp/crontab.txt
Install sudosh
-Setup sudosh
Assume root PWD is with security, enusre all user shells including roots are recorded when used, the sudosh-replay logs need to be shipped out via syslog. For the moment they are local “TPOC”
-echo “/usr/bin/sudosh” >>/etc/shells
Synchronise all group accounts
-Synchronise all group accounts across all systems to use specific GID’s using higher numbers so we have no chance of application group overlap i.e.
groupadd ops -g 1000
groupadd ops_support -g 1001
-Then ( only use -g 10 if they need sudo for root )
useradd spannerh -n -m -c “Spanner Admin” -G 1000 -s /usr/bin/sudosh
-use -p and crypt if you do not want to use #passwd spannerh to set the password
Disable YUM after updates run
-Disable yum automatic updates and do it manually if needed
-List all packages installed on the sytem:
yum list installed >> ~/installed.txt
-Add it to cron
cat > /tmp/yumtab.txt <<DELIM
#!/bin/sh
/usr/bin/yum -R 120 -e 0 -d 0 -y update yum
/usr/bin/yum -R 10 -e 0 -d 0 -y update
DELIM
cp /tmp/yumtab.txt /etc/cron.daily/yum_update.cron
chmod 500 /etc/cron.daily/yum_update.cron
-manual until we script it | kill off suid
find / \( -perm -4000 -o -perm -2000 \) –print
Ensure that the system cannot be messed with
-You should have a central logging system, on a remote server (LDAP with Kerberos/PAM auth and Samba for other OS cooperation)
-On critical machines can be installed/configured Host Based IDS and Network Based IDS at software level such as (Snort, AIDE, Tripwire, LogCheck, etc.)
Twenty-Five Linux Server Hardening Tips
When it comes to having a Linux server hosted in a data center or it is not behind any kind of Firewall or NAT device there are a number of security requirements that need to be addressed. Linux servers generally come with no protection configured by default and depending on the hosting company or distro can come preconfigured with many services installed that are not required, including Web Servers, FTP Servers, Mail Servers and SSH Remote Access.
The following is a compilation of various settings and techniques you can employ to harden the security of your vulnerable Linux systems. While I have tried to put them in order of the most important features first I would recommend all of these options be used on your critical production servers.
TIP #1 – Strong Passwords
Always create long passwords that contain upper and lower case letters, numbers and non alpha-numeric characters. Enforce password ageing so users need to change their passwords regularly. Lock user accounts after a certain number of failed login attempts.
TIP #2 – Use Public/Private Keys
Make use of Public/Private SSH keys for login of remote users instead of passwords, this provides the benefit of turning off password authentication in SSH so that your server can’t be Brute-Force cracked. However this does introduce a new problem whereby a malicious person could compromise a user’s computer or steal their laptop and then have access to the server. This can be overcome by using a password on the client certificate which must be entered before connecting, a kind of two factor authentication.
TIP #3 – Disable Root Login
Disable the Root user from being able to login either via the console or remote SSH connections. Instead have users use Sudo to run programs that require root privileges, or use sudo su to change to the Root user once logged in. This provides an audit path to show which user installed a piece of software or ran a program.
TIP #4 – Use Encrypted Traffic
Always use the encrypted equivalent protocol when transferring critical and sensitive data such as passwords and confidential material. Remove RSH and always use SSH for remote access. Instead of using FTP for file transfer, consider using SFTP or FTP/S (FTP over SSL) or RSYNC. Instead of having remote access open to the internet i.e. SSH or VNC setup an OpenVPN SSL VPN Server to connect to first.
TIP #6 – Use Centralized Password Server
Consider implementing either a LDAP or Kerebos server to perform password authentication. This allows for a central database to maintain user’s passwords between multiple servers for easy management. This prevents user account and password data from becoming inconsistent and out of date, and prevents user accounts that should have been deleted on all servers being left behind on one server.
TIP #7 – Use IPTABLES Firewall/TCP Wrapper
Implementing a secure IPTABLES firewall will limit your exposure to network threats such as DOS and Port Scanning attacks. You can lock down any ports that don’t require access from external networks. For instance you can use the following command to only allow SSH access to the server from the local network.
# iptables –A INPUT –s 192.168.0.0/24 –p tcp –dport 22 –j ACCEPT
You can install a TCP Wrapper named libwrap which will give information like who connected, when and from where and even which services they connected to. It can also be used for locking down access to ports and services for certain hosts or IP’s.
TIP #8 – Use Intrusion Detection Systems
Consider installing both a Network IDS (NIDS) and a Host Based IDS (HIDS). NIDS’s are used to protect against malicious threats such as DOS and Port Scan Attacks. HIDS’s such as AIDE are used to monitor file system changes such as an intruder replacing core system files like ls or ps with malicious ones that hide their Trojan from file or process lists. It will produce a report that tells you what files have been modified so you can repair or replace them.
TIP #9 – Users Assigned Least Privileges
Disable Shell access to users that don’t need it (ftp, mail users etc) by changing to /bin/noshell in the /etc/passwd file. Setup a group for standard users and remove permissions to tools that can be used to download malicious software like wget, lynx, ftp etc. Consider chrooting users to their home directories to stop them from modifying critical system files.
TIP #10 – Minimize Software
Only install software that is actually needed, some systems come preconfigured with many software packages that you may never need or use. When installing always choose the Minimal Installation or Manual Installation option if they exist. Then simply install the software that you actually need.
TIP #11 – Keep Software Updated
Always try to keep your software packages up to date, such as ensuring the latest version of Apache, MySQL and PHP on a standard LAMP setup will protect you against any vulnerabilities that have been discovered in previous versions.
TIP #12 – Disable Unwanted Services
Your servers will most likely have many background services (Daemons) running which are not required and some may be configured to run on start-up. The following command (Red Hat, Cent OS only) can be used to show all services that will start on boot.
# chkconfig --list | grep : on
Or just use the following command to view services which are turned on only for Run Level 3.
# chkconfig --list | grep 3:on
You would then use a command like this to remove the service from start-up.
# chkconfig --del ‘service-name’
TIP #13 – Remove X Windows
Consider completely removing X Windows from the system and just using the command line for management. There isn’t anything that you can do in the GUI that you can’t do using the command line and removing it will not only enhance security but also performance because no system resources are wasted displaying the GUI.
TIP #14 – Secure Linux Kernel
You can secure your Linux Kernel by modifying the /etc/sysctl.conf file, this file is read by the Kernel at boot time and can be edited with the following settings to add extra security.
# Turn on execshield
kernel.exec-shield = 1
kernel.randomize_va_space = 1
# Don't reply to broadcasts. Prevents joining a smurf attack
net.ipv4.icmp_echo_ignore_broadcasts = 1
# Enable protection for bad icmp error messages
net.ipv4.icmp_ignore_bogus_error_responses = 1
# Enable syncookies for SYN flood attack protection
net.ipv4.tcp_syncookies = 1
# Enable IP spoofing protection
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
# Log spoofed, source routed, and redirect packets
net.ipv4.conf.all.log_martians = 1
net.ipv4.conf.default.log_martians = 1
# Don't allow source routed packets
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0
# Don't allow outsiders to alter the routing tables
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.all.secure_redirects = 0
net.ipv4.conf.default.secure_redirects = 0
# Don't pass traffic between networks or act as a router
net.ipv4.ip_forward = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
TIP #15 – Install Linux Kernel Patches
You should have a written security policy for handling Linux Kernel Patches, which should include which Linux security notices have been received, which updates have been tested to ensure problems don’t arise and which patches have been installed on the system. Always ensure Production servers are updated regularly to avoid any potential known vulnerability from being exploited on your system.
TIP #16 – Separate Partitions
You should create separate partitions for user modifiable directories and block write and execute access to unneeded partitions. You should consider placing the following file systems on different partitions.
/usr
/home
/var and /var/tmp
/tmp
Then you can edit the /etc/fstab file to prevent execution of binary files, disable block devices on the partition and prevent the SUID/SGID from being set on files. Here is a common fstab file entry to limit user access to the ftpdata directory.
/dev/sda5 /ftpdata ext3 defaults,noexec,nodev,nosuid 1 2
TIP #17 – Use Linux Security Extensions
Make use of software like SELinux, AppArmor or GRSecurity to provide additional hardening to your Linux Kernel. These products provide additional policies to restrict processes and services based on Access Control Lists.
TIP #18 – Separate Servers for Services
Consider setting up different physical or virtual servers for different roles, i.e. separate your Mail server and your Webserver, or your Database server and your Application server. This ensures that if one particular service is compromised it is contained to just one server.
TIP #19 – Physical Server Security
You can secure your server as much as possible from remote attacks, but if you don’t do anything to protect the physical hardware it is pointless. If someone has access to your physical server they can remove your hard drive and read your confidential data or boot from a CD and access your data. Consider creating a BIOS password and disabling booting from CD or USB. Also you should password protect your boot loader (GRUB, LILO, etc) to prevent users from accessing Single User Mode or Recovery Environments where passwords are not required.
TIP #20 – Setup NTP
Having an accurate system clock is important for reviewing log files and determining when an event occurred. Often system clocks can become out of sync or be reset to an older date and this can cause havoc with tracking of errors. Consider creating a Cron job rather than running ntpd (See Tip #12) to update the time daily or hourly with a common source for all servers.
TIP #21 – Monitor All Logs
Setup logging and auditing software to track errors and changes to your servers, such as Auditd and Logwatch/Logcheck. Consider configuring a remote logging server that is updated regularly to protect against an intruder compromising your log files without your knowledge.
TIP #22 – Disable IPv6
IPv6 is very rarely needed at this stage as most traffic only utilizes IPv4 and having IPV6 enabled is just another network you need to monitor and protect. Disabling IPv6 is the easiest option but if for some reason you do require it then you should configure an IPv6 Firewall.
TIP #23 – Remove SUID and SGID from Files
After you have setup and configured your system and software you should run the following commands to search for all file and folders with either the SUID, SGID bit set or world writeable folders.
To find all SUID files:
# find / -xdev -type f -perm +u=s –print
To find all SGID files:
# find / -xdev -type f -perm +g=s -print
To find all World Writeable Dirs:
# find / -xdev -perm +o=w ! \( -type d -perm +o=t \) ! -type l -print
You should then inspect each file and folder to determine if they have the correct settings and if not use the chmod command to make changes to them.
TIP #24 – Encrypt Confidential Data
Your data is usually stored on a hard drive in an unencrypted format so any user that has access to the server can remove the hard drive and install it in another system and read all your data. You should consider configuring Linux disk or folder encryption on either your home directories or your sensitive folders (i.e. Database Files, Emails, etc). While you could encrypt your entire drive this is a lot of work and may not be worth the hassle.
TIP #25 – Harden Your Software
It is great to have a highly secure Linux server but your system is only secure as the software you run on it. You should always install the latest versions of software and ensure they stay up to date. Also most programs have ways to make them more secure by editing their configuration files and disabling unnecessary parts of the software. The following is an example for hardening your OpenSSH Server settings, simply add the following to your OpenSSH config file.
# Use only SSH Protocol Ver 2
Protocol 2
# Only allow the following users SSH Access
AllowUsers User1 User2 etc
# Deny access to the following users
DenyUsers admin etc
# Set the timeout period for idle sessions (in seconds)
ClientAliveInterval 300
ClientAliveCountMax 0
# Disable .rhosts files
IgnoreRhosts yes
# Disable Host-Based Authentication
HostbasedAuthentication no
# Remove ability to login as Root
PermitRootLogin no
# Change the default SSH Port (Not essential but can help uncomment if you want)
#Port 22
#ListenAddress 192.168.1.1
# Consider CHRooting users to their own directories.
# Subsystem sftp internal-sftp
#Match group sftponly
# ChrootDirectory /home/%u
# X11Forwarding no
# AllowTcpForwarding no
# ForceCommand internal-sftp
# Disable empty passwords from login
PermitEmptyPasswords no
# Set your required Log Level (Either INFO or DEBUG)
LogLevel INFO
# Turn on privilege separation
UsePrivilegeSeparation yes
# Prevent the use of insecure home directory and key file permissions
StrictModes yes
# Turn on reverse name checking
VerifyReverseMapping yes
# Do you need port forwarding?
AllowTcpForwarding no
X11Forwarding no
# Specifies whether password authentication is allowed. The default is yes.
PasswordAuthentication no
Recent Comments