RubyGreenBlue

Public Key Authentication with SSH

Posted by keith over 2 years ago

Here's how to setup public key authentication over ssh.

  1. Generate the keys

    First create a directory on your local machine ~.ssh/ if it is not already there.

    ssh-keygen -t dsa
    ssh-keygen -t rsa
    

    ssh-keygen will ask for the filename to save to. Just press ENTER to use the default values. It will then ask for a passphrase. A blank passphrase can be entered but this is obviously less secure and the same result can be achieved by using an ssh-agent.

    Private and public keys will then be generated. The public keys have a .pub extension.

    Your private keys should be kept private so you should make sure they are only readable by you (chmod 0600).

  2. Copy the Keys

    Now you should copy the public keys to each machine you will want to connect to. The contents of the public key needs to be appended to ~.ssh/authorized_keys on the remote machine. You could upload them using scp then login to the remote machine and append the contents but these commands can do all of that from your local machine:

    cat .ssh/id_dsa.pub | ssh username@newmachine "cat >> .ssh/authorized_keys"
    cat .ssh/id_rsa.pub | ssh username@newmachine "cat >> .ssh/authorized_keys"
    
  3. Configure the SSH daemon

    You need to make sure the SSH daemon (sshd) is configured to allow the use of public keys.

    cd /private/etc/
    sudo vi sshd_config
    

    Make sure the sshd_config file contains these options:

    PubkeyAuthentication yes
    AuthorizedKeysFile .ssh/authorized_keys
    
  4. Test it out:

    ssh username@host
    

    You will now be asked for you passphrase (not your password for the remote machine).

    To avoid having to type in the passphrase, setup an ssh-agent which will effectively do that for you each time you connect to a remote machine that knows about public keys. If you're on a Mac, SSHChain is an excellent utility.