SSH Key-based Authentication on Ubuntu

Wasin Thonkaew - Dec 21, 2016

What Catches Me On

I still remember the very first time I log in to DigitalOcean server. I don't have to enter password.
At first, it feels something fishy going on behind the scene. I thought why they do something like this, the security is not on par.

That was because I don't have much experience on key-based authentication just yet. But later I found out that actually that kind of set up is highly secured.

The concept is you map the client to target server via public-private key pair of RSA. This means only a particular client can connect to server.
By doing this, we disable normal SSH login with password. This increases security at the same time.

Steps

On client system, execute ssh-keygen -t rsa to generate key. The key will be located at ~/.ssh/.

Copy public key from clien system to target server by ssh-copy-id root@target-host.com; assume that target-host.com is your server's domain name. This command will copy public key to target server under specified username's directory.

Now on client system, you can try log in via ssh root@target-host.com. It will prompt for passphase (if you enter it during step 1.).

(optional) If you don't want to enter passphase every time, you can use keychain to solve the problem by following the steps as below.

Execute sudo apt-get install keychain to install keychain

Execute keychain id_rsa

Execute
shell
. ~/.keychain/`uname -n`-sh
You shoul add the last two commands into ~/.bashrc. So that it will take effect every time you log in and even rebooting.

Updated

More information on how to do this.

You have an option to do it manually by inspecting a system ~/.ssh/id_rsa.pub that will be logging in to remote server then appending such line into remote server's ~/.ssh/authorized_key. That's basically what ssh-copy-id does the job.

If there's no ~/.ssh/id_rsa.pub does not yet exist yet, then create it with ssh-keygen -t rsa -b 4096 which has better security in which it uses 4096 bit instead of default 2048.

I blog about projects I'm working on. Mostly about mobile games, tech, web service, little tiny things I built for myself or for public, and tech/game industry-wide. Currently I'm living in Shenzhen, China. I'm running a small creative company with my girlfriend here.