5 practices to keep Linux SSH secure

Introduction

Minimizing vulnerabilities in your Secure Shell (SSH) protocol is essential to ensure the security of your Linux environment.

In this article, we address the measures of SSH security most common Linux that you can adopt to make your servers more secure. By changing the default SSH port, using key pairs and following other best practices, you can significantly improve the overall security of your system.

What is SSH?

THE Secure Shell (SSH) protocol allows remote system administration protected by encryption and file transfers over insecure networks. Using various encryption methods, SSH protects the connection between a client and a server, protecting users' commands, authentication and exit from unauthorized access and attacks.

The SSH protocol is now widely used in data centers and by almost all large companies running on any of the UNIX variants.

When it comes to security measures, it is essential to combine them, apply them in layers and not choose just one and rely only on this solution.

Read more:

Changing the Remote Desktop 3389 default port
The importance of email auditing
Enabling the RDP Protocol via Powershell
How to install FileZilla on Linux manually
Device security: how to protect them properly?

1. Change the default SSH port

The use of a non-standard port for SSH connection helps to prevent automated attacks on your server. It also helps to reduce the chances of appearing on a hacker's radar and makes him a less obvious target.

Note : Most hackers looking for OpenSSH servers will aim to standard SSH port 22.

In this case, the scripts they are using will look for IP addresses on port 22 only. If the server falls into this group, all automated attacks will affect their log files. Consequently, the load on the server can increase substantially, as many exploits of the SSH server are running 24 hours a day, knocking on the door of all servers.

It is important to note that changing the default SSH port does not improve the security of your server. However, it helps to prevent automated attacks.

How to change the port number

Before you start, you need to decide which port to use instead of the default port 22. Before making a decision, consider a few things:

To change the port on your Linux server , follow these steps:

1. Connect to the server via SSH as you normally would.
2. Switch to the root user using the su command, which will prompt you to enter the server password.
3. Use a text editor of your choice to edit the sshd configuration file located in etc / ssh / directory If you have never used a text editor inside the terminal, it is recommended to use Nano. Otherwise, use vi or vim, as they are the most used editors today. We advise you to back up the original file before making changes.
4. Run this command to edit the configuration file:

nano / etc / ssh / sshd_config

5. On file output sshd_config, find the line that says ” Port 22.”

editando o arquivo de configuração sshd

6. Change the port number to the value of your choice. Make sure there are no ” #”At the beginning of the line.
7. Exit the editor and confirm that you want to save the changes.
8. For the changes to take effect, restart the sshd service with this command:

service sshd restart

9. Verify that SSH is listening on the port you specified by connecting to it.

Note that you will now need to specify the port when connecting, as your customer will always use the standard SSH port, unless otherwise stated.

#Professional Tip: How about you have more security in your work?
Ensure professional service by taking one of the IT and Software courses on the online study platform Udemy.
Access here and learn more!

Benefits

While the procedure for changing the default SSH port does not increase the security level itself, it does take away the radar from the most common scans. An easy way to test this is to let the server run for a few days with sshd listening on the standard port and then change it to a non-standard one. Compare the number of failed logins on your server and you will see a substantial reduction.

Using a non-standard port for SSH:

  • You avoid being seen by random checks.
  • It is more difficult to find your server. Most attacks will scan the standard port or some variants of it, but will continue as soon as the connection is refused.
  • The SSH daemon can pause as it will not receive connection requests for scripted attacks. The server load is reduced and the log file remains clean, saving you time to review it.
  • You don't get as many alerts for login failures. If you are using a non-standard port and someone is still trying to access the server, it probably means that the server is being targeted specifically and that the alarm does not come from a scripted attack.
  • You are less exposed to being hacked due to errors in sshd or weak private keys.
  • Most hackers will be repelled if they notice that you are not using the default port. It will be a sign that the server is adequately protected and that other security measures are probably also in place, making the server an undesirable target.

Disadvantages

There are a few precautions to remember before you decide to change the default SSH port. The disadvantages of running a non-standard port may mean that:

  • Anyone who can connect to your server will need to be informed of the change and will have to start using the new port.
  • If you are using third-party monitoring for the server, you also need to make them aware of the change. Otherwise, they can treat this as a potential threat that can lead to server downtime.
  • Firewall rules related to the SSH service should be inspected and modified according to the changes made.

Some of these disadvantages are unlikely to apply to your use case, but should be taken into account. The benefits of changing the port outweigh the disadvantages and prove to be a good additional layer of security for your server.

2. Enhance Linux SSH security using key pairs

One of the most secure methods for authenticating clients on servers is to use SSH key pairs . Strong passwords may be sufficient to keep your server secure, but persistent brute force attacks can still crack them. That's why you need additional SSH reinforcement with key pairs.

SSH keys are resistant to these attacks and are virtually impossible to decrypt. An SSH key pair consists of two long series of characters, one private key which is kept secret and a public key that can be safely shared. Its purpose is similar to passwords and allows you to automatically establish an SSH session without the need to enter a password.

How to generate a key pair

To configure SSH keys, you will need to generate a key pair on the client computer that will be used to connect to the server. To do this:

1. Start the terminal and run the SSH keygen utility , available with the standard OpenSSH tool.

ssh-keygen –t rsa

2. You will receive the message ” Generating public / private RSA key pair ”. If you want to save the key in the default location, press Enterwhen solicited. The key will be saved in the home user's directory, in the ~ / .sshdirectory To change the location, just enter the new path. The recommendation is to keep the default location, so that you don't have to make changes to your SSH client. The private or identification key will be saved as id_rsaand the corresponding public key as id_rsa.pub.
3. Optionally, you can enter a password . If you don't want to use one, press Enterto continue. The password provides an additional layer of security by encrypting the private key on the local machine. To crack the password, a hacker will first need to access the system, as the private key is not exposed on the network. Even so, it will take time to be successful, allowing you to change the key used before the hacker gains access to other servers. The downside is that you will need to enter it every time you try to connect using this key.

The process of generating a key pair is complete.

The final screen will look like this:

ssh-keygen -t rsa Generating public / private rsa key pair. Enter file in which to save the key (/home/demo/.ssh/id_rsa): Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /home/demo/.ssh/id_rsa. Your public key has been saved in /home/demo/.ssh/id_rsa.pub. The key fingerprint is: 8b: cd: 0b: f7: 38: 4a: 3f: ed: 24: 18: 8d: 54: 34: 2c: 63: 56 your_username @ host The key's randomart image is: + - [RSA 2048] ---- + | ..The. | | . Eo | | +. o | | . = =. | | ..S | | = + = + | | . o + o. | | . + + o | | .. | | | + ----------------- +

note: You can make authentication / authorization even more secure by creating keys larger than 4096 bits instead of the standard 2048 bits. To do this, add –B 4096to ssh-keygencommand. This will look like this:

ssh-keygen -t rsa -b 4096

#Professional Tip: How about you have more security in your work?
Ensure professional service by taking one of the IT and Software courses on the online study platform Udemy.
Access here and learn more!

Copying a public key

To use the key pair you created on your machine for SSH authentication, it is necessary to place the public key on the desired server. The simplest way to do this is to use the tool available in OpenSSH:

ssh-copy-id

The procedure is easy:

1. Type ssh-copy-id username @ your_host_address.
2. If you are connecting to this host for the first time, you will receive an authenticity message. type it Yesto continue.
3. Enter your password when requested, and the tool will copy the contents of the ~ / .ssh / id_rsa.pub key to authorized_keysfile no ~ / .sshhome directory of the server.

note: No characters will be visible as you enter the password for security reasons.

4. You will receive a message:

Your public key has been placed on the remote server and you can now log in without entering your account password.

5. To test whether key authentication is working, connect to your server with ssh username @ your_host_address. If successful, you will be logged in automatically. If you have previously set up a passphrase, you will need to enter it first before gaining access to the server.

How Keys Work

Essentially, a public key it is not a key. It behaves like a padlock that you can place on an SSH account on another machine. When you run the 'ssh-keygen' utility, it generates the padlock and the key that opens it id_rsa.puband , id_rsa respectively.

You can make as many copies of the padlock necessary, distribute them to any server you want and only you will have the right key to unlock them all. That’s why it’s important to keep the private key secure, as it unlocks all copies of padlocks that you distributed.

It doesn't matter where you put your public key, as long as the master key is not compromised. Since no one else has the private key, this authorization and authentication method is probably the most secure and highly recommended.

3. Disable the root login of the SSH server

Linux server distributions have external root access enabled by default. This can be a serious security threat, as hackers can attempt to crack the password with brute force attacks. It is recommended to disable root login and use a regular account and command to switch to the root user. su - command to switch to the root user.

Before disabling root logon, add an account that can obtain root access. To do this, follow the steps below:

1. Use SSH to log in server login as root.
2. Use a text editor to open the main configuration file. This time, we will use the editor saw .

vi / etc / ssh / sshd_config

3. Find the line that says “ PermitRootLogin_yes and switch to PermitRootLogin_no. You may need to scroll down a few lines to find it.
4. It is important add the user account that you'll use to sign in. Just add another line with the username in question:AllowUsers your_username_here
5. Save the changes made and skirt the text editor.
6. Restart the SSH service, but not yet close the root session. For Ubuntu / Debian use sudo service ssh restartand for Fedora / CentOS use the service ssh restart command
7. Open a new terminal window and verify that you can now log in as the user you added. After confirming that it works, skirt of the active root session.

4. Disable password-based logons on the server

If you are using SSH keys for SSH authentication, you can completely disable server password authentication. This is another way to keep your server safe from brute force attacks and attempts to crack your password. Before proceeding, verify that SSH key-based authentication is working for the root account on the server or an account with access sudo .

When you're ready, follow these steps:

1. Use SSH keys to make server login as root or with sudo privileges.
2. Use a text editor to open the file sshd_config . Let's use the saw:

vi / etc / ssh / sshd_config

3. Look for the line that says PasswordAuthenticationand switch to PasswordAuthentication_no. Be sure to uncomment the line if #any.
4. Save the changes made and skirt the text editor.
5. Restart the SSH service to apply the changes. For Ubuntu / Debian use sudo service ssh restart and for Fedora / CentOS use the service ssh restartcommand

Congratulations, you have successfully disabled the option to login via SSH using account passwords. The SSH Daemon will simply ignore any authentication requests that do not include public / private key pairs.

#Professional Tip: How about you have more security in your work?
Ensure professional service by taking one of the IT and Software courses on the online study platform Udemy.
Access here and learn more!

5. Restrict SSH access using iptables

Iptables is a Linux utility used to configure firewall rules and monitor / filter incoming and outgoing traffic on your server. It is included by default in most Linux distributions.

With iptables, you can define rules which limit or allow traffic to different types of services by IP address, port or network protocol and thus substantially improve the security of your server. In our case, we will define firewall rules to restrict incoming SSH traffic to everyone except an IP address or subnet.

In this way, blocking port 22 not only stops unauthorized access to your servers, but can also stop or prevent DDoS attacks.

When performing this step, make sure not to block yourself by completely blocking SSH traffic. You will only need to use a few commands to allow a specific IP address or subnet for incoming SSH connections.

Note : Commands are case sensitive.

1. This rule will include the entered IP address in the white list. Replace the example of IP in the command with your IP. You can also use a subnet, for example, 10.10.10.0/24.

sudo iptables -A INPUT -p tcp -s 123.456.78.90 –dport 22 -j ACCEPT

2. You need to save the rules in order not to lose them after the restart:

sudo iptables-save

If you want to view the list of all iptables rules, you can use the command To include more details, such as information about packages, bytes and destination, add to the command above. Add it all up and the output will be displayed in numeric format.iptables–L –V -n

If you want to reset all the rules and start cleaning, use the flush command This will clear the iptables configuration, which is useful if you are not sure if everything is configured as you wish.iptables –F

Iptables Parameters and Option Definitions

Here are some explanations for the iptables parameters, options and values ​​used in the examples above, as well as some not mentioned earlier.

Valuedescription
ACCEPTAllow packets to pass
DROPBlock packets
RETURNSSays to skip the current chain and continue on to the next rule in the previous chain (caller)
> Parameterdescription
accountants  allows you to define the packet and byte counters for a specific rule
-ddestiny - can be an address, host name or address etc.
-ffragment - applies the rule to the second and the fragments that follow it
-gGo to jail - indicates that the action will continue in a user-specified chain
-Mein-interface - indicates the name of the interface from which the packages come
-jjump - specifies the action if a packet matches the rule
-Theoutput interface  the interface name of an outbound package
-Pprotocol - any available protocol, such as SSH, TCP, UDP and FTP
-ssource - can be an address, host name or address etc.
Chaindescription
INPUTControls incoming packets
FORWARDSForwards packets that arrive at your server, but destined for another place
RESULTFilters packets leaving your server
Optiondescription
-ANadd  add one (or more) rules from the selected chain
check - checks a rule that matches the criteria in the selected chain
-Ddelete - deletes only one rule from the selected chain
-Fflush - excludes all defined iptables rules
-MEinsert - insert a rule in the selected chain
-MElist - displays the rules for the selected chain
-nnumeric - shows IP address / host name and return value in numeric format
-Nnew-chain - creates a new user-defined chain
-vdetailed - used in combination with -L to provide additional information
-Xdelete-chain - deletes the user-defined string

Conclusion, SSH security and protection best practices

Whether you are building a new server or a virtual machine, it is a good practice to implement multiple layers of security in your environment. Companies often like to set up their infrastructure as quickly as possible, but the necessary security measures must be in place from the start.

If you employ the Linux SSH security methods listed above, you can avoid common security threats in the cloud.

Make it difficult for hackers to penetrate the server (s) and restrict any damage. Be sure to implement as many of these best practices as possible before making your server available on the network.


Was this article helpful?

To maintain a quality standard for you, we have invested in a great hosting plan, Paid CDN, Website Optimization Plugins, etc ...

Help us to keep the project active! 

Follow the news in real time. Follow our Instagram profile.

Felipe Santos
Felipe Santos is a Cloud and Security Architect, with experience in Windows Server, Cluster, Storages, Backups Veeam and Office 365 environments.
en_USEnglish

UP TO 90% DISCOUNT

TAKE OFF YOUR CAREER !!

Do you want to upgrade your career? 

Invest in yourself and get ahead! Get that dream job in 2021!