The Secure Shell Protocol (or SSH) is a cryptographic network protocol that allows users to securely access a remote computer over an unsecured network.
Though SSH supports password-based authentication, it is generally recommended that you use SSH keys instead. SSH keys are a more secure method of logging into an SSH server, because they are not vulnerable to common brute-force password hacking attacks.
Generating an SSH key pair creates two long strings of characters: a public and a private key. You can place the public key on any server, and then connect to the server using an SSH client that has access to the private key.
When the public and private keys match up, the SSH server grants access without the need for a password. You can increase the security of your key pair even more by protecting the private key with an optional (but highly encouraged) passphrase.
Note: If you are looking for information about setting up SSH keys in your DigitalOcean account, please refer to our DigitalOcean product documentation on SSH Keys
The first step is to create a key pair on the client machine. This will likely be your local computer. Type the following command into your local command line:
OutputGenerating public/private ed25519 key pair.
You will see a confirmation that the key generation process has begun, and you will be prompted for some information, which we will discuss in the next step.
Note: if you are on an older system that does not support creating ed25519
key pairs, or the server you’re connecting to does not support them, you should create a strong rsa
keypair instead:
This changes the -t
“type” flag to rsa
, and adds the -b 4096
“bits” flag to create a 4096 bit key.
The first prompt from the ssh-keygen
command will ask you where to save the keys:
OutputEnter file in which to save the key (/home/sammy/.ssh/id_ed25519):
You can press ENTER
here to save the files to the default location in the .ssh
directory of your home directory.
Alternately, you can choose another file name or location by typing it after the prompt and hitting ENTER
.
The second and final prompt from ssh-keygen
will ask you to enter a passphrase:
OutputEnter passphrase (empty for no passphrase):
It’s up to you whether you want to use a passphrase, but it is strongly encouraged: the security of a key pair, no matter the encryption scheme, still depends on the fact that it is not accessible to anyone else.
Should a private key with no passphrase fall into an unauthorized user’s possession, they will be able to log in to any server you’ve configured with the associated public key.
The main downside to having a passphrase — typing it in — can be mitigated by using an ssh-agent
service, which will temporarily store your unlocked key and make it accessible to the SSH client. Many of these agents are integrated with your operating system’s native keychain, making the unlocking process even more seamless.
To recap, the entire key generation process looks like this:
OutputGenerating public/private ed25519 key pair.
Enter file in which to save the key (/home/sammy/.ssh/id_ed25519):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/sammy/.ssh/id_ed25519
Your public key has been saved in /home/sammy/.ssh/id_ed25519.pub
The key fingerprint is:
SHA256:EGx5HEXz7EqKigIxHHWKpCZItSj1Dy9Dqc5cYae+1zc sammy@hostname
The key's randomart image is:
+--[ED25519 256]--+
| o+o o.o.++ |
|=oo.+.+.o + |
|*+.oB.o. o |
|*. + B . . |
| o. = o S . . |
|.+ o o . o . |
|. + . ... . |
|. . o. . E |
| .. o. . . |
+----[SHA256]-----+
The public key is now located in /home/sammy/.ssh/id_ed25519.pub
. The private key is now located in /home/sammy/.ssh/id_ed25519
.
Once the key pair is generated, it’s time to place the public key on the server that you want to connect to.
You can copy the public key into the server’s authorized_keys
file with the ssh-copy-id
command. Make sure to replace the example username and address:
Once the command completes, you will be able to log into the server via SSH without being prompted for a password. However, if you set a passphrase when creating your SSH key, you will be asked to enter the passphrase at that time. This is your local ssh
client asking you to decrypt the private key, it is not the remote server asking for a password.
Once you have copied your SSH keys onto the server, you may want to completely prohibit password logins by configuring the SSH server to disable password-based authentication.
Warning: before you disable password-based authentication, be certain you can successfully log onto the server with your SSH key, and that there are no other users on the server using passwords to log in.
In order to disable password-based SSH authentication, open up the SSH configuration file. It is typically found at the following location:
This command will open up the file within the nano
text editor. Find the line in the file that includes PasswordAuthentication
(or create the line if it doesn’t exist), make sure it is not commented out with a #
at the beginning of the line, and change it to no
:
PasswordAuthentication no
Save and close the file when you are finished. In nano
, use CTRL+O
to save, hit ENTER
to confirm the filename, then CTRL+X
to exit.
Reload the sshd
service to put these changes into effect:
Before exiting your current SSH session, make a test connection in another terminal to verify you can still connect.
In this tutorial we created an SSH key pair, copied our public key to a server, and (optionally) disabled password-based authentication completely.
For more information about SSH and the SSH service, including how to set up multifactor authentication, please read our related tutorials:
We’ve made it super easy to add SSH Keys to your new or existing DigitalOcean virtual machines.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
If you don’t have ssh-copy-id you can use the following command: cat ~/.ssh/id_rsa.pub | ssh user@machine “cat >> ~/.ssh/authorized_keys”
Heya,
Yes this should also work, but I’ll still recommend using
ssh-copy-id
to copy the public key to the droplet.Regards
Hey Matt,
Great suggestion, we’ll update the article with that.
Dear Digital Ocean. You guys make the best tutorials. Thank you so much.
Great article, but what if your client is a Windows box and you’ve generated your public key with Puttygen, then need to transfer it to your VPS? Is there any way to copy-paste the public key, for example using nano? I’d rather not create a completely new server using the ‘Addendum’ method.
If you are copying the key over to a server you can certainly SSH and in and use nano/vi or any other editor and copy and paste it in. Just make sure that the formatting is preserved and no new line characters are added.
If I misunderstood the question let me know.
Wow, thanks for the quick reply on a Sunday night :-) I tried that and must have made a mistake as I couldn’t get it to work. I had created a way too large DSA key anyway. Since I’m trying to learn anyway, I’ve decided to recreate a droplet from scratch and get this down before I proceed. I’ll try integrating the SSH key through your ‘addendum’ method next time. I’m assuming I can just copy-paste the entire key, or do I have to omit lines like '---- BEGIN SSH2 PUBLIC KEY ---- Comment: “rsa-key-20130121”?
I think you may be looking at the wrong file possibly, because when the key is created the public one that you should be sharing doesn’t have any comments, so you can copy and paste it directly.
Please make sure that you are copying and pasting from the file that ends in “.pub”
I’m pretty sure I had the correct file, but to make sure I’ve put an exact copy/paste on Pastebin: http://pastebin.com/Hzi30uMM Apparently puttygen adds lines Linux doesn’t?
On Linux you would get : ssh-dss AAAAB3NzaC1yc2EAAAABJQAAAQEAgj… user@host
That should all be on one-line, the ssh-dss portion is because the key was created with dsa instead of rsa.
But thats what it should look like and you should paste it in on one line.
Right. Just to make sure I’ve got everything down correctly: if my username were ocean and my IP were 185.14.185.149, and my key were in ssh2-rsa the correct format would be:
ssh-rsa [key with all line breaks removed] ocean@185.14.185.149
Which I can then add to the Digital Ocean control panel and will be integrated in any future droplets I create.
Correct? Thanks!
When you create the key it will be created with your username@host the key was created on, it’s not related to the user / IP you are sshing to. It’s also optional and not necessary to be included.
Thanks for the clarification; puttygen does not add username@host data so I was under the impression I would have to manually add it. I’ll leave it out then.
If you open the private key with puttygen, there’s a box with the public key in openssh format http://i.imgur.com/1Cv0kmu.png
Copy and paste that into ~/.ssh/authorized_keys
Do the usernames on the client and server have to match? Or are there restrictions on logging into root@server from non-root@client?
Hey 👋
No, the usernames on the client and server do not have to match. You can log into
root@server
fromnon-root@client
by specifying the server username in your SSH command like this:Make sure your SSH key is authorized on the server for the user you’re trying to log in as.
I cannot finish step 3. I get blah blah blah port 22: Connection refused
I changed the port as recommended by a previous tutorial.
if you’ve changed your port then you need to give your port id in step 3. something like: cat ~/.ssh/id_rsa.pub | ssh -p yourportid user@123.45.56.78 “mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys”
This comment has been deleted
Heya,
If the ssh port is changed, then you need to specify the new port when you copy the public key over to the droplet.
You can also use the
ssh-copy-id
tool to handle the process for you.Where you need to change $PORT with the actual ssh port.
Regards
I tried this on my amazon ec2 virtual machine (running ubuntu 12.10 32-bit server), and on my desktop machine (running ubuntu 12.10 desktop 64-bit) and it does not work. I checked the dir and there is nothing there, and when trying the commands to transfer the key it tells me there were no identities found.
Okay it seems I was succesful this time, the only thing I did different is follow the tutorial. The first 2 times I entered a name for the file when asked for a name, and I also did use a password. I’m thinking it’s the former that made it not work, not sure why though. Anyhow…
When trying to connect, it asks me for a password and I did not enter one upon configuration. I guess I’m locked out of my virtual machine.
You can reset the root password for your droplet and then update the ssh configuration to accept only pubkey authentication.
https://docs.digitalocean.com/support/how-do-i-reset-my-droplets-root-password/
Hope that this helps!
Totally not working for me. I’m rebuilding my virtual machine for the second time.
Heya,
I’m sorry to hear about your experience. In case you’re locked from your droplet you can always use the recovery console to access the droplet and change the ssh configuration.
Also a root password reset is available if your key is not recognised for some reason and you do not have the root password.
Regards
Why enable root login over ssh at all? Add your normal admin user to the admin group, or add an entry to the /etc/sudoers file (as described in https://www.digitalocean.com/community/articles/how-to-add-and-delete-users-on-ubuntu-12-04-and-centos-6) and use sudo. If you need full root login, then just use sudo su - root
Heya,
All Linux-based machines come with a default root user that has all privileges on the machine; by default, you always act as a root user (a superuser).
It is considered a good security practise to disbale the root username and if anyone is interested into this can check our tutorial here:
https://www.digitalocean.com/community/tutorials/how-to-disable-root-login-on-ubuntu-20-04
Hope that this helps!
One thing to note if you are moving the pub key manually and creating the authorized_keys file is to make sure it has it’s permissions set to 700.
sudo chmod 700 ~/.ssh/authorized_keys
Question about the Addendum: if I include my public key, will the root user still have a password? If the answer is no, that means step 4 won’t make any difference, correct?
If you create the droplet with your SSH keys, the root user will not have a password. If you set the keys up later, the root user will have a password and step four would be helpful.
What are the advantages to uploading the public key to Digital Ocean’s Addendum?
Never mind. I found another tutorial.
On Cent6, I created the .ssh directory as a user and it wouldn’t work until I replicated the permissions of root’s .ssh directory (755) and authorized_keys file (644).
When i do this and locked me out of the server. Can you still access the server using the console of DigitalOcean within the control panel?
Remove the need for any editor.
$ sudo sed -ie “s/^PermitRootLogin without-password/#&/” /etc/ssh/sshd_config
Personally, I would also change PermitRootLogin yes appropriately.
If you have configured a different port for ssh(for example, port 54321), then you need to use this instead(with the quotes): ssh-copy-id “user@123.45.56.78 -p 54321” Can you please update the article?
@kamaln7 @etel Could you please update the article? I am sure I am not the only one spending a lot of time encountering issues like the one mentioned here. Please bear in mind when writing your tutorials that not all of us can connect the dots between various tutorials so easily.
We will look into updating this information in the article. Thanks for your feedback.
Regards
Heya,
Yes if the ssh port is custom the ssh-copy-id command needs to replicate that. I’ll look into updating this.
Regards
@Peter Oudenes: Yes. Our remote console does not rely on ssh and will work even if you’re locked out of ssh.
How about an option to disable root login upon creation of the droplet? And taking it further, the option to create a new user (e.g. ‘admin’), add it to sudoers and give it the public key instead?
It sure would save me some time!
@Jamie Schembri Please see the following articles:
https://www.digitalocean.com/community/articles/initial-server-setup-with-ubuntu-12-04 https://www.digitalocean.com/community/articles/initial-server-setup-with-centos-6 https://www.digitalocean.com/community/articles/initial-server-setup-with-arch-linux
Thanks @nicholas.teeple!
For CentOS 6, Instead of permissions 700 for ~/.ssh and 600 for ~/.ssh/authorized_keys…I had to set them to 755 and 644 respectively.
after i follow the tutorial and when i tried to ssh using terminal it show this “Agent admitted failure to sign using the key.” And they prompt me for password
Can anyone help?
@weeleetan Try running the ‘ssh-add’ command locally and then try to ssh in again.
Hello,
I’ve followed the instructions but I don’t get any reply from the server in step 3 when I add the public key. I use the ‘cat’ method because osx does not have ‘ssh-copy-id’
I’ve generated new keys and given another name to the files.
The copy of the public key seems to be ok though. I’ve checked authorized_keys on the server and it’s in there. But then, when I ssh root@myserver.com I’m prompted for the password.
Any idea?
@kevin.purnelle: What’s the output of the following command?
<pre>ssh -vvv user@yourdroplet</pre>
@Kamal Thanks to your comment I could solve the problem. The output was very long so I decided to look for an answer before posting.
Here I’m going to describe my steps as a SSH noob. I think it can be useful for any beginner like me.
So, after running the above command: ssh -vvv user@yourdroplet I saw something about identity files. When I created the key, I specified a different rsa filename for Digital Ocean. digitalo_rsa instead of the default one. (I use it for something else) -> There was no mention of it.
So after looking a little, I found two things.
One can select an identity file when calling ssh like this: ssh -i /path/to/key_rsa user@mydroplet (and it works, I wasn’t asked for password)
One can create a config file (well, it’s nicer that the command in 1) You have to go to your ~/.ssh folder and create a file named ‘config’ in there, you can add something like this:
Host example.com HostName example.com User root IdentityFile ~/.ssh/digitalo_rsa
You can add as many of these blocks as needed if you use various keys.
Then you can simply > ssh example.com ;)
main source: http://ivetetecedor.com/how-to-set-up-an-ssh-config-file-in-mac-os-x/
Heya,
I’m glad that you’ve sorted this! Thanks for sharing the information, I always feel proud of our community members when they want to share their knowledge to help others!
Regards
@kevin.purnelle: That is correct. Trust me, knowing how to look stuff up online can be really useful later on :D
Hi,
there should be an article that explains how to setup users + sudo + SSH key authentication and disable password authentication altogether + fail2ban + disable root login
Just to keep it simple for people who don’t really know what they are doing :)
This comment has been deleted
Heya,
All this steps are covered by couple of tutorials that can be found on our docs. I do believe that the process is fairly simple, but everyone can always ask here in the community if they face difficulties to complete any of the steps throughout the configuration.
Regards
@Julian: Re: users, sudo, SSH key auth, disabling root login; We have an article on that: https://www.digitalocean.com/community/articles/initial-server-setup-with-ubuntu-12-04 :]
As for fail2ban: https://www.digitalocean.com/community/articles/how-to-protect-ssh-with-fail2ban-on-ubuntu-12-04
You can disable password authentication by editing /etc/ssh/sshd_config and setting the PasswordAuthentication directive to ‘no’.
what should i do as i have forgot my passphrase.How to retrieve my old passphrase or how to remove the old one create a new key pair? I am in danger please help me.
@tanin.cs07: You can’t retrieve a key’s passphrase. The only options you have are:
Back up your current ssh key:
<pre>mv ~/.ssh/id_rsa ~/.ssh/id_rsa.bak rm ~/.ssh/id_rsa.pub</pre> Generate a new ssh key pair (this time, make sure you specify a passphrase you won’t forget):
<pre>ssh-keygen -t rsa</pre> Reset your droplet’s root password using our control panel, log in to your droplet through the console, set PermitRootLogin to yes (Step 4), restart ssh and run this command locally (on your computer):
<pre>ssh-copy-id root@droplet’sIP</pre> Then log back in to your droplet via SSH and redo Step 4 (set it to without-password and restart ssh).
You should now be able to access your droplet.
I’m using cygwin terminal to generate my public key but it returns a " -bash: ssh-keygen:? command not found " error please help
@gamesandgadgetz: Install the openssl cygwin package.
password using our control panel, log in to -" error please help,ssh-keygen:? access your droplet.
Reset your droplet’s root password using - my public key but it returns a " -mv ~/.ssh/id_rsa ~/.ssh/id_rsa.bak
: users, sudo, SSH key auth, disabling root login; We have an article on that: specified a different rsa filename for Digital Ocean. digitalo_rsa instead of the default one. (I use it for something else) -> There was no mention of it.Warning: Permanently added ‘12.34.56.78’
Thanks much for explaining in detail. I Was having idea about algorithms on public key and private key. When you explained conceptually on client and servers I got an overview about it in a very quick short of time.
Thanks again
@annanagy49: I’m not sure what you mean – can you please explain in one comment?
thanks
Create an alias like this: alias ssh-copy=“cat ~/.ssh/id_rsa.pub | ssh $1 ‘cat >> ~/.ssh/authorized_keys’”
use like this ssh-copy user@127.0.0.1
ssh-copy-id isn’t on OSX (ML) - but there’s a great article here: http://www.jacobtomlinson.co.uk/2013/01/24/ssh-copy-id-os-x/ which tells you how to install it….
Heyam
For anyone using Homebrew you can install it with:
https://formulae.brew.sh/formula/ssh-copy-id
Regards
I hav? done exactly as on tutorial, copied content of Public Key to authorised_keys nut I am still getting password prompt when I login via ssh. What is wrong?
@info: Is it authorised_keys or authorized_keys?
it is authorized_keys, sorry for mistake here. I got my root account working with SSH (with no password) but for my second user (not root) it does not work. How to make this work with my second user? Can I use the same public key?
@info: You can use the same public key, just make sure that the second authorized_keys is in /home/youruser/.ssh.
yes, i did that several times with no luck. I have put public key in user’s authorized_keys folder and still got prompt for password. There is nothing I can faint in logs related to auth failure…
I was trying to do this by adding an ssh key to an existing droplet. My first droplet had a password emailed to me. However after I added the key using cat .ssh/id_rsa.pub | ssh user@123.45.56.78 “cat >> ~/.ssh/authorized_keys” but I still get prompted for that original password?
This was on Windows using the github provided command line.
I decided to destroy the server and restart using the GUI.
Any help?
Oh I had to use ssh-add the key on the client.
cat .ssh/id_rsa.pub | ssh user@123.45.56.78 “cat >> ~/.ssh/authorized_keys”
should probably be changed to
cat ~/.ssh/id_rsa.pub | ssh user@123.45.56.78 “cat >> ~/.ssh/authorized_keys”
(added “~/” prefix to “.ssh/id_rsa.pub”)
@Dan: Updated. Thanks!
Just a note on Debian, reload isn’t recognized, had to use
sudo /etc/init.d/ssh restart
I tried copying the key and got the following error:
/home/user/.ssh/authorized_keys: Is a directory
How did that happen and what do I do?
@Ryan: Check if there are any files in it and if not you can safely remove it: <pre>sudo rm -r /home/user/.ssh/authorized_keys</pre> and then recreate it properly as a file.
assuming I have my keys set up, what do I use for user and host names in my SFTP client? (transmit) I have other ssh keys set up fine with transmit but can’t get this to work.
@tim: Simply enter the username that you added the SSH key to and your droplet’s IP as the host.
There is no help here for a Windows user for ssh login. Can y
@alikkalfizal,
What are you talking about, Willis? Check out <a href=“https://www.digitalocean.com/community/articles/how-to-create-ssh-keys-with-putty-to-connect-to-a-vps”>How To Create SSH Keys with PuTTY to Connect to a VPS | DigitalOcean</a>.
Couldn’t enable so I rebuilded it and did the following steps:
Everything works great.