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
SSH into your server as the root user. Open the configuration file:
nano -w /etc/ssh/sshd_config
Step 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 appvz
passwd appvz
Now the root login can be deactivated. Therefore the line PermitRootLogin in the SSH configuration file must be changed as follows:
PermitRootLogin no
Step 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 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 appvz
Step 4 - Change default port for SSH
Warning: By changing the SSH port, it may be necessary to change the firewall settings. This should be checked first.
See article: How to change the SSH port?
Step 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 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 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:
RHEL/Almalinux:
systemctl restart sshd
Debian/Ubuntu:
systemctl restart ssh