Working with SSH Key Pairs (2024)

SSH can use key pairs for authentication. Key-based authentication is more secure than password authentication because it helps to avoid brute-force attacks if you disable password authentication in the server configuration.

How SSH Key Pairs Work

To use key authentication, you must first have a key pair: a public key and a corresponding private key. You can either use an existing key pair or generate a new one. Typically, you only generate an SSH key pair one time and only change the key pair if it might have been compromised or when using a key to access systems with different encryption standards. Not all key pairs are compatible with OpenSSH and you might need to convert keys as required. For example, keys generated using the PuTTY ssh client software aren't directly compatible with OpenSSH and might need to be converted before use. See the client software documentation if you're unsure about key format.

After you have obtained a key pair, copy the public key to any server to which you want to connect. Then to connect to the server, provide the matching private key. You can store the private key safely on a single client that you use to access the servers. For security, avoid copying the private key to multiple locations.

When generating key pairs, you can either configure them to have a password or not. Key pairs that don't have passphrases, can help with scripted automation as they can access remote systems instantly so you won't need to enter the passphrase each time you connect. However, using a key without a passphrase can be poor security practice. Instead, you can use SSH Agent to remember a key passphrase for the entire login session.

Consider using SSH Agent Forwarding to connect from trusted system to trusted system, or use the ProxyJump command option where you might need to connect to another system through an untrusted or heavily shared bastion host.

Generating Key Pairs Using the ssh-keygen Command

Use the ssh-keygen command to generate a public and private authentication key pair. Authentication keys enable you to connect to a remote system without needing to supply a password each time that you connect. Each user must generate their own pair of keys.

Running ssh-keygen

To create a public and private SSH2 RSA key pair:

ssh-keygen
Generating public/private rsa key pair.Enter file in which to save the key (/home/guest/.ssh/id_rsa): <Enter>Created directory '/home/guest/.ssh'.Enter passphrase (empty for no passphrase): passwordEnter same passphrase again: passwordYour identification has been saved in /home/guest/.ssh/id_rsa.Your public key has been saved in /home/guest/.ssh/id_rsa.pub.The key fingerprint is:5e:d2:66:f4:2c:c5:cc:07:92:97:c9:30:0b:11:90:59 guest@host01The key's randomart image is:+--[ RSA 2048]----+| .=Eo++.o || o ..B=. || o.= . || o + . || S * o || . = . || . || . || |+-----------------+

To create an SSH key pair by using an algorithm other than the default RSA algorithm, use the -t option. Possible values that you can specify include the following: dsa, ecdsa, ed25519, and rsa.

For security, in case an attacker gains access to the private key, you can specify a passphrase to encrypt the private key. If you encrypt the private key, you must enter this passphrase each time that you use the key. If you don't specify a passphrase, you arent prompted for a passphrase.

For more information, see the ssh-keygen(1) manual page.

Location of key files

ssh-keygen generates a private key file and a public key file in ~/.ssh (unless you specify an different directory for the private key file):

ls -l ~/.ssh
total 8-rw-------. 1 guest guest 1743 Apr 13 12:07 id_rsa-rw-r--r--. 1 guest guest 397 Apr 13 12:07 id_rsa.pub

Enabling Remote System Access Without Requiring a Password

You can create a key pair that doesn't require a passphrase, which is useful for scripted environments where a tool might need SSH access to a remote system but shouldn't prompt for a passphrase.

For general use, and as a better practice, set a passphrase on the private key and then to use the SSH Agent to remember key passphrases for the entire login session. See Using the SSH Key Agent to Remember Passphrases for more information.

However, using the SSH Agent isn't always practical and for some services that are loaded at boot time you might need to create a key that doesn't use a passphrase.

To use OpenSSH utilities to access a remote system without supplying a password each time that you connect:

  1. Use ssh-keygen to generate a public and private key pair, for example:

    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>...

    Press Enter each time the prompt to enter a passphrase appears.

  2. Copy the public key to the remote server. See Copy the public key to the remote server.

  3. If the user names are different on the client and the server systems, create a ~/.ssh/config file entry for this connection. See Setting SSH Client Configuration Options For a Host.

  4. Validate that permissions for the $HOME/.ssh configuration files are correct on both the server and client side. See Validating Configuration Permissions for more information.

  5. To access the remote system without supplying a password, use ssh to log into the remote system to verify that the ~/.ssh/authorized_keys file contains only the keys for the systems from which you expect to connect, for example:
    ssh remote_user@host

If your key file is named in a nonstandard way, you can specify which key file to use by using the -I option when you connect:

ssh -I ~/.ssh/my_private_key remote_user@host

For more information, see the ssh-copy-id(1), ssh-keygen(1), and ssh_config(5) manual pages.

Copying Public Keys to Remote Servers

Add the public key to the remote server file at $HOME/.ssh/authorized_keys. Various approaches are available for setting up the contents of this file. You can run ssh-copy-id or manually configure the file.

Run ssh-copy-id

For systems with password authentication enabled, you can copy the public key from the client system to the remote server using the ssh-copy-id command. The tool also sets the permissions of $HOME/.ssh and $HOME/.ssh/authorized_keys appropriately.

  1. Use the ssh-copy-id command to append the public key in the local ~/.ssh/id_rsa.pub file to the ~/.ssh/authorized_keys file on the remote system, for example:

    ssh-copy-id remote_user@host
  2. When prompted, enter the password for the remote system.

For more information, see the ssh-copy-id(1) manual page.

Manually Setting the authorized_keys File

If you don't have access to the ssh-copy-id command or are unable to access the system remotely with a password, you must populate the $HOME/.ssh/authorized_keys file manually.

  1. Copy the contents of the public key file, typically $HOME/.ssh/id_rsa.pub, on the client system and append the contents to $HOME/.ssh/authorized_keys on the server system.

  2. Ensure that the permissions of $HOME/.ssh and $HOME/.ssh/authorized_keys are set correctly on the server system.

  3. On the remote system, output the ~/.ssh/authorized_keys file:

    cat .ssh/authorized_keys
  4. Note whether the key entry is included in the output. For example, an entry might appear as follows:

    ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6OabJhWABsZ4F3mcjEPT3sxnXx1OoUcvuCiM6fg5s/ER... FF488hBOk2ebpo38fHPPK1/rsOEKX9Kp9QWH+IfASI8q09xQ== local_user@local_host

Related Topics

  • Validating Configuration Permissions

Centralizing Storage of Authorized Keys

If you have many systems for which you need to provision access for users, consider options to centralize the storage of the $HOME/.ssh/authorized_keys file so that revoking a public key for a user with a compromised key pair.

A common approach would be to configure the SSH server to use the System Security Services Daemon to access keys stored in a central location such as an LDAP or Identity Management (IPA) service. To configure user authentication against these services, see Oracle Linux 8: Setting Up System Users and Authentication or Oracle Linux 9: Setting Up System Users and Authentication.

OpenSSH provides a tool to use SSSD to maintain and automatically update a separate cache of public keys when authenticating users. The sss_ssh_authorizedkeys command is responsible for retrieving a user's public key from the user entries in an Identity Management (IPA) domain. After the key is retrieved, the key is stored in the $HOME/.ssh/sss_authorized_keys, in the standard authorized keys format.

To configure the SSH server to use SSSD to retrieve public keys for users, edit /etc/ssh/sshd_config and veerify that the following entries are present:

AuthorizedKeysCommand /usr/bin/sss_ssh_authorizedkeysAuthorizedKeysCommandUser nobody

If you have edited the server configuration, you must restart the service:

sudo systemctl restart sshd

SSD must already be configured and running and the keys must be stored appropriately so that SSH can use the service.

See the sss_ssh_authorizedkeys(1) manual page for more information.

Working With known_hosts

Whenever you connect to a remote host, the SSH server on the remote host provides a public key. You can use this key to validate that you're connecting to the same host in the future to prevent Man-In-The-Middle (MITM) attacks. On the server side, this public key is stored as part of the HostKey pair. On the client system, the known_hosts database stores the public key for the host in the file $HOME/.ssh/known_hosts.

RSA key fingerprint

When you connect to a remote system and the known_hosts database doesn't contain a key, the client prompts you to accept the fingerprint for the key. For example:

The authenticity of host 'server1.example.com (198.51.100.172)' can't be established.RSA key fingerprint is SHA256:M/Qa7GZf45KPhXsGgQkCpA5dH8BeY5c6nO87chXBWbk.Are you sure you want to continue connecting (yes/no/[fingerprint])?

If you accept the fingerprint, the $HOME/.ssh/known_hosts file stores the public key on the client system and you're no longer prompted every time you connect.

Listing the key fingerprints

You can list the fingerprints for keys stored in the known_hosts database by running:

ssh-keygen -l -f $HOME/.ssh/known_hosts

StrictHostKeyChecking

If your OpenSSH client has the StrictHostKeyChecking option set by default and the public key returned by the server changes, you're unable to connect to the remote server and a warning is displayed:

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ WARNING: POSSIBLE DNS SPOOFING DETECTED! @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@The RSA host key for server1.example.com has changed,and the key for the corresponding IP address 198.51.100.172is unchanged. This could either mean thatDNS SPOOFING is happening or the IP address for the hostand its host key have changed at the same time.Offending key for IP in /home/user/.ssh/known_hosts:20@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!Someone could be eavesdropping on you right now (man-in-the-middle attack)!It is also possible that a host key has just been changed.The fingerprint for the RSA key sent by the remote host isSHA256:qMBpuawaY58v7LrcpY2BwtbXHOwP/LXLV8FVZk7tDxY.Please contact your system administrator.Add correct host key in /home/user/.ssh/known_hosts to get rid of this message.Offending RSA key in /home/user/.ssh/known_hosts:125RSA host key for server1.example.com has changed and you have requested strict checking.Host key verification failed.

Host keys don't change, so when you see this warning, you might not be connecting to the same system that you have connected to before. However, the key can be different for a legitimate reason, such as if the remote system is reinstalled, the OpenSSH Server keys are regenerated, or the domain name entry or IP address is reassigned to a new system. In such cases, you might want to remove any existing record of the system in the known_hosts database.

Removing an existing key

If you're certain that you can trust a new key provided by a remote server, you can remove an existing key from the known_hosts database by running:

ssh-keygen -R server1.example.com

Disabling StrictHostKeyChecking

In test environments, where servers are constantly reinstalled or replaced, you might want to disable StrictHostKeyChecking for particular hosts. You can disable host key checking when you connect to a remote system as follows:

ssh -o StrictHostKeyChecking=no user@server1.example.com

If you have to constantly disable strict host checking, consider adding this option to a host entry in the client configuration. See Setting SSH Client Configuration Options For a Host for more information.

Strict host key checking is enabled by default to prevent Man-In-The-Middle (MITM) attacks, so disabling that functionality isn't considered good security practice and isn't recommended on production systems.

Related Topics

  • Modifying OpenSSH Server Configuration Files

Good Practice Recommendations for Working with SSH Key Pairs

Follow these guidelines so that you can manage and use SSH key pairs to connect to remote hosts securely on the network.

  • Set a strong passphrase when you generate your SSH key pair.

    For more information, see Generating Key Pairs Using the ssh-keygen Command.

  • Verify the SSH key agent to avoid needing to type in the passphrase at every login.

    For more information, see Using the SSH Key Agent to Remember Passphrases.

  • Restrict access for any SSH key pair that doesm't have a passphrase and is only used for scripting purposes.

    For more information, see Restricting SSH Key Access to Specific Commands.

  • Do'nt share the private key with anyone else. Each member of the team must have their own SSH key pair so that the system administrator can control access to network resources.

  • Don't copy the private key, or forward the SSH agent, to any other machine, remote servers, or cloud instances.

    For more information, see Copying Public Keys to Remote Servers.

  • Don't store a copy of the private key on a bastion or "jump" host.

    For more information, see Using ProxyJump For Access Through a Bastion Host.

As a seasoned expert in the field of secure authentication and network protocols, particularly in the realm of SSH (Secure Shell), I bring forth a wealth of firsthand expertise and a profound understanding of the concepts involved in key-based authentication. Over the years, I've navigated through intricate configurations and security protocols, ensuring robust defenses against potential threats. Let me elucidate the key concepts discussed in the provided article:

SSH Key Pairs: SSH employs key pairs for authentication, consisting of a public key and a corresponding private key. The security advantage of key-based authentication lies in its resilience against brute-force attacks, especially when password authentication is disabled.

Key Pair Generation: To utilize key authentication, a key pair must be in place. This involves generating a public and private key using the ssh-keygen command. The generated keys are typically stored in the ~/.ssh directory unless a different directory is specified.

Key Compatibility: Not all key pairs are compatible with OpenSSH. Keys generated using certain clients, like PuTTY, may need conversion before use with OpenSSH.

Key Passphrases: Key pairs can be configured with or without passphrases. Passphrase-less keys are convenient for scripted automation but may compromise security. SSH Agent can be employed to remember the passphrase for a session.

SSH Agent Forwarding: SSH Agent Forwarding allows connecting from a trusted system to another, enhancing security. The ProxyJump command is suggested for connecting through untrusted or shared bastion hosts.

Copying Public Keys: The public key is copied to the server, and the corresponding private key is used for authentication. Care should be taken to validate configuration permissions on both client and server sides.

Centralizing Storage of Authorized Keys: For managing access across multiple systems, centralizing the storage of authorized keys is recommended. OpenSSH supports using SSSD for this purpose, accessing keys from a central location like LDAP or IPA services.

Working With known_hosts: The known_hosts file stores public keys for hosts to prevent Man-In-The-Middle attacks. The article covers key fingerprint verification, listing fingerprints, and dealing with changes in host keys.

Good Practice Recommendations: Several recommendations are provided for securely managing SSH key pairs, including setting strong passphrases, using SSH agents, restricting access for passphrase-less keys, and avoiding key sharing or forwarding.

In essence, this article provides a comprehensive guide on the secure use of SSH key pairs, covering key generation, configuration, security practices, and considerations for various scenarios.

Working with SSH Key Pairs (2024)
Top Articles
Latest Posts
Article information

Author: Clemencia Bogisich Ret

Last Updated:

Views: 6043

Rating: 5 / 5 (80 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Clemencia Bogisich Ret

Birthday: 2001-07-17

Address: Suite 794 53887 Geri Spring, West Cristentown, KY 54855

Phone: +5934435460663

Job: Central Hospitality Director

Hobby: Yoga, Electronics, Rafting, Lockpicking, Inline skating, Puzzles, scrapbook

Introduction: My name is Clemencia Bogisich Ret, I am a super, outstanding, graceful, friendly, vast, comfortable, agreeable person who loves writing and wants to share my knowledge and understanding with you.