How to Set Up Keys and Disable Password Login for ssh on your Raspberry Pi
If you want or need to be able to access and control your Raspberry Pi from outside your local area network (LAN), it’s a very good idea to disable password logins. This prevents hackers from being able to use/guess your password. In order to do this, we need to set up a public/private key pair and enable it for ssh login. This will make it almost impossible for a hacker to get into your Pi via ssh. The flip-side of that is the minor inconvenience of having to install your private key on any machine you want to log in with (but it’s not that big a deal really).
This has been done, based on a fresh install of Raspbian Wheezy 16 Aug 2012 edition, but will work on any version of Debian.
Ensure ssh is working.
We are going to be using ssh to do this process, so you need to ensure that ssh is working before we begin. Login to your Pi using your normal ssh procedure. Once logged in, you might as well stay logged in, as we will use the connection a little later on.
Create keys on your local computer, not on the Pi
You will need to use a program to generate a public/private key pair. The public key will be uploaded onto the Pi and you will use the private key on any computer (phone, tablet etc.) you wish to access it with. The private key must be kept private.
Many people rave about putty and puttygen. Putty is a very popular ssh client, and puttygen is the key generating part of putty. Here are instructions for generating a public private key pair with puttygen.
Creating keys with tunnelier
I use Bitvise Tunnelier, so here are instructions for how to create and export keys with tunnelier.
On the main screen click “user keypair manager”
Then click “generate new”
Then click generate, unless you want to add a passphrase, in which case type that in twice and then click generate. A passphrase is an extra layer of security if you want to use your private key on shared machines. Your key will not be usable without the passphrase. I find it unnecessary. Your needs may be different.
Your keypair will now be created for you and you will be returned to the previous screen.
Click on the key you just created and then click Export.
Choose Export public key and Open SSH, then click Export, type a filename e.g. publickeyopenssh.txt
Now we’re ready to start working on the Pi itself.
In the home directory of the user you’re logging in as (/home/pi in the case of the default pi user) you need to create a special directory called .ssh
This process is easier if you are logged in as the user you want to set up (as the owner of the files and directories we are about to create will automnatically be the correct one).
cd ~ (the ~ is important – this will take you to the home folder of the logged in user)
pwd (print working directory – shows you where you are in the file system)
mkdir .ssh (Make a directory called .ssh The . is very important)
cd .ssh (change directory – go to the .ssh directory)
nano authorized_keys (Open/Create a file and call it authorized_keys. Note the z – British spelling will not work in this case.)
You now need to copy and paste the contents of your public key file into this nano window. So open the exported public key file on the machine where you created it and copy it across into the nano window (right-click, paste works from windows). Then,
Enter (confirm file name)
ls -l (list the contents of the .ssh directory, view permissions and ownership)
chmod 700 ~/.ssh/ (set permissions for the .ssh directory)
chmod 600 ~/.ssh/authorized_keys (set permissions for your key file)
ls -l (check permissions were changed properly)…
Notice that before we changed the permissions of authorized_keys, they were…
-rw------- (r=read, w=write)
This is how it should be. We’ve just set the permissions so that nobody can read, write or execute your key file except pi (and super-users, like root).
Set up your ssh client to use your private key
In the latest Raspbian, (August 2012) public key ssh login is enabled by default, but so are passwords and there may be a couple of other things we want to change in the configuration file (like the port number).
So, at this point, you can already set up your ssh client (e.g. tunnelier or putty) to use your keys. In tunnelier, your keypair would have been allocated a slot number. Under initial method, choose public key – slot X, where X is the slot number you want.
Then, without logging out of your existing ssh session, try logging in using another instance of tunnelier, using port 22 and your public/private keypair. If this keyed login now works, it’s safe for you to disable password login (for ssh). Obviously, if you disable passwords before keys are working, you’ll lock yourself out from remote login :(
Edit the ssh config file /etc/ssh/sshd_config
sudo nano /etc/ssh/sshd_config
Somewhere in this file (usually on page 2 – CTRL+V for next page) should be a parameter
This needs to be uncommented (remove the #) and yes changed to no
You’ve now switched off ssh password logins – well nearly. We haven’t activated it yet. Before we do that, you might want to consider changing the port number as well…
Changing the ssh port number from the default 22
The world and his wife know that the default port number for ssh is port 22. It is a good idea to change the port to something non-standard and forward to that port from your router. You can also set up ssh to use more than one port, (e.g one for local “traffic” and another forwarded from external connections by your router).
Broadly speaking, you can choose any port number between 1 and 65535, but it’s worth checking on a list of commonly used ports to avoid messing something up.
If you want to change the port number, it’s near the top of the sshd_config file.
You can just change 22 to your chosen port number, or you can add a new line with your new port number in if you want to use more than one port.
Once you’ve done that, we need to save and exit the configuration file.
Enter (confirm file name)
If you’ve changed the port number, remember to change the port number on your ssh client as well, or you’ll be stuck wondering why you can’t login. :(
Restarting the ssh server
Your new ssh configuration settings won’t take effect until you restart the ssh server. You can either use this command…
sudo /etc/init.d/ssh restart
or you can reboot your Pi.
And from now on, you will only be able to ssh into your Pi using keys and you have enhanced your security enormously. :) Good job! May your data always be safe and secure. (Of course this does not affect the normal console login if you are using keyboard and screen connected directly to your RasPi.)
Set up port forwarding on your router
All that will work fine on your LAN, but if you want access from outside, you’ll then have to set up port forwarding on your router. What you will need to do is log into your router’s control panel and set it up so that when you try to log into a specified port on your router (e.g. port 777 if that’s what you set ssh to listen on) all such traffic is diverted to the local ip address and port number of the Raspberry Pi.
An example. If your internet connection’s ip address is 111.222.333.444 and your RasPi is on 192.168.0.45 and you set up ssh to listen on port 777, you would need to set up port forwarding so that whenever anyone tries to access 111.222.333.444:YYY it would forward all that traffic to local ip 192.168.0.45:777 On some routers you can set the incoming YYY to whatever you like. On others it must be the same as the 777.
There are so many different types of routers, I’m afraid I can’t offer help with that part of the setup, or be more specific. But once you’ve got port forwarding set up, you should be able to ssh in from outside. If your internet provider gives you a dynamic IP address, you will probably need to look into something called DDNS to keep track of your ever-changing internet connection’s IP address.
Hey thanks a lot of help reading this, I plan to ssh from outside my LAN to my pi for python practice. But… Why set permissions? I currently have default. :chic:
If you don’t set the permissions properly, it won’t work (properly or at all). It’s as simple as that. :)
Okey got it. I it all made more sense after changing the ownership (chown) and the keys worked.
[…] How to Set Up Keys and Disable Password Login for ssh on your Raspberry Pi […]
Hi I tried to follow your instructions but instead of the rw—- pi pi — i get root root. When I try and log in it does not accept my key. I amuseing the latest raspbian install and this is the first thing I am trying to do. All other screens come up the same (I have to type sudo though to create the dir and to make the authorized_keys file)
What do you think is going wrong? My login is the default login:pi pw:raspberry. Also when I first connect with putty it pops up that the key is not the same as the other keys… that I haven’t generated yet.
Thanks for your help if you have the time.
It looks as if you have created the directory using sudo, hence it is now owned by the root user root.
You should be able to change that using the chown command.
Did you do this from /home/pi originally? Or have you created a root user and are logging in as root?
The original cd ~ command at the top is to ensure that you start in /home/pi because pretty much anywhere else you will need sudo to create a directory and then you’ll run into the kind of problems you describe.
You might be able to get out of it with
sudo chown pi:pi .ssh
sudo chown pi:pi .ssh/authorized_keys
You might be able to get out of it with
sudo chown pi:pi .sshand
sudo chown pi:pi .ssh/authorized_keys
…or you could combine the two commands into a single command ;-)
sudo chown -R pi:pi .ssh(-R = recursive)
Another useful ‘chown’ tip (chown = CHange OWNer) is that instead of specifically specifying a user:group paring, you can leave off the group and just specify user: and it’ll then default to using the default group for that user (the default group is often the same as the username, but not always).
please i need to change my host ip to another ip on my computer, when i did it asked for a password which i dont know, i used the public key method for authentication but didnt work, please what can i do to achieve my aim so that i can use any host ip???
I’m afraid I’m not sure what you’re asking for, but I wonder if http://raspberryalphaomega.org.uk/2013/07/10/a-solution-to-multiple-raspberry-pi-ssh-key-woes/ is helpful?
Or could you provide more details / explanation?
One comment. If you already have a key pair, the line in “authorited keys” needs to start with “rsa ” before the key, otherwise the key will get refused. Also the key needs to be in one line with no line feeds… Otherwise great tutorial, also for beginners coming from windows…
[…] How to Set Up Keys and Disable Password Login for ssh on your … […]
I did this and it work. :D
Great guide! Thanks!
Hi! Maybe I am being a little thick but I have just downloaded Bitvise and for the life of me cannot find “user keypair manager” to click on. Where do I find this? Many thanks!
Never mind it is now under ‘Client key manager’.
THanks for the guide :D
Will this work for multiple pi connected to one host. Need ssh access to 15nos pi without password.
I just wanted to say thanks! Now I can use connectbot profiles to execute batch commands with a single tap.
Great guide, thanks.
After following the tutorial (and activating ssh on the pi, which is no longer active be default)
I can use windows the windows programs putty and WinSCP to connect to the pi.
Connecting from another pi with ssh @ -i -v
fails It connects, but endlessly asks for the passphrase of the private key.
It also complained about the key being visible to other users, which
I changed with the chmod command.
Any tip on how to ssh into a certificate protected pi from the linux terminal?
the commenting system ate half of the ssh command
I tried ssh username@ip_of_pi -i filename_private_key -v
Once you’ve setup the keys correctly, it should be as straight-forward as:
More info at https://www.raspberrypi.org/documentation/remote-access/ssh/passwordless.md and https://www.raspberrypi.org/documentation/configuration/security.md
Changing port number …
Axiom: the computer is not visible from outside, only the router.
One needs to forward a port on the router. IE: it is enough to forward port 777 on the router to port 22 on the computer. No need to change the ssh port on the computer. It is NOT visible from the outside …
Axiom: Obfuscation is NOT security!
One would leave all ports closed on the router, right?
So a simple port-scan will reveal the open ports: 80, 8080, some known game port, your idiotic non-standard port.
Guess what! The hacker will know EXACTLY what you are doing…
Not all routers allow you to do this. Some will only pass through the same port as the incoming port.
I’ll remember not to obfuscate my spare house keys under a rock but leave them in plain view instead right? Coz obfuscation is not security.
Also if obfuscation is not security, why do you feel more secure obfuscating your name?
But all of this misses the point, the main security step here is in using ssh keys and disabling passwords. I agree with you that anyone using the default password and opening ports to the world is extremely vulnerable and ignorant (perhaps not an idiot though, just doesn’t know better).
I agree that obfuscation alone is not good security, but that’s not the case here.
Security through obscurity (IE changing port numbers) will not prevent targeted attacks but it will prevent the millions of bots out there that go around attempting to log into port 22 on random IP addresses from banging on your door. I changed my servers from port 22 to a different port and the login attempts went from thousands per day to zero. I can now monitor the SSH and have my systems raise alerts if they see multiple attempts which was impossible before.
Changing the port number should not be used in isolation but as part of a combined security effort which includes using SSH keys as Alex described it is good practice – even if it’s just to stop your Pi being slowed down and your SD card being filled up with logs of invalid attempts.
With reference to leaving it on 22 and changing the port using the router, there’s a good reason for doing it that way. Having it on the same port both externally and internally means as long as you set up DNS correctly (so it identifies as the same hostname both inside and outside of your network) then you can add an entry in .ssh/config which automatically uses the correct port. You can then access your Pi no matter where you are with the same SSH command. This is particularly useful if you want to access files on it using SCP or SFTP as it means paths stay the same for your applications.
One other thing is that TCP ports can range from 0 to 65535 – ports below 1024 are defined as “well known ports”, so I suspect that most automated port-scanners probably just probe ports below 1024 for speed reasons? So picking some random port between 1024 and 65535 will probably result in even fewer SSH scans than picking the 777 example that Alex gives above.
Disclaimer: I’m not a security expert, always do your own research before listening to advice from random strangers on the internet ;-)
Technically the recommendation for SSH is you should use a port below 1024 as as they are also privileged ports. What that means is on UNIX systems you have to be root to use them (as opposed to ports above 1024 which any old process can use).
The theory goes if you use a port above 1024 a rogue process could replace your real SSH server on the port and then when you went to log in it could obtain your credentials and gain elevated privileges. I’m not sure how much of a risk there is of that happening in reality….
Disclaimer: Same as what AndrewS said! ;)
Good point Daniel – I guess I should have clarified that I was talking about using something above 1024 as the “external” port, which your router would then forward to the “internal” port 22 of your Pi. But if you have a rogue process running on your Pi that’s able to replace ports above 1024, you might have other things to worry about ;-)
Oh yeah definitely.
I was thinking about it though and in some situations its probably not that hard to do. Lets say you have WordPress running on your box and it gets hacked, I’m pretty sure you can open a port using PHP, so the attacker could add a couple of lines of code to WordPress and open a web page which generates the fake SSH port.
Logged onto No1 Pi successfully with Global 1; method public key.; Client key 1 and saved the profile as 1. Similarly logged into No 2 Pi with public key and client key as Global 2 and saved profile as 2. This works fine if I have to log in individually. Pl guide if I can log in to both Pi No 1 & 2 simultaneously with one click?
Hey there that is a very good tutorial. Although I wouldn’t consider myself a total beginner I’m always frustrated when people omit some of the most important parts because they think it’s common knowledge. This tutorial was very easy to read and helpful. Now I don’t need to be afraid anymore to open my ssh via port forwarding on the router thanks to my auth-key ;-)