How to Configure ssh key-based authentication to login to remote host

SSH Key-based Authentication

You can configure an SSH server to allow you to authenticate without a password by using key-based authentication. This is based on a private-public key scheme. To do this, you generate a matched pair of cryptographic key files. One is a private key, the other a matching public key. The private key file is used as the authentication credential and, like a password, must be kept secret and secure. The public key is copied to systems the user wants to connect to and is used to verify the private key. The public key does not need to be secret.

You put a copy of the public key in your account on the server. When you try to log in, the SSH server can use the public key to issue a challenge that can only be correctly answered by using the private key. As a result, your ssh client can automatically authenticate your login to the server with your unique copy of the private key. This allows you to securely access systems in a way that doesn’t require you to enter a password interactively every time.

Generating SSH Keys

To create a private key and matching public key for authentication, use the ssh-keygen command. By default, your private and public keys are saved in your ~/.ssh/id_rsa and ~/.ssh/id_rsa.pub files, respectively.

[[email protected] ~]$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/user/.ssh/id_rsa): Enter
Created directory '/home/user/.ssh'.
Enter passphrase (empty for no passphrase): Enter
Enter same passphrase again: Enter
Your identification has been saved in /home/user/.ssh/id_rsa.
Your public key has been saved in /home/user/.ssh/id_rsa.pub.
The key fingerprint is: SHA256:vxutUNPio3QDCyvkYm1oIx35hmMrHpPKWFdIYu3HV+w [email protected]
The key's randomart image is:
+---[RSA 2048]----+
|                 |
|   .     .       |
|  o o     o      |
| . = o   o .     |
|  o + = S E .    |
| ..O o + * +     |
|.+% O . + B .    |
|=*oO . . + *     |
|++.     . +.     |
+----[SHA256]-----+

If you do not specify a passphrase when ssh-keygen prompts you, the generated private key is not protected. In this case, anyone with your private key file could use it for authentication. If you set a passphrase, then you will need to enter that passphrase when you use the private key for authentication. (Therefore, you would be using the private key’s passphrase rather than your password on the remote host to authenticate.)

You can run a helper program called ssh-agent which can temporarily cache your private key passphrase in memory at the start of your session to get true passwordless authentication. This will be discussed later in this section. The following example of the ssh-keygen command shows the creation of the passphrase-protected private key alongside the public key.

[[email protected] ~]$ ssh-keygen -f .ssh/key-with-pass
Generating public/private rsa key pair.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in .ssh/key-with-pass.
Your public key has been saved in .ssh/key-with-pass.pub.
The key fingerprint is:
SHA256:w3GGB7EyHUry4aOcNPKmhNKS7dl1YsMVLvFZJ77VxAo [email protected]
The key's randomart image is:
+---[RSA 2048]----+
|    . + =.o ...  |
|     = B XEo o.  |
|  . o O X =....  |
| = = = B = o.    |
|= + * * S .      |
|.+ = o + .       |
|  + .            |
|                 |
|                 |
+----[SHA256]-----+

The -f option with the ssh-keygen command determines the files where the keys are saved. In the preceding example, the private and public keys are saved in the /home/user/.ssh/key-with-pass /home/user/.ssh/key-with-pass.pub files, respectively.

Warning: During further SSH keypair generation, unless you specify a unique file name, you are prompted for permission to overwrite the existing id_rsa and id_rsa.pub files. If you overwrite the existing id_rsa and id_rsa.pub files, then you must replace the old public key with the new one on all the SSH servers that have your old public key.

Once the SSH keys have been generated, they are stored by default in the .ssh/ directory of the user’s home directory. The permission modes must be 600 on the private key and 644 on the public key.

Sharing the Public Key

Before key-based authentication can be used, the public key needs to be copied to the destination system. The ssh-copy-id command copies the public key of the SSH keypair to the destination system. If you omit the path to the public key file while running ssh-copy-id, it uses the default /home/user/.ssh/id_rsa.pub file.

[[email protected] ~]$ ssh-copy-id -i .ssh/key-with-pass.pub [email protected]
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/user/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
[email protected]'s password: mypass
Number of key(s) added: 1

Now try logging into the machine, with: "ssh '[email protected]'"
and check to make sure that only the key(s) you wanted were added.

After the public key is successfully transferred to a remote system, you can authenticate to the remote system using the corresponding private key while logging in to the remote system over SSH. If you omit the path to the private key file while running the ssh command, it uses the default /home/user/.ssh/id_rsa file.

[[email protected] ~]$ ssh -i .ssh/key-with-pass [email protected]
Enter passphrase for key '.ssh/key-with-pass': mypass
...output omitted...

[[email protected] ~]$ exit
logout
Connection to remotehost closed.
[[email protected] ~]$

Using ssh-agent for Non-interactive Authentication

If your SSH private key is protected with a passphrase, you normally have to enter the passphrase to use the private key for authentication. However, you can use a program called ssh-agent to temporarily cache the passphrase in memory. Then any time that you use SSH to log in to another system with the private key, ssh-agent will automatically provide the passphrase for you. This is convenient and can improve security by providing fewer opportunities for someone “shoulder surfing” to see you type the passphrase in.

Depending on your local system’s configuration, if you initially log in to the GNOME graphical desktop environment, the ssh-agent program might automatically be started and configured for you. If you log in on a text console, log in using ssh, or use sudo or su, you will probably need to start ssh-agent manually for that session. You can do this with the following command:

#[[email protected] ~]$ eval $(ssh-agent)
Agent pid 10155
[[email protected] ~]$

Once ssh-agent is running, you need to tell it the passphrase for your private key or keys. You can do this with the ssh-add command. The following ssh-add commands add the private keys from /home/user/.ssh/id_rsa (the default) and /home/user/.ssh/key-with-pass files, respectively.

[[email protected] ~]$ ssh-add
Identity added: /home/user/.ssh/id_rsa ([email protected])

[[email protected] ~]$ ssh-add .ssh/key-with-pass
Enter passphrase for .ssh/key-with-pass: mypass
Identity added: .ssh/key-with-pass ([email protected].lab.example.com)

After successfully adding the private keys to the ssh-agent process, you can invoke an SSH connection using the ssh command. If you are using any private key file other than the default /home/user/.ssh/id_rsa file, then you must use the -i option with the ssh command to specify the path to the private key file. The following example of the ssh command uses the default private key file to authenticate to an SSH server.

[[email protected] ~]$ ssh [email protected]
Last login: Fri Apr  5 10:53:50 2019 from host.example.com
[[email protected] ~]$

The following example of the ssh command uses the /home/user/.ssh/key-with-pass (nondefault) private key file to authenticate to an SSH server. The private key in the following example has already been decrypted and added to its parent ssh-agent process, so the ssh command does not prompt you to decrypt the private key by interactively entering its passphrase.

[[email protected] ~]$ ssh -i .ssh/key-with-pass [email protected]
Last login: Mon Apr  8 09:44:20 2019 from host.example.com
[[email protected] ~]$

When you log out of the session that started ssh-agent, the process will exit and your the passphrases for your private keys will be cleared from memory.