SSH communication has some security issues. To avoid them, you shoud do following two things.
Key Authentication
SSH login with password authentication is vulnerable to external attacks. So you should use key authentication to login with ssh to your server.
Generate a keyfile(on local PC)
To generate a keyfile, you can use “ssh-keygen” command on your local PC.
$ ssh-keygen -t rsa -b 4096
Copy the keyfile to the server
Copy the keyfile to your Raspberry Pi server by “ssh-copy-id” command.
$ ssh-copy-id -i ~/.ssh/id_rsa.pub user@192.168.10.109
Notice: The user name and IP address should be replaced by your user name and servers IP address.
Login with key authentication
To login with key authentication, use “-i” option to ssh command.
$ ssh user@192.168.10.109 -i ~/.ssh/id_rsa
Disable password authentication
If you can login the server with key authentication, you should disable password authentication. Edit /etc/ssh/sshd_config file.(NOT ssh_config file.)
$ sudo vi /etc/ssh/sshd_config
In this file, edit the following line, “yes” to “no”.
PasswordAuthentication no
Restart sshd service
$ sudo systemctl restart sshd
Login
$ ssh user@192.168.10.109 -i ~/.ssh/id_rsa
Change SSH port number
Original ssh port number is fixed to 22 and this is widely known. So this should be a security risk. So you should change the port number of SSH connections.
Configure firewall
Now I changed SSH port number 22 to 80022.
$ sudo ufw allow 80022
$ sudo ufw reload
Configure SSH service
Edit /etc/ssh/sshd_config file.(NOT ssh_config file.)
$ vi /etc/ssh/sshd_config
Edit the following line, “22” to “80022”
Port 80022
Restart sshd service
$ sudo systemctl restart sshd
Login
To login with another port number, use “-p” option to ssh command. You can use the combination of key authentication and port change, this will make ssh connections so much secure.
$ ssh user@192.168.10.109 -i ~/.ssh/id_rsa -p 80022
Close default SSH port
Now you can close default SSH port(port 22).
All the rules on UFW are displayed by following command.
$ sudo ufw status numbered
Delete rules of Port 22 from UFW.
$ sudo ufw delete <<RULE NUMBER OF PORT 22>>
$ sudo ufw reload
SSH connection config file
You would be lazy to type like a long ssh command every time to login. There is a short hand to do this.
On local PC, create a file ~/.ssh/config like following.
Host raspberrypi
HostName 192.168.10.109
User user
IdentityFile ~/.ssh/id_rsa
Port 80022
Now you can connect to the server by the following simple command.
$ ssh raspberrypi
Last Updated on January 25, 2025 by Kenn
Leave a Reply