SSH Public Key Authentication
From Gentoo Linux Wiki
OpenSSH allows you to use Public Key authentication to login to servers without a password.
Contents |
[edit] Generating Keys
To generate the public and private key files you can use the ssh-keygen command which is installed with OpenSSH.
This will result in the following output and a prompt for you to choose the location to store the key files.
| Code: Result from running ssh-keygen |
Generating public/private rsa key pair. Enter file in which to save the key (/home/gerard/.ssh/id_rsa): |
The default location is fine for this tutorial so press <enter> to accept the default.
You will now be prompted to enter the passphrase. A good passphrase should be at least 10 - 20 characters long, and use a mix of alphanumeric and punctuation characters.
| Code: ssh-keygen prompting for a passphrase |
Enter passphrase (empty for no passphrase): |
Your public key file is now ~/.ssh/id_rsa.pub this key can be shared with anyone. Your private key file is now ~/.ssh/id_rsa this key must be kept secret.
[edit] Key Installation
You now need to copy your public key file to the remote host(s) you want to be able to use public key authentication on.
[edit] Using ssh-copy-id
To copy your new key you can use the following command to copy the key to host1.example.net:
[edit] Manual Installation
To install the key need to append the key to the ~/.ssh/authorized_keys file on each host you wish to use it on.
# copy the key to the remote host scp ~/.ssh/id_rsa.pub user@remotehost:id_rsa.pub # ssh into the remote host using your password ssh user@remotehost # append the public key cat id_rsa.pub >> ~/.ssh/authorized_keys rm id_rsa.pub
[edit] Forcing Public Key Authentication
Once you have setup public key authentication successfully you may wish to make OpenSSH more secure by removing all other authentication options.
OpenSSH supports 3 main methods of authentication
- Password
- Challenge Response, also known as keyboard interactive (normally this also does password authentication via PAM, but can be setup to do other things like using SecurId tokens)
- Public Key
You can remove support for the first 2 options by editing the OpenSSH server config file.
ChallengeResponseAuthentication no PasswordAuthentication no
Now reload your server
You will now only be able to login using public key authentication
[edit] Using ssh-agent
It can be annoying having to type your long passphrase every time you want to connect to a ssh server. An easier way is to launch the ssh-agent daemon and add your key to it. Then anytime ssh needs to use your private key it talks to ssh-agent. This means you only have to enter your passphrase once (when you add your key to ssh-agent).
Launch ssh-agent
Add your private key (you will be asked for your passphrase).