Monday, 21 December 2009

SSH public key authentication

This procedure is to eliminate the use of passwords in ssh, ideal for scripts involving remote execution (server side)
1.-Generate the RSA & DSA keys:
This keys can be cyphered using 3DES, but we don't want to be asked for a passphrase instead of a password, so we're gona left the passphrase blank:

[root@nagios ~]# ssh-keygen -b 1024 -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx root@nagios
[root@nagios ~]# ssh-keygen -b 1024 -t dsa
Generating public/private dsa key pair.
Enter file in which to save the key (/root/.ssh/id_dsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_dsa.
Your public key has been saved in /root/.ssh/id_dsa.pub.
The key fingerprint is:
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx root@nagios

Because we don't use any passphrase, protect the keys is a MUST, so we need to change the permission to this files (located in ~/.ssh)

[root@nagios ~]# chmod 700 ~/.ssh

The private keys are id_dsa and id_rsa, the public keys have the same name, but ended with .pub.

2.-Server side configuration:
In order to allow the public key based authentication, we need to copy the public keys to the server, so with every login, the keys will be checked, and the access will be granted.

We will concatenate the public keys in a file:

[root@nagios ~]# cat ~/.ssh/id_dsa.pub ~/.ssh/id_rsa.pub > public_keys

Next, the keys must be copied to the remote machine:

[root@nagios ~]# scp -P1138 public_keys root@example.net:/root/.ssh/authorized_keys
root@example.net's password:
public_keys 100% 822 0.8KB/s 00:00

Now, we login to the remote machine to change some permissions:

[root@nagios ~]# ssh -l root remote-server.net -p1138
Last login: Mon Dec 21 11:38:10 2009 from 200.75.19.2
Linux server 2.6.24-16-server #1 SMP Thu Apr 10 13:58:00 UTC 2008 i686
root@remote-server:~# mkdir -p ~/.ssh
root@remote-server:~# chmod 700 ~/.ssh

Voila! The login don't ask for password nor passphrase! Let's play with remote execution!

No comments:

Post a Comment