SSH setup and configuration on VPS
In this article, the setup of the SSH server on my vps is presented. The setup is aimed for high security and this setup should be valid for other types of server as well.
Pre-configuration
It is more secure to login to the VPS as a non-root user with SSH key
instead of the password. So we choose to create a user yue
with the following command:
1 | adduser --disabled-password yue |
To be able to use sudo, we need to add the following line to the sudo configuration file:
1 | yue ALL = (ALL) NOPASSWD: ALL |
SSH server configuration
We change the the SSH configuration file
/etc/ssh/sshd_config
to the following form:
1 | Protocol 2 |
Here:
Protocol 2
ensures that the server only accepts connections via secure protocol version 2Port 11451
changes the port SSH connects to. Changing the port does not increase security, but we can bypass most automated login attempts as they usually only use the default portPermitRootLogin no
prohibits login as root via SSHPasswordAuthentication no
forbids login with passwords. The login with a public key is more secure than the login with passwordsPubkeyAuthentication yes
enables authentication using SSH key pairsStrictModes yet
prevents the SSH server from starting if certain files have too loose permissions. A lot of weird bugs pop up because of this optionAllowUsers yue
provides a whitelist for all users who are allowed to log in via SSH
To activate this configuration, we need to restarting the SSH server:
1 | systemctl restart sshd |
Creating an SSH key pair
On the client machine, an SSH key pair can be created by the following command:
1 | ssh-keygen \ |
If you created your key with a different name, or if you are adding an existing key that has a different name, you can run the following command to add your SSH private key to the SSH-agent
1 | ssh-add ~/.ssh/your_private_key |
Depositing the public key
On the server, run:
1 | mkdir -p /home/yue/.ssh |
The permission of these files and folders needs to be set to a specific level so that OpenSSH shall work and the security is not compromised. The permission should be set with command similar to the following ones on BOTH the client side and the server side:
1 | chown -R yue:yue /home/yue/ |
To avoid this cumbersome and error prune way of copying the public
key, we can use ssh-copy-id
(I haven't tested this
method)
Login
The SSH server needs to be activated with the new configuration on the VPS:
1 | systemctl restart sshd |
Now we can login to the VPS with the following command:
1 | ssh -p 11451 yue@<vps_ip> |
Copy file from the client to the server with SCP
We can use SCP to upload files to the server by following command:
1 | scp -P 11451 -r ~/folder_to_be_uploaded/* yue@<vps_ip>:/destination_directory/ |
Setup the firewall
To further increase the security, we can add a firewall the VPS by the following command. The firewall will block all incoming connections that were not explicitly allowed
1 | sudo apt install ufw |