How to Setup SSH Key Authentication on a Linux Server

Setting up SSH key authentication on a Linux server involves generating a key pair on your local machine, copying the public key to the server, and ensuring the SSH configuration allows key-based authentication. Here’s a step-by-step guide:

Step 1: Generate an SSH Key Pair

  1. Open a terminal on your local machine.
  2. Generate the key pair using the ssh-keygen command:
   ``
   ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
   ``
  • -t rsa: Specifies the type of key to create (RSA).
  • -b 4096: Specifies the number of bits in the key (4096 bits is a strong key size).
  • -C "your_email@example.com": Adds a label to the key, such as your email address.
  1. When prompted, choose a location to save the key (the default is usually ~/.ssh/id_rsa).
  2. Optionally, enter a passphrase to add an extra layer of security.

Step 2: Copy the Public Key to the Server

  1. Use the ssh-copy-id command to copy your public key to the server:

   ssh-copy-id username@server_ip_address
  • Replace username with your username on the server.
  • Replace server_ip_address with the IP address or domain name of the server.

If ssh-copy-id is not available, you can manually copy the key:

cat ~/.ssh/id_rsa.pub | ssh username@server_ip_address ‘mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys’

Step 3: Verify SSH Key Authentication

  1. Attempt to log in to the server using SSH:

   ssh username@server_ip_address

You should be able to log in without being prompted for a password (unless you set a passphrase for the key).

Step 4: Configure SSH for Security (Optional but Recommended)

  1. Edit the SSH daemon configuration file on the server:

   sudo nano /etc/ssh/sshd_config
  1. Ensure the following settings are configured:

   PubkeyAuthentication yes
   PasswordAuthentication no
   ChallengeResponseAuthentication no
   UsePAM no
  • PubkeyAuthentication yes: Enables public key authentication.
  • PasswordAuthentication no: Disables password authentication for additional security.
  • ChallengeResponseAuthentication no: Disables challenge-response authentication.
  • UsePAM no: Disables Pluggable Authentication Modules (PAM).
  1. Restart the SSH service to apply the changes:
   sudo systemctl restart ssh

Summary

  • Generate an SSH key pair.
  • Copy the public key to the server.
  • Verify SSH key authentication.
  • Optionally, configure the SSH daemon for enhanced security.

With these steps, you’ve set up SSH key authentication on your Linux server, improving both security and convenience.

About Daniel Fredrick

Technology enthusiast, Programmer, Network Engineer CCIE# 17094

View all posts by Daniel Fredrick →

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.