How to Use SSH Key Authentication

Secure your server by requiring SSH keys for remote logins

An unlocked combination lock

Pixabay

 

Normally, when you log into a remote server with SSH, you do so using a username/password combination.

However, using a password is limited to the length of password you can remember or are willing to type out. With SSH key authentication, an encrypted passphrase offers far more secure credentials than are practical with a standard password. The cryptographic strength in SSH key authentication goes way beyond what a standard password can match.

Generating Your SSH Key

Screenshot of generating an SSH Key on Linux.

Open a terminal window on the client machine you plan on using to log into your server and issue the command:

ssh-keygen

You will be asked to enter a filename for your newly generated key. We recommend accepting the default (~/.ssh/id_rsa). Then select and verify a passphrase. Make this passphrase a strong one.

When the command completes, your key is ready to use.

Copying Your Key to the Server

Use SSH to copy your key to the remote server. Issue the command:

ssh-copy-id USER@SERVER_IP

Where USER is the username and SERVER_IP is IP address of the server you want to log into. You’ll be prompted for the USER password. After you successfully authenticate, the SSH key copies and you can then log into the server in the normal fashion.

Because the client you are logging in from has the matching key that is now on the server, you’ll be logged in.

Repeat this process on every client machine that needs to SSH into the server.

Locking It Down

Screenshot of the sshd_config file found on Linux.

It's considered best security practice to disable password authentication into servers, relying solely on SSH key authentication. Modify the SSH daemon configuration accordingly. Open the configuration file by executing:

sudo nano /etc/ssh/sshd_config

In that file, look for the line:

#PasswordAuthentication yes

Un-comment the line by removing the hashtag then change yes to no.

Next, look for the line:

#PubkeyAuthentication yes

Un-comment that line as well.

Save and close the file. Restart the SSH daemon with the command:

sudo systemctl restart sshd

Now if you attempt to SSH into that server from any client that does not contain a matching SSH Key, you will be denied access.

Where Is the SSH Key Stored?

Screenshot of the authorized_keys file found on Linux.

Log onto the server to which you copied your keys. Issue the command:

less ~/.ssh/authorized_keys

You'll see all of the keys you’ve sent from clients (using the ssh-copy-id command). To revoke SSH key authentication from a particular client, delete the lines that correspond with the client’s hostname (the hostname is the last bit of information in the key).