X

How To Setup SSH Key Authentication

SSH key authentication can be used for password-less login between 2 servers. This is also useful for adding a key to accounts like git or gitlab for version management.

Source Server SSH Key Configuration

Generate a RSA key for this system by typing the following

ssh-keygen -t rsa

The key generated will ask for a location to store the newly created key, the default is the home directory of the user creating it under the .ssh directory. It will also ask you for a password which you optionally leave blank.

Destination Server SSH Key Configuration

On the source server you can use ssh-copy-id to copy over the id_rsa.pub file to the new server. It will use the SSH protocol to copy over the public key and insert it into the authorized_keys file on the destination server.  To read more about ssh-copy-id you can read the man page.

ssh-copy-id -i ~/.ssh/id_rsa.pub user@192.168.1.3
Replacing 192.168.1.3 with the appropriate host name of the destination server and user with the user you would like to add the key too. 

/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
user@192.168.1.3's password:

Number of key(s) added: 1

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

Manual SSH Key Configuration on the Destination Server

First verify if you already have a .ssh directory

ls ~/.ssh

If you do not you will want to create the following directory

mkdir ~/.ssh

You will also want to create authorized_keys file

touch ~/.ssh/authorized_keys

You will then want to copy the public key from the source server in to the authorized_keys file. You can do this by copying the id_rsa.pub on the source server.

scp  ~/.ssh/id_rsa.pub username@remote_host:~/.ssh/authorized_keys

Root SSH Key Configuration

If you are adding keys to a root user on the destination server, you will want to ensure the sshd configuration allows remote root logins with either the following 2 options enabled in /etc/ssh/sshd_config

PermitRootLogin yes

Which will allow root logins with both passwords and keys.

PermitRootLogin without-password

Which will allow root logins only with keys

If you modify the ssh configuration, you will need to reload sshd to load the new configuration

/etc/init.d/sshd reload

After you have added the key to the destination server, ssh from the source server it should allow you to login using the key.

LinuxAdmin.io
0 0 votes
Article Rating
LinuxAdmin.io:
Related Post