Monday, February 21, 2011

SSH and OSX

From http://www.stocksy.co.uk/articles/Mac/ssh_on_mac_os_x/

Passwordless logins with SSH

You can SSH without using a password by generating a private/public key pair. Bear with me! The public key resides on the computer you are connecting to (server) and is compared with your private key on the computer you are connecting from (client).

The keys could be generated anyway, but for this example we will be generating them on the client computer:

$ ssh-keygen -t dsa
Generating public/private dsa key pair.
Enter file in which to save the key (/Users/stocksy/.ssh/id_dsa):
Enter passphrase (empty for no passphrase): wxyz
Enter same passphrase again: wxyz

The ssh-keygen programme has just created two DSA (-t dsa specifies this) keys on your Mac. id_dsa is the private key and id_dsa.pub is the public key. You need to copy the public key, ~/.ssh/id_dsa.pub from the client to ~/.ssh/authorized_keys2 on the server using scp:

scp [source] [user]@[remote.host]:[destination]

For example:

iMac:~ stocksy$ scp ~/.ssh/id_dsa.pub james@194.11.2.81:~/.ssh/authorized_keys2

Important: Only ever copy the public key to other machines. The private key, as the name suggests must be kept secret, so only store it on computers you know are secure.

If you have several clients you want to connect to the server, you'll need to combine all the id_dsa.pub keys from each machine into one authorized_keys2 file. I would suggest that the best way to do this is to copy all the id_dsa.pub files into a temporary directory on the server, so that you have something like

Power-Mac:~/Desktop/ssh jamen$ ls
id_dsa.pub.1 id_dsa.2 id_dsa.3

Then, combine them like so:

Power-Mac:~/Desktop/ssh jamen$ cat id_dsa.pub.1 id_dsa.pub.2 id_dsa.pub.3 > authorized_keys2

cp authorized_keys2 ~/.ssh/authorized_keys2

Ok, you're ready to test your keys! Open a fresh terminal on your client and ssh to your server as above. It should ask you for the passphrase you provided for the key rather than the password of you account on the machine. The next step is to use SSHKeychain to hold this passphrase in the Apple Keychain.

Download SSHKeychain, mount the .dmg and drag sshkeychain to /Applications. Run SSHKeychain from the Finder and open its preferences. In the 'general' tab, set it to show in the Status Bar. In the 'security' tab, set 'On client connection' to 'Add keys to agent'. In the 'environment', tick 'Manage global environment variables'. From the menu bar Select 'Agent|Add All Keys'. Enter the passphrase you specified when you did ssh-keygen -t dsa and tick 'Add to keychain'.

Now, add /Applications/SSHKeychain to Login items in System Preferences -> Accounts.

Log out and back in to your account on the client, open a terminal and ssh to your server, it should not ask for a password!