RasPi.TV

Raspberry Pi, Electronics & Making
  • Home
  • Site Map
  • Shop
  • Downloads
  • I²C
  • raspberry pi
  • Linux usage
  • Python prog.
  • Input & Output

How to Set Up Keys and Disable Password Login for ssh on your Raspberry Pi

 Linux usage, raspberry pi  Add comments
Sep 182012
 

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”

keypair manager

Then click “generate new”

generate keypair

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.

generate keys


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.)

making the files/directories for the keys

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,
CTRL+O (save)
Enter (confirm file name)
CTRL+X (Exit)

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)…

checking permission changes

Notice that before we changed the permissions of authorized_keys, they were…
-rw-r--r--
afterwards…
-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
#PasswordAuthentication yes

This needs to be uncommented (remove the #) and yes changed to no
PasswordAuthentication 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.
Port 22

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.
Port 777

Once you’ve done that, we need to save and exit the configuration file.
CTRL+O (save)
Enter (confirm file name)
CTRL+X (Exit)

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.

sudo reboot

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.

 Posted by alex at 9:07 am  Tagged with: disable password login for ssh, login to raspberry pi using keys not passwords, ssh keys raspberry pi, use keys for ssh login on raspberry pi

  31 Responses to “How to Set Up Keys and Disable Password Login for ssh on your Raspberry Pi”

  1. Daniel says:
    November 5, 2012 at 11:53 pm

    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:

    Reply
    • alex says:
      November 6, 2012 at 8:15 am

      If you don’t set the permissions properly, it won’t work (properly or at all). It’s as simple as that. :)

      Reply
  2. Daniel says:
    November 30, 2012 at 7:31 pm

    Okey got it. I it all made more sense after changing the ownership (chown) and the keys worked.

    Reply
  3. See how to Set Up Keys and Disable Password Login for ssh on your Raspberry Pi « Frustrated IT Engineer says:
    February 2, 2013 at 12:58 pm

    […] How to Set Up Keys and Disable Password Login for ssh on your Raspberry Pi […]

  4. simon says:
    June 10, 2013 at 11:05 am

    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.

    Reply
    • alex says:
      June 10, 2013 at 11:37 am

      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
      and sudo chown pi:pi .ssh/authorized_keys

      Reply
      • AndrewS says:
        June 11, 2013 at 1:04 am

        You might be able to get out of it with sudo chown pi:pi .ssh and 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).

        Reply
  5. sgizzy says:
    August 20, 2013 at 10:20 pm

    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???

    Reply
    • AndrewS says:
      August 20, 2013 at 11:19 pm

      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?

      Reply
  6. dajolt says:
    February 16, 2014 at 10:30 am

    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…

    Reply
  7. how to login to raspberry pi ssh says:
    September 10, 2014 at 12:59 pm

    […] How to Set Up Keys and Disable Password Login for ssh on your … […]

  8. Shovels says:
    February 28, 2015 at 2:15 am

    I did this and it work. :D

    Reply
  9. Daniel Skogly says:
    March 11, 2015 at 4:01 pm

    Great guide! Thanks!

    Reply
  10. smartroad says:
    March 5, 2016 at 9:36 am

    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!

    Reply
    • smartroad says:
      March 5, 2016 at 9:53 am

      Never mind it is now under ‘Client key manager’.

      THanks for the guide :D

      Reply
  11. Alka Nagory says:
    May 10, 2016 at 12:11 pm

    Will this work for multiple pi connected to one host. Need ssh access to 15nos pi without password.

    Reply
    • alex says:
      May 10, 2016 at 2:55 pm

      yes

      Reply
  12. nub says:
    June 8, 2017 at 12:48 am

    I just wanted to say thanks! Now I can use connectbot profiles to execute batch commands with a single tap.

    Reply
  13. chimsa says:
    June 23, 2017 at 1:27 pm

    Great guide, thanks.

    Reply
  14. Jolt says:
    July 3, 2017 at 10:46 am

    Hi,

    two comments:

    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?

    Reply
    • Jolt says:
      July 3, 2017 at 10:48 am

      the commenting system ate half of the ssh command

      I tried ssh username@ip_of_pi -i filename_private_key -v

      Reply
    • Andrew Scheller says:
      July 3, 2017 at 2:20 pm

      Once you’ve setup the keys correctly, it should be as straight-forward as:
      ssh username@ip_address

      More info at https://www.raspberrypi.org/documentation/remote-access/ssh/passwordless.md and https://www.raspberrypi.org/documentation/configuration/security.md

      Reply
  15. Not an Expert says:
    October 20, 2017 at 4:57 am

    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?
    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…

    Reply
    • alex says:
      October 20, 2017 at 7:48 am

      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.

      Reply
    • Daniel Bull says:
      October 20, 2017 at 8:59 am

      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.

      Reply
      • AndrewS says:
        October 20, 2017 at 11:48 am

        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 ;-)

        Reply
        • Daniel Bull says:
          October 20, 2017 at 12:11 pm

          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! ;)

          Reply
          • AndrewS says:
            October 23, 2017 at 1:00 pm

            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 ;-)

            Reply
          • Daniel Bull says:
            October 23, 2017 at 1:09 pm

            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.

            Reply
  16. Alka Nagory says:
    February 12, 2018 at 10:06 am

    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?

    Reply
  17. Felix says:
    October 27, 2018 at 11:23 pm

    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 ;-)

    Reply

Leave a Reply to Daniel Skogly Cancel reply

  Play a DVD on Raspberry Pi with Raspbian, omxplayer and the MPEG2 codec   Watch encrypted DVD on Raspberry Pi by streaming to omxplayer
RasPi.TV Site Map - click here

Follow Me

RSS Twitter YouTube

NEW Product

NEW RasPiO® Breadboard Pi Bridge New RasPiO Breadboard Pi Bridge

Pi Ports to Breadboard in Numerical Order

Products Designed by Alex

RasPiO® Night Light - great gift idea! New RasPiO Night Light RasPiO® Analog Zero - Read sensors, make a weather station, thermometer or voltmeter RasPiO Analog Zero

Recent Posts

  • Back up your Garmin activity data on a Raspberry Pi
  • How much power does the Pi4B use? Power Measurements
  • Raspberry Pi 4 launches with BCM2711 quad-core Cortex-A72 64-bit SoC running at 1.5GHz with dual 4K display capability
  • Development of a new product – RasPiO Breadboard Pi Bridge (BBPi)
  • Making a fairly simple bike dashcam with Raspberry Pi – “Live project blog” pt5 Road Testing

Recent Comments

  • Dirk Broer on New Raspberry Pi Family Photo including Pi3A+ plus Zero WH
  • Dirk Broer on New Raspberry Pi Family Photo including Pi3A+ plus Zero WH
  • Peter Capon on Ethernet On Pi Zero – How To Put An Ethernet Port On Your Pi
  • Giles on How to drive a 7 segment display directly on Raspberry Pi in Python
  • Ben on Review of ISO-TECH IDM99III Digital Multimeter
Tweets by @RasPiTV

Categories

  • Electronics
  • Gertboard
  • get_iplayer
  • Input and Output
  • interfacing
  • Laser Cutting
  • Linux usage
  • Mailbag
  • Making
  • Product Launch
  • python programming
  • raspberry pi
  • Raspberry Pi Camera
  • Raspberry Pi Hardware
  • raspberry pihardware
  • RasPiO Duino
  • Review
  • software installation
  • Uncategorized
  • Wemos

Blogroll

  • Makersify
  • Oxford Raspberry Jam
  • Raspberry Pi Foundation
  • Raspberry Pi Spy
  • Raspberry PiPod
  • Robotics and Add-ons
  • See – Adafruit Industries

Archives

  • July 2020
  • June 2019
  • March 2019
  • December 2018
  • July 2018
  • June 2018
  • May 2018
  • March 2018
  • February 2018
  • January 2018
  • November 2017
  • October 2017
  • September 2017
  • July 2017
  • June 2017
  • May 2017
  • March 2017
  • February 2017
  • January 2017
  • December 2016
  • November 2016
  • October 2016
  • September 2016
  • August 2016
  • July 2016
  • June 2016
  • May 2016
  • April 2016
  • March 2016
  • February 2016
  • January 2016
  • December 2015
  • November 2015
  • October 2015
  • September 2015
  • August 2015
  • July 2015
  • June 2015
  • May 2015
  • April 2015
  • March 2015
  • February 2015
  • January 2015
  • December 2014
  • November 2014
  • October 2014
  • September 2014
  • August 2014
  • July 2014
  • June 2014
  • May 2014
  • April 2014
  • March 2014
  • February 2014
  • January 2014
  • December 2013
  • November 2013
  • October 2013
  • September 2013
  • August 2013
  • July 2013
  • June 2013
  • May 2013
  • April 2013
  • March 2013
  • February 2013
  • January 2013
  • December 2012
  • November 2012
  • October 2012
  • September 2012
  • August 2012
  • July 2012
  • June 2012

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org

Stats since June 2012

blog posts: 305
word count: 210,404
© 2012-19 RasPi.TV Site Map | Reviews Policy Suffusion theme by Sayontan Sinha