If you expose your Pi's SSH service to the web, you should seriously consider the security implications.
It is common for people to run mass port scans looking for open SSH ports and then run brute-force attacks against these ports hoping to crack the password and gain access to the system.
Follow this guide for a secure SSH setup.
Key-based authentication works by only allowing people to log into your Pi who have a specific SSH key. You make a whitelist of certain computers which can log into the Pi via SSH - nobody can log in unless they have been manually added to this list and possess the correct key. Thus, you can disable password logins entirely, compeltely negating brute-force password attacks.
First, create an SSH key on the computer you want to be able to connect to the Pi from (e.g. your laptop):
ssh-keygen
Follow the instructions presented on screen. Note that it is recommended to set a password during this step in case someone manages to steal your SSH key from your computer.
Your 2 keys (public and private) will be stored in ~/.ssh
. Make sure to never reveal your private key.
Next, you will have to copy your public key over to your Pi:
cat ~/.ssh/id_rsa.pub
Copy the string starting with ssh-rsa ...
and move it over to your Pi. (We will assume that you have copied it to your clipboard and are now about to log into the Pi via SSH).
After logging into the Pi, simply run the following two commandsd (where PUBLIC_KEY
is the string you copied):
mkdir -p ~/.ssh
echo "PUBLIC_KEY" >> ~/.ssh/authorized_keys
Now, edit /etc/ssh/sshd_config
to enable key-based authentication, disable password authentication, and secure our setup. Change the following lines (uncomment them if are commented out):
PasswordAuthentication no
ChallengeResponseAuthentication no
UsePAM no
Make sure to also require your password whenever using sudo
:
sudo nano /etc/sudoers.d/010_pi-nopasswd
And change this line to:
pi ALL=(ALL) PASSWD: ALL
Finally, restart the Pi to commit all the changes:
sudo reboot
Most automated SSH attacks first check if your home IP address has port 22
open (default SSH port). There are 65,535 ports in total, meaning that choosing one between 49152
and 65535
makes it impractical for someone to scan for, further strengthening our setup.
Steps will vary depending on your ISP and router, however, the basic premise is that you need to log into your router (typically located at 192.168.1.1
) and change the external port for your SSH port.
After you have logged into your router, set the outward-facing port to an arbitrary number between 49152
and 65535
and the internal port number to 22
, making sure to direct the internal IP address towards that of your Pi and save the settings.
That's it, however you must now specify this arbitrarty port before login by using the following command (where 49152
is the outward port you set):
ssh pi@IP_ADDRESS -p 49152