Stay Tuned!

Subscribe to our newsletter to get our newest articles instantly!

Feature Security

How to Harden the Ubuntu Server in 2022

Background

As I wrote the blog – A Complete Setup Guide for Contabo VPS Ubuntu 20.04 with preinstalled Webmin + LAMP previously, my next step is to harden this server from the attackers.

We also started using more internal cloud-based applications to host our website and applications. We compiled a blog post about how to secure Ubuntu and ensure it’s appropriately hardened against cyber-attacks.

It’s important to note that even with the steps described above, it’s impossible to prevent all cyber-attacks against a website. The most practical thing we can do is mitigate the risks as much as possible by following best practices and implementing additional security measures.

Last Updated – 2023-08-25: Added the Only Allow the Port if you need access and give internal access only section.

Solution

Here is the setup:

Enabling Automatic Updates

When you reinstall the VM, log in via SSH and you find this message:
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

You need to remove the 3 lines associated with the IP address on the .ssh folder on your client machine.

The servers need to be patched. If you don’t patch your server, it will likely be hacked. To update your server manually can be challenging, but some commands make it easy to keep track of what needs to be updated regularly.




To update the server manually:

sudo apt update

To install the update:

sudo apt dist-upgrade

To install the automatic update utility:

sudo apt install unattended-upgrades

To setup:

sudo dpkg-reconfigure --priority=low unattended-upgrades

The GUI pops up. For the Automatically download and stable updates option, select the Yes button.




Creating Login Other than Root in SSH

Login SSH using root is something that you need to avoid.

To do this, create another user called, let say anotherroot and give this is administrator access (sudo group).

adduser anotherroot

Enter the password. Enter the profile questions.

Add the user to the sudo group:

usermod -aG  sudo anotherroot

Logged out from the terminal.




Try login the new user:

ssh [email protected]

To test the without a sudo:

adduser anotherroot2

This will show the command not found!!!

To try with a sudo:

sudo adduser anotherroot2

This should prompt a password and the test user will get created.




Removing the Use of Password in SSH

Password can be brute-forced. So to avoid this, we use the authentication key pair instead (the public and private keys). On the server, we will give the public key while on the client (laptop/desktop) we use the private key.

The analogy will be the public key is a padlock while the private key is a key.

Log in to the anotherroot user on the terminal (Powershell or any)

ssh [email protected]

Create a folder:

mkdir ~/.ssh && chmod 700 ~/.ssh
Do not use sudo as the owner needs to be anotheruser/anotheruser

This command will create a folder called .ssh under the home directory – /home/anotherroot where the public key will be stored and give the right permission.




Log out:

logout

Back to the terminal (Powershell / Linux Shell) and create the pair:

ssh-keygen -b 4096
4096 is how big the key is. The bigger is better.

The question pops up. Enter file in which to save the key (C:\Users\[your_windows_user]/.ssh/id_rsa):

Leave the default and press enter.




If it’s prompted to overwrite, it means that the key has been generated previously that is being used to access other servers. Be careful with this! Please backup first or cancel this action and give another name.

Enter a passphrase or you can leave it blank.

The 2 keys should be created under C:\Users\[your_windows_user]\.ssh\id_rsa and C:\Users\[your_windows_user]\.ssh\id_rsa.pub

To verify the key-pair, still under the terminal:

sudo cd .ssh
sudo ls

Back up these key pairs to somewhere save ie. your password library.

The next step is to upload the public key into the server, still on the terminal:




scp -P XXX $env:USERPROFILE/.ssh/id_rsa.pub [email protected]:~/.ssh/authorized_keys
The command above is only for Powershell.

Try now the login and this should not prompt a password:

ssh [email protected]

Straight in without a password!!!

Lockdown SSH Logins with No Password

Before doing this, ensure you have VPN access from your host provider to the machine just in case.

Log in to the server using anotherroot:

sudo nano /etc/ssh/sshd_config

Go to the line and replace the line:

PermitRootLogin yes

with
PermitRootLogin no

Go to the line and replace the line:




PasswordAuthentication yes
PasswordAuthentication no

To save the document, press Ctrl + X and press Y, and enter.

Restart the ssh server:

sudo systemctl restart sshd

To test it, leave the current terminal, just in case.

Open another terminal to test with the root account:

ssh [email protected]

This account should not be logged in – permission denied (public key).




Changing the SSH Port

Log in to the server using anotherroot:

sudo nano /etc/ssh/sshd_config

Replace the line:

#Port 22

with something other than 22 and in this case 222 for instance

Port 222

Replace the line:

#AddressFamily any

with allowing IPv4 only:




AddressFamily inet

To save the document, press Ctrl + X and press Y, and enter.

Restart the ssh server:

sudo systemctl restart sshd

To test it, leave the current terminal open, just in case.

Open another terminal to test:

ssh [email protected] 

This account should be a connection timeout.




Test again with custom port – 222:

ssh [email protected] -p 222

Activating the Firewall

Putting a firewall or a fence up around the perimeter, it will make the server more secure.

Start the terminal (Powershell) and login into the server

ssh [email protected] -p 222

To see what port is being opened (listened to):

sudo ss -tupln

There should be a list and check out the Local Address.Port heading.




If your current server has a long list, please document and do some research about the port.

To install the firewall:

sudo apt install ufw
By default, this is not going to be activated.

To see the status:

sudo ufw status

This should be inactive.




Before activating this, the first requirement is to allow SSH with a custom port first.

sudo ufw allow 222

The rules should be updated (ipv4 and ipv6)

The following command will activate the firewall. This will block everything except the custom port.

To activate the firewall, enter:

sudo ufw enable

Press Y and the firewall should be active and enabled.




To check the status:

sudo ufw status

You should be to see To / Action / From only for that port 222

To test it, leave the current terminal open, just in case.

Open another terminal to test:

ssh [email protected] -p 222

If you are in, that means good!




Add more ports if necessary such as port 80/443 (web)

Only Allow the Port if you need access, and give internal access

If you need to disable the SSH port, you need to have a backup method to get into systems open such as VNC via host or Webmin.

In the case of custom SSH port 222 above, only allow it when you need access and limit your public IP Address.

To remove the firewall rule:

sudo ufw status numbered
sudo ufw delete X

Ensure to run again the status numbered if you want to delete other rules.

sudo ufw status numbered
This same applies to FTP Access (port 21). If you don’t need it, remove it.

Blocking the Ping

We want the machine to be hidden and to do this by blocking the ICMP ping request on the UFW firewall.




Start the terminal (Powershell) and log into the server

ssh [email protected] -p 222

To edit the config:

sudo nano /etc/ufw/before.rules

Add a new line under the #ok icmp codes for input section:

-A ufw-before-input -p icmp --icmp-type echo-request -j DROP

To save the document, press Ctrl + X and press Y, and enter.

Restart the firewall:




sudo ufw reload

Reboot the machine:

sudo reboot

Run the terminal to see if it’s rebooted successfully:

ssh [email protected]

To test it, open up another terminal.

Ping the IP address:

ping xxx.xxx.xxx.xxx

This should display the request timeout.




Changing the Webmin Port

Before changing the Webmin port, please ensure to allow the port in the firewall. Once the process below complete, then remove the default port from the firewall.

Webmin tool is used for managing the admin easily. Changing the port is the way to make it secure.

Open up the browser and access the Webmin via IP address and the default port.

Webmin

Click the Webmin Configuration link.

Select the Ports and Addresses link.

Under the Listen on the port, select a specific port to 10001 for instance.




Under the IPv6 connection, select the No option.

Under Listen for broadcast on UDP port, type in 10001.

Click the Save button.

Under the Web Configuration, click the Restart Webmin button.

Starting the Webmin Service if only Needed

Open up the browser and access the Webmin via IP address and the default port.




Webmin

Click the Webmin Configuration link.

Under a Start a boot time, select the No option.

Click the Start at boot time button.

To start manually:

sudo /etc/webmin/start

To stop again:




sudo /etc/webmin/stop

Setting up Two-Factor Authentication in Webmin

Open the browser and access the Webmin via IP address and the default port.

Webmin

Click the Webmin Configuration link.

Click the Two-Factor Authentication link.

Select Google Authenticator as the Authentication provider.

Click the Save button.




Go back and go to Webmin Users link.

Select the User and activate the Two-Factor Authentication by scanning the QR code.

Test by logging out of Webmin.

Log in again, and it should ask for the password and token.




That’s it! The solution above will at least protect the server. It does not mean it is not hackable, but it at least makes it the hacker to attack the machine, and we want to be safe.

Checking the PHP version

Check the current version:

php --version

Then it showed the 7.4.3 version

Then you check, hang on isn’t that the minor version already more than 3? It’s not being updated then ?!?!

It’s a common mistake!!! See below for an explanation.




With Ubuntu Focal Fossa 20.04 LTS, PHP was frozen at version 7.4.3. That means Focal’s PHP package will never again get a minor release update (e.g. 7.4.x) throughout its support lifespan. However, that doesn’t mean that the PHP package will never ever get updates at all.

The proper version needs to be checked on the apt package by running a command:

apt policy php7.4

The output:

Then, search on Google to find the package’s (7.4.3-4ubuntu2.15) change log to see what’s included in that build.

UbuntuUpdates.org

Updating the PHP configuration

Before applying this, please ensure to back up this php.ini. Also, please consult with the web developer cause some of these recommendations might break the web application i.e. downloading or upgrading plugins.

For the webserver (Apache) that uses the PHP module, modify the settings accordingly.

Before doing this, the php.ini can be in a different location, check the default location:




php --ini

Check the loaded configuration file location.

Download the php.ini, change accordingly, and upload back in:

expose_php = Off

display_errors = Off

mail.add_x_header = Off

session.name = PHPSESSID

allow_url_fopen = Off

allow_url_include = Off

disable_functions = show_source,system,shell_exec,passthru,exec,phpinfo,popen,proc_open,allow_url_fopen,curl_exec,curl_multi_exec

Restart the Apache:

sudo /etc/init.d/apache2 restart

Check the website if running ok or not.




The End

If you have reached the end of this article, congratulation. Hopefully, we have been able to shed some light on outlining what you need to know to harden Ubuntu Server.

Let’s Discuss – We would love to hear about how you deal with the situation and what problems you might be facing. Please feel free to comment below this article or jump into our Dewachat and let us know if you have any questions we can answer! If you like our content and would like to say thank you, you can support us by buying me a coffee.

We write this so that this is not a fixed article. Like in this journey, we learn as we go and re-write some parts, so please keep pinging with this article.

Take a Look – To boost your product and service to the broader web community, you can visit our Dewalist classified website – home to 39,000+ active registered users and 52,000+ one year of active advertising so far.

If you like this post, please check out our other related posts:

Try it Out – To solve, maintain and monitor Search Engine Optimisation (SEO) and other web challenges, check out our Dewagear tools website – home to 50+ tools so far.

If you love this article or any security posts and you would like to receive an update on this article or our latest post, please sign up for the form below:

Newsletter signup

This is a newsletter for tech, creative, gadgets, games and crypto.




Please wait...

Thank you for sign up!

Valdy

About Author

Valdy founded Dewacorp.com, a helpdesk and IT Services provider that has taken care of nearly 40,000 customer service requests in the past 15 years - nearly 2,600 per year. He also created the growing Dewalist.com - a classified website that has close to 110,000 page views and 9,000+ user visits per month with 61,000+ yearly published ads and 47,000 active registered users. He blogs for the ever-growing Dewapost.com, a tech blog that gets around 20,000 impressions per month with 700 clicks and 10 average pages first impressions on Google Search. You can reach him on the Contact Us page, social media links below or Dewachat.com.

You may also like

Feature Tech

A Complete Setup Guide for Contabo VPS Ubuntu 20.04 with preinstalled Webmin + LAMP

Background I haven’t touched the Linux server for ages and getting used to it with Cpanel or Parallel. However, as
Security

How to Harden Router Security for Home/Office in 2022

Background As configured more routers on-site either in the office or home-office environment, we started to compile on how to