Use the ssh-keygen command to generate a public/private authentication key pair. Authentication keys allow a user to connect to a remote system without supplying a password. Keys must be generated for each user separately. If you generate key pairs as the root user, only the root can use the keys.
Generating keys and configuring passwordless ssh with ssh-keygen command
1. Use the -t option to specify the key type. Example:
# ssh-keygen -t rsa Generating public/private rsa key pair. Enter file in which to save the key (/root/.ssh/id_rsa): Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /root/.ssh/id_rsa. Your public key has been saved in /root/.ssh/id_rsa.pub. The key fingerprint is: 3a:b8:10:71:b7:ee:66:15:0f:a2:b0:89:ef:65:0b:f0 root@geeklab The key's randomart image is: +--[ RSA 2048]----+ | | | | | . . . | | .o ...o | |...+ ...S+ | |.oo..o .. . | | .E + +. | | .= +o. | | .. oo. | +-----------------+
Use the –t option to specify the type of key to create. Possible values are
a. “rsa1” for protocol version 1
b. “dsa”, “ecdsa”, or “rsa” for protocol version 2.
2. You have the option of specifying a passphrase to encrypt the private part of the key. If you encrypt your personal key, you must supply the passphrase each time you use the key. This prevents an attacker, who has access to your private key and can impersonate you and access all the computers you have access to, from being able to do so. The attacker still needs to supply the passphrase.
3. The ssh-key command in the example of step 1 generated two keys in the ~/.ssh directory:
$ ls ~/.ssh id_rsa id_rsa.pub
4. To log on to, or copy files to, a remote system without supplying a password, copy the public key (~/.ssh/id_rsa.pub in this example) to ~/.ssh/authorized_keys on the remote system. Set the remote ~/.ssh directory permissions to 700. To allow multiple connections, append the public key to the authorized_keys file on the remote system instead of copying it. The following example appends the public key:
$ cat id_rsa.pub >> authorized_keys
5.You can then use the ssh or scp tools to access the remote system without supplying a password.
Enforcing the key-based authentication
1. You can improve system security even further by disabling the standard password authentication, and enforcing the key-based authentication. To do so, set the PasswordAuthentication option to no in the /etc/ssh/sshd_config configuration file as follows:
# vi /etc/ssh/sshd_config PasswordAuthentication no
2. This disallows users whose keys are not in the authorized_keys file of the specific user on the server to connect via ssh. The connection is denied and the following message appears:
$ ssh remote_host Permission denied (publickey,gssapi-keyex,gssapi-with-mic).
3. Setting the PasswordAuthentication option to yes, which is the default, permits a user to use a password for authentication.