Get Rewarded! We will reward you with up to €50 credit on your account for every tutorial that you write and we publish!

Securing the SSH service

profile picture
Author
Markus
Published
2019-04-30
Time to read
10 minutes reading time

Introduction

This article deals with securing the SSH service on Linux systems. The following points are explained in more detail:

  • Protection of the SSH service
  • certificate-based login
  • Two factor authentication

Prerequisites

  • SSH service based on OpenSSH

Step 1 - Securing the SSH service

This is mainly about customizing the OpenSSH configuration. All subsequent changes in the SSH configuration file refer to the following file: /etc/ssh/sshd_config

Step 1.1 - Deactivate the root login

Before turning off the root login, you should create an administrative user with which it is possible to gain root privileges.

To create such a user, it is necessary to execute the following commands on the system.

useradd -m -U -s /bin/bash -G sudo holu
passwd holu

Now the root login can be deactivated. Therefore the line PermitRootLogin in the SSH configuration file must be changed as follows:

PermitRootLogin no

Step 1.2 - Automatic session timeout

With this setting, a forced disconnection of the SSH connection is performed after a certain inactivity. The following settings are necessary in the SSH configuration file:

ClientAliveInterval 300
ClientAliveCountMax 1

ClientActiveInterval defines the maximum time the session can be inactive before it terminates. In this case, 300 seconds is 5 minutes. ClientAliveCountMax defines the number of checks to be performed before a disconnect.

Step 1.3 - Enable user for SSH

With this setting, only selected users are allowed to establish an SSH connection to the server. The following settings are required in the SSH configuration file:

AllowUsers holu holu2

Step 1.4 - Change default port for SSH

This setting changes the SSH port from 22.

Advantages: Bots and scanners scanning for SSH services on port 22 will not find the server and will not launch automated attacks against the server.

Disadvantages: The modified SSH port must be specified for each connection. Here you have the possibility to save the SSH connection. On Windows, for example with PuTTY, this is done via the interface. On Linux clients, the file ~/.ssh/config with the following content must be created.

Host <your_host>
    HostName <your_host>
    Port SELECTED_PORT

(Optional) The key can also be stored here later: IdentityFile ~/.ssh/id_rsa.

Warning: ** By changing the SSH port, it may be necessary to change the firewall settings. This should be checked first.

To apply the setting, the following changes must be made to the SSH configuration file: For security reasons it is recommended to select a port below 1024.

Port SELECTED_PORT

Step 1.5 - Automatic disconnection in case of incorrect login

After the specified number of failed login attempts, the SSH connection is automatically disconnected from the server. To apply the setting, the following changes are necessary in the SSH configuration file:

MaxAuthTries 2

Step 1.6 - Deactivate unused functions

To prevent unused functions from being exploited, they should be switched off. To apply the setting, the following changes in the SSH configuration file are necessary:

AllowTcpForwarding no                   # Disables port forwarding.
X11Forwarding no                        # Disables remote GUI view.
AllowAgentForwarding no                 # Disables the forwarding of the SSH login.
AuthorizedKeysFile .ssh/authorized_keys # The ".ssh/authorized_keys2" file should be removed.

Step 1.7 - Apply the settings

To activate the settings, it is necessary to restart the SSH service. Before you do this you should check the configuration for errors, this is done with this command:

sshd -t

If no errors were detected when checking the configuration, the SSH service can be restarted with the following command:

systemctl restart sshd

Step 2 - Setup of Fail2Ban

This software offers protection against so-called Brute force attacks.

The IP address of the user is blocked for a certain period of time after several incorrect passwords have been entered. This is to prevent the attacker from trying out a large password list in a short time.

To install Fail2Ban the following steps are necessary. Installing the software:

  • Ubuntu / Debian
    apt install fail2ban
    systemctl enable fail2ban
  • CentOS / RedHat
    yum install epel-release
    yum install fail2ban
    systemctl enable fail2ban
  • ArchLinux
    pacman -S fail2ban
    systemctl enable fail2ban
  • OpenSUSE / SLES
    zypper install fail2ban
    systemctl enable fail2ban
  • Fedora
    dnf install fail2ban
    systemctl enable fail2ban

Customizing the Fail2Ban configuration

Create the configuration using a template:

cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

In the file /etc/fail2ban/jail.local the following changes must be made:

In the [sshd] tab, enable must be set to true and the possibly changed SSH port must be specified.

enabled = true
port = SELECTED_SSH_PORT

Optionally, the values for:

  • bantime (The time in which no further logins are possible.)
  • findtime (The time in which the incorrect login attempts are to be counted. Starts from the first failed login.)
  • maxretry (The maximum possible number of failed attempts before a lock occurs.)

can be changed.

The following command is to adopt the changed configuration for this:

systemctl restart fail2ban

Step 3 - Certificate based authentication

This allows the user to log on to the server without a login password; only the password is required to protect the private key.

On the Client

  • Create the SSH key pair

    Linux / MacOS

    Create an SSH key pair with a bit length of 4096.

    ssh-keygen -b 4096

    Attention: For security reasons it is recommended to protect the key with a passphrase. This means that the key is not available in plain text, but is AES-CBC encrypted.

    Windows

    To generate an SSH key pair on Windows systems, either the WSL (Windows Subsystem for Linux) or the software PuTTYgen can be used.

  • Transfer the public SSH key to the server

    Linux / MacOS

    To transfer the public key to the server, the first step is to use the SSH connection using password authentication. The ssh-copy-id tool copies the corresponding identity file to the server:

    ssh-copy-id -i .ssh/id_rsa.pub -p <your_port> holu@<your_host>

    Windows

    On Windows systems, this step is done manually by copying the contents of the public key to the /home/holu/.ssh/authorized_keys file on the server. It is also possible that this file must be created first.

Testing the SSH connection with certificate-based authentication:

ssh -i .ssh/id_rsa -p <your_port> holu@<your_host>

On the Server

Note: After changing the following keywords to "no", it is no longer possible to log in with a password via SSH.

Keyword Description
PasswordAuthentication Specifies whether password authentication is allowed.
KbdInteractiveAuthentication Specifies whether to allow keyboard-interactive authentication.

"ChallengeResponseAuthentication" is a deprecated alias for "KbdInteractiveAuthentication".


If you wanted to disable all types of password authentication, you would need to set both keywords to "no". However, the next step explains how to setup two factor authentication and for this to work, you need ChallengeResponseAuthentication, or on new systems KbdInteractiveAuthentication, set to "yes".


You can now edit the SSH configuration file under /etc/ssh/sshd_config.

  • Disable password authentication
    To disable basic password authentication, the configuration needs to look like this:

    PasswordAuthentication no

    If you do not want to setup two factor authentication and you want to disable all types of password authentication, you can also set KbdInteractiveAuthentication to "no" (in older systems ChallengeResponseAuthentication).

    It is also possible to disable password authentication for a specific user. The entry for the SSH configuration file looks like this:

    Match User holu
        PasswordAuthentication no

  • Enable public key authentication
    You should double-check if PubkeyAuthentication is set to "yes" and make sure it is not commented out.
    PubkeyAuthentication yes

  • Adopt the changes
    To activate the settings, it is necessary to restart the SSH service. Before you do this you should check the configuration for errors, this is done with this command:
    sshd -t
    If no errors were detected when checking the configuration, the SSH service can be restarted with the following command:
    systemctl restart sshd

Step 4 - Two factor authentication

After a successful login, a one-time password is required before the login process is finished. This is done via the Google Authenticator.

Notice: To create the time-based one-time password (TOTP) a smartphone with one of the listed apps is required.

Installing the Google Authenticator

  • Ubuntu / Debian
    apt install libpam-google-authenticator
  • CentOS / RedHat
    yum install epel-release
    yum install google-authenticator
  • ArchLinux
    pacman -S libpam-google-authenticator
  • openSUSE / SLES
    zypper install google-authenticator-libpam

Configuration of the Google Authenticator

After the PAM module has been installed, it can be initialized and configured as shown below.

Starting the Google Authenticator:

google-authenticator
  1. Do you want authentication tokens to be time-based (y/n)

y, it creates TOTP tokens (time-based one-time passwords) n, it creates HOTP tokens (counter-based one-time passwords)

  1. a QR code is now displayed on the SSH console

Scan this code with a compatible app on your smartphone.

  1. copy and store the keys listed below securely.

With the emergency scratch codes you can log in without OTP. Update the file .google_authenticator with this information. Type y.

  1. confirm all other questions with y, or with n if you want different settings.

Integration into the SSH logon

The Google Authenticator PAM module is configured ready, now services like the SSH daemon can be customized to allow 2-factor authentication over it.

  • Adjustments in /etc/pam.d/sshd

    Here the time @include common-auth must be commented out with a # at the beginning of the line. Then the line auth required pam_google_authenticator.so is inserted.

  • Adaptations in /etc/ssh/sshd_config

    In the configuration file the ChallengeResponseAuthentication can now be set to yes.

    ChallengeResponseAuthentication yes

    Ubuntu 22.04 and newer versions need to adjust this flag instead:

    KbdInteractiveAuthentication yes

    Also the entries UsePAM and AuthenticationMethods should be checked. The entry UsePAM should be set to yes and AuthenticationMethods should look like this:

    AuthenticationMethods publickey,keyboard-interactive
  • Restart the SSH service

    systemctl restart sshd

After that the setup of the Two Factor Authentication is complete.

Conclusion

This article describes several ways to secure the SSH service on Linux systems.

License: MIT
Want to contribute?

Get Rewarded: Get up to €50 in credit! Be a part of the community and contribute. Do it for the money. Do it for the bragging rights. And do it to teach others!

Report Issue
Try Hetzner Cloud

Get 20€ free credit!

Valid until: 31 December 2024 Valid for: 3 months and only for new customers
Get started
Want to contribute?

Get Rewarded: Get up to €50 credit on your account for every tutorial you write and we publish!

Find out more