Wednesday, September 23, 2015

Setup SSH Keys

If you use ssh to connect to remote hosts, entering a password every time is a bit tedious, not to mention a bit less secure. A better approach is to setup SSH keys between machines so that they exchange an encrypted identity. One benefit is that you no longer have to provide credentials.

Create the SSH keys on the local host and the remote host.


ssh-keygen -t rsa -b 2048

This command says create a 2048-bit, RSA key. When prompted to, "Enter file in which to save the key," create the file with the name of the host rather than the default id_rsa. When prompted for a passphrase, leave it blank. If you choose, you can provide a passphrase, but then you'll be prompted to enter it every time you ssh to the remote host.

Generating public/private rsa key pair.
Enter file in which to save the key (/Users/bwallen/.ssh/id_rsa): /Users/bwallen/.ssh/myHost
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /Users/bwallen/.ssh/myHost.
Your public key has been saved in /Users/bwallen/.ssh/myHost.pub.
The key fingerprint is:
e3:9e:9e:7d:d2:3d:fb:74:24:2d:34:1a:c5:34:62:fa bwallen@myHost.local
The key's randomart image is:
+--[ RSA 2048]----+
|            oo+  |
|           o o.. |
|          . . o  |
|           . + o |
|        S   E o o|
|       . .     + |
|        .  . .  o|
|       . +. o o..|
|       .= .o  .+.|

+-----------------+

Copy the local host public key to the remote host authorized_keys file.


ssh-copy-id -i myHost.pub user@remoteHost

or 


cat /Users/bwallen/.ssh/myHost.pub | ssh user@remoteHost "cat >> ~/.ssh/authorized_keys"

Now, when you ssh to the remote host, you should not be prompted for a credential or passphrase. If you run into problems, there are few things to check.

Ensure that ssh on the local host is using the correct identity file.

less /Users/bwallen/.ssh/config.sftp

Host 192.168.43.76
Port 7522
PasswordAuthentication no
User MFT_AD
IdentityFile /Users/bwallen/.ssh/myHost

The IdentifyFile should point to the local host's private key, not the public key.

Add the private key identities to the authentication agent on the local host.

ssh-add /Users/bwallen/.ssh/myHost

Identity added: myHost (myHost)

ssh-add -L
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAA...[omitted].../Users/bwallen/.ssh/myHost

1 comment:

  1. Instead of using cat to copy your ID file to the remote host, use ssh-copy-id. It's far more secure and much easier:
    ssh-copy-id -i my_id_file.rsa user@remotehost. It uses ssh with password authentication to first login then does all the copying plus secures your authorized_hosts file. Once you've completed the task, you can turn off password authentication.

    ReplyDelete