November 24, 2013

Securing SSH with Public/Private Key Authentication

The motive for using public/private key authentication are:

  1. Firstly for convinience, you no longer need to enter password (unless you encrypt your keys with password protected).
  2. Secondly, ones setup, you can remove password protection, which is a big cracking hole.

Prerequisite

The remote user needs to exist on the remote server. If it does not. Create it. And at least LOGIN ONES, so that it's home directory is created. Otherwise you can eagerly created the home directory when you add the user.

Here I will use the existing user root, for simplicity.

Client Side

Generate public and private keys, with NO password protection. I will here use the RSA algorithm and key length 2048 bits.

$ ssh-keygen -b 2048 -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/magnus/.ssh/id_rsa): <Enter>
Enter passphrase (empty for no passphrase): <Enter>
Enter same passphrase again: <Enter>
Your identification has been saved in /home/magnus/.ssh/id_rsa.
Your public key has been saved in /home/magnus/.ssh/id_rsa.pub.
The key fingerprint is:
90:da:b5:5a:db:59:be:34:04:6a:99:81:c3:d5:5d:25 magnus@tester1.example.com
The key's randomart image is:
+--[ RSA 2048]----+
|        .. . .E..|
|     . +  . .  . |
|      * o .      |
|     o + * .     |
|    . . S   o    |
|       + o =     |
|      . . o +    |
|           . o   |
|            .    |
+-----------------+

Next make sure that the ssh key directory and private key has proper file permission

$ chmod 700 ~/.ssh
$ chmod 600 ~/.ssh/id_rsa

The last step is to copy the client public key to the server. You can either do that manually, or with the ssh-copy-id tool. Here I will use the tool.

$ ssh-copy-id -i ~/.ssh/id_rsa.pub root@remoteserver

If you were setting up public/private key authentication for a different user, please replace root in above command with you user.

Server Side

On the server side, open /etc/ssh/sshd_config and enable public/private key authentication

PubkeyAuthentication yes

Then restart the ssh daemon service.

$ service sshd restart

And finally verify that the keys directory and files have the proper file permission and SELinux type for your user.

$ chmod 700 ~/.ssh
$ chmod 600 ~/.ssh/id_rsa

$ restorecon -Rv ~/.ssh

Test

Finally you need to test, to verify the installation. On the client machine switch to the user you had setup for and

$ ssh <your_user>@remoteserver

No comments: