Hey friends, Do you want to launch your own production cloud server but don’t have the budget to hire dedicated security professional for implementing security on your server. Worry no further. I will teach you in this article how you can secure your Ubuntu Server for production Usage in few simple steps. Although these steps have been performed on Ubuntu 20.04.1 LTs with root privileges, it can work on any Linux distro with little changes.
Jump Directly To
Keep Your Server Updated
An extremely crucial part of hardening any server/system is to ensure that it is always kept up-to-date. Keeping your server updated means that your system is patched for any known bugs, if there is any. Using the command below will update your ubuntu system in few moments.
//Update ubuntu server apt-get update && apt-get upgrade //Use sudo if not logged with root privileges
Linux Kernel Security Hardening
Sysctl is a command on linux systems that acts as an interface to dynamically change kernel parameters. Sysctl.conf is a simple configuration file containing sysctl values to be read in and set by sysctl. Use the settings below to harden the kernel configurations.
//First things first, use the command below to see all the sysctl settings sysctl -a // Cofigurtions can be udated by using -w switch like below: sysctl –w net.ipv4.conf.all.rp_filter=1 // But preferred way to update settings directly into sysctl.conf file //open sysctl.conf file in editor nano /etc/sysctl.conf //Update the settings in conf files as per the instructions below. If the below settings are commented, uncomment it and change values accordingly. //Turn on Source Address Verification to enable spoof protection net.ipv4.conf.default.rp_filter = 1 net.ipv4.conf.all.rp_filter = 1 //Enable TCP/IP syn Cookies to protect from SYN pacets flooding net.ipv4.tcp_syncookies = 1 net.ipv4.tcp_synack_retries = 5 //Protection from network attacks like MITM & Spoofing attachs through redirection net.ipv4.conf.all.accept_redirects = 0 net.ipv6.conf.all.accept_redirects = 0 net.ipv4.conf.all.send_redirects = 0 net.ipv4.conf.all.accept_source_route = 0 net.ipv6.conf.all.accept_source_route = 0 //Log problematic martian packets net.ipv4.conf.all.log_martians = 1 // Ignore all ICMP ECHO and TIMESTAMP requests sent to it via broadcast/multicast net.ipv4.icmp_echo_ignore_all = 1 net.ipv4.icmp_echo_ignore_broadcasts = 1 //Increase system IP port limits net.ipv4.ip_local_port_range = 2000 65000 //Reboot the machine soon after a kernel panic kernel.panic=10 //Reload configurations after the changes are done in sysctl.conf files and saved sysctl -p
Host.conf hardening
Although host.conf hardening does not do much impact these days as the operating systems are already equipped to handle these scenarios. These steps can be treated as a good to have steps. So, what are we doing in the host.conf hardening? The order directive tells the system in what order it should lookup information. By default, the system first checks the host file and then uses DNS information. In the hardened version, the system first checks DNS and then uses the hosts file. It is disclaimed that order directive is only used by old c library. The ‘multi on’ directive simply allows the resolver, the system that translates hostnames into IP addresses, to return multiple listings if they are found in the hosts file. The ‘nospoof on’ setting will compare the IP address returned by a hostname lookup to the hostname returned by an IP address lookup. If the forward and reverse lookups do not match, then a spoof warning is generated.
///Default entry # The "order" line is only used by old versions of the C library. order hosts,bind multi on //change the values to the below values order bind,hosts multi on nospoof on
Users & Groups Security
Another hardening which should be done and which is very important is about the user’s security. You have to ensure that only authorized users should be able to login into your server and that your server is protected from unauthorized logins. The below steps will help you to ensure it. Before performing these steps let’s understand what’s difference between a user and a group. In simpler terms, Group is a collection of user, ids, or objects. When you allow permission on any group, all the users present in that group get the same right. User is individual identity and permission or one user might be different from another user. A user can be a member of multiple groups. Let’s dive in now.
All About User Groups
//list all groups, please check that no other group apart from root should have id as 0. if another group has same level as 0, check and remove it $ cat /etc/group //create a new admin group using the commands below $ groupadd admin //Removing a group. Remember grou can only be deleted if all the users present in this group has been removed from the group $ groupdel Group_Name //adding users to groups //You can use the usermod command to add a user to a group. below command will show you to add the user "alex" to the group "admin". The -a parameter means "append" and the -G parameter adds a group as a secondary group. $ usermod -a -G admin alex //You can also add a user to many groups at once by separating the group names with commas. -G group1,group2,group3. //First, the id command can be used to check what secondary groups a user belongs to: $ id -nG alex //Removing a user from a secondary group requires you to overwrite the current groups of a user with a new set of groups that does not contain the group that is being removed. Let's say that 'alex' is part of the "alex",admin, and "sudo" group. If you want to remove the "sudo" group, use this command: $ usermod -G admin alex //(Since the -a flag was not used, the previous set of groups was overwritten)
All About User Accounts
Managing user accounts on your server is very crucial for server security. Anything done incorrectly can be devastating for your server. So, it’s important that you only create a specific number of user accounts which is important to be used on your server. For security reasons, it is safe to disable the root account. Removing the account might not be a good idea at first, instead, we simply need to disable it. Also, it has to be ensured that there are no more than one root user present on the server. Let’s dive in:
//list all users $ cat /etc/passwd //Adding Users. It is best practice to keep the use of the root account to a minimum. $ adduser userName // Change password for users //$ passwd (for changing password of logged in user) $ passwd userName (for changing password for a particular user) //Deleting a user $ userdel userName (it keeps the home directory of users) //$ userdel -r userName ( it deletes users as well as its home directory) //checking for root users. ensure that no more than one root users should exist on the server. if multiple roots users are present, please remove extra users $ awk -F: '($3 == "0") {print}' /etc/passwd //The command below will print all accounts that have an empty password:Please remove it for safety reasons cat /etc/shadow | awk -F: '($2==""){print $1}' //Granting Sudo rights to nwly created users. its as simple as adding new users to sudo group $ usermod -a -G sudo alex //Now alex can use sudo command. but whenever sudo commnd is used, he will be prompted to type in his password. To ensure that he is not asked for password, you will have to do below modification in /etc/sudoers file $ nano /etc/sudoers //(opening sudoers files for editing) $ alex ALL=(ALL) NOPASSWD: ALL //(this setting will remove password prompt from alex for using sudo) //Keep use of root account to a minimum. its advised to lock root account or unused useraccount. Before locking root account, ensure that you are not locked out of your server. $ passwd -l userName //(lock username) $ passwd -u userName //(unlock username)
Server SSH hardening
SSH hardening is one of the most critical parts of server security. Since SSH provides direct access to the server it is important to understand how critical SSH security is. Therefor do the following activities. Disable password-based login, only allow key-based login through shell, only few users should be allowed, only specific IPs should be allowed, harden SSH config as shown below. Let’s dive in
//Allow key based login for a particular user ssh username@remote-system mkdir ~/.ssh chmod 700 ~/.ssh edit ~/.ssh/authorized_keys and copy the public key scp authorized_keys [email protected]:/home/alxajft/.ssh/ chmod 600 ~/.ssh/authorized_keys // open ssh server config file and do the following changes $ nano /etc/ssh/sshd_config //Before editing ssh_config file, you can review the options that are currently set using the command below $ sudo sshd -T //Change SSH port Port 900 (make the number a bit higher so that its difficult to be found in port scan) //Disable x11 forwarding if not getting used X11Forwarding no //Disable rhosts IgnoreRhosts yes //Check and do the below settings in sshd_config file UseDNS yes PermitEmptyPasswords no MaxAuthTries 3 PubkeyAuthentication yes PasswordAuthentication no PermitRootLogin no ChallengeResponseAuthentication no KerberosAuthentication no GSSAPIAuthentication no PermitUserEnvironment no // Allow ssh login from allowed users only AllowUsers john root //AllowUsers [email protected] [email protected]<^> //Restrict a specific user to a specific IP address, while continuing to allow all other users to log in without restrictions: Match User tango AllowUsers [email protected]
Knowing More About Your Server
The below command can be an Ubuntu sysadmin’s best friend, it will list all current connections and listening services on a system along with the processes and PIDs for each connection:
//Show all active SSH connections $ ss -n -o state established '( dport = :22 or sport = :22 )' //change port from 22 to your server port //Disable shell accounts will allow the account to be active without the ability to login on your server. //To see which active accounts are on your server, run: $ cat /etc/passwd | egrep -v '\/false|\/nologin|\/shutdown|\/halt' | cut -d':' -f 1,7 //You can disable account using this command: $ usermod -s /usr/sbin/nologin "username" // (without quotes) //Checking for open posts $ netstat -npl //list all current connections and listening services on a system along with the processes and PIDs for each connection: $ netstat -tulpn //Display Services and Their Status $ service --status-all $ service --status-all | grep "[ + ]" //Use grep to specify only the running services
Implement SELINUX / AppArmour
Security-Enhanced Linux (SELinux) is an access control security mechanism provided in the kernel. It has to be remembered that certain Linux flavors come default with AppArmour which needs to be disabled before using SElinux.
//Check selinux status $ sestatus //Stop AppArmor using systemctl: $ systemctl stop apparmor $ apt remove apparmor //do not use apt purge apparmor if you think this might create problems //If Command 'sestatus' not found, it can be installed with: $ apt install policycoreutils //default options in selinux Enforcing: This is default mode which enable and enforce the SELinux security policy on the machine. Permissive: In this mode, SELinux will not enforce the security policy on the system, only warn and log actions. Disabled: SELinux is turned off. //Open selinux config file and update the options as needed $ nano /etc/selinux/config //If you have set SELinux to enforcing mode, ensure that your SSH port has access before logging out of your session. $ semanage port -l | grep 'ssh' $ semanage port -a -t ssh_port_t -p tcp 22 //If you do not see this entry, open the port with the following command
Install Fail2Ban
Fail2ban is an intrusion-prevention system that monitors log files and searches for particular patterns that correspond to a failed login attempt. If a certain number of failed logins are detected from a specific IP address (within a specified amount of time), fail2ban blocks access from that IP address.
//install, enable and start fail2ban service $ apt install fail2ban $ systemctl enable fail2ban $ systemctl start fail2ban //the main fai2ban jail configurations are located at /etc/fail2ban/jail.conf . its not advised to update the configurations in this file as this file usually gets updated. so either create a new file with the name jail.local or copy jail.conf as jail.local file and do the changes $ nano /etc/fail2ban/jail.local // $ cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local (copying main file as jail.local) //add below congirations in the file [sshd] enabled = true port = 22 filter = sshd logpath = /var/log/auth.log maxretry = 3 //save and close the file and restart the fail2baan service $ systemctl restart fail2ban
Install & Configure Firewall
How can we expect a complete security without a set of good firewall rules. Here we go. UFW, or Uncomplicated Firewall, is an interface to iptables
that is geared towards simplifying the process of configuring a firewall.
// Install UFW and setup rules first before enabling it so that ssh connection is not blocked $ apt-get install ufw $ ufw limit 22/tcp // limit ssh port for more than 6 connections from a particular ip $ ufw allow 80/tcp //allow http $ ufw allow 443/tcp //allow https $ ufw enable //allow ufw // Verify ufw status $ ufw status // Do Global default block configurations $ ufw default deny incoming $ ufw default allow outgoing
Server Security Disclaimer
Server security is a never-ending process and thus it has to be pursued as an ongoing process. The steps mentioned in this article will make your server pretty hacker-proof and stable for production use. The article will be updated with time. In case you think some points are missed, do comment that below and if you think this article can benefit your friend or family member, so share this article with them. Best of Luck!