Securing an SSH Server (Basic)

Setting secure SSH on a Server


In this guide we are going to create a new user with an ssh key and lock out the root user from ssh.

You can also enable sudo for this new user and prevent ANY root login if you wish

This should be one of the first things done on any new server.


1 Login to your server



ssh root@<ip>


2 Create a user



adduser -m exampleuser
passwd exampleuser
Changing password for user exampleuser.
New password:
Retype new password:
passwd: all authentication tokens updated successfully.


Exit the ssh session after this, you need to create the keypair on your local machine

3 Create an ssh keypair



ssh-keygen -t ed25519 -C "exampleuser"
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /your_home/.ssh/id_rsa.
Your public key has been saved in /your_home/.ssh/id_rsa.pub.
The key fingerprint is:
a9:49:2e:2a:5e:33:3e:a9:de:4e:77:11:58:b6:90:26 exampleuser
The key's randomart image is:
+--[ RSA 2048]----+
|     ..o         |
|   E o= .        |
|    o. o         |
|        ..       |
|      ..S        |
|     o o.        |
|   =o.+.         |
|. =++..          |
|o=++.            |
+-----------------+


4 Copy this key to your server



ssh-copy-id -i ~/.ssh/id_ed25519.pub exampleuser@<IP>
The authenticity of host '<IP> (<Host>)' can't be established.
ECDSA key fingerprint is fd:fd:d4:f9:77:fe:73:84:e1:55:00:ad:d6:6d:22:fe.
Are you sure you want to continue connecting (yes/no)? yes
exampleuser@<IP>'s password:

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh ‘exampleuser@<IP>’"
and check to make sure that only the key(s) you wanted were added.


5 Remove Password based login



nano /etc/ssh/sshd_config

...
PasswordAuthentication no #find these two lines and edit them to show ‘no’
PermitRootLogin no
...


6 Restart the ssh daemon



systemctl restart ssh


To test that the above steps have worked, try exampleuser@<ip> and root@<ip>

exampleuser should be able to login without a password, root should be denied even with a valid password.

7 Enable sudo access



ssh exampleuser@<ip> #login to the server
su - #provide the root password when requested
apt update sudo
usermod -aG sudo exampleuser
getent group sudo  #verify the user was added


You can now prefix commands with ‘sudo’ when logged in as exampleuser

8 Disable root (even with su)



sudo usermod --shell /bin/nologin root