Devbyte tutorials cover

How to Set Up SSH Keys on Ubuntu 22.04: A Quick and Secure Guide

Table of Contents

Setting up SSH keys on Ubuntu 22.04 is a crucial step for enhancing server security and streamlining remote access. SSH keys offer a more secure alternative to password-based authentication, reducing the risk of unauthorized access to your system. To set up SSH keys on Ubuntu 22.04, you’ll need to generate a key pair, copy the public key to the server, and configure SSH to use key-based authentication.

The process of setting up SSH keys involves creating a pair of cryptographic keys – a public key and a private key. The public key is placed on the server you want to access, while the private key remains on your local machine. When you attempt to connect to the server, it verifies your identity using these keys, granting access only if they match.

By using SSH keys, you can improve your system’s security and make login processes more efficient. This method eliminates the need to remember complex passwords and reduces the chances of brute-force attacks. Additionally, SSH keys can be easily managed and revoked if necessary, providing greater control over access to your Ubuntu 22.04 server.

Key Takeaways

  • SSH keys provide stronger security than password-based authentication
  • The setup process involves generating a key pair and configuring the server
  • Key-based authentication simplifies logins and improves access management

Prerequisites

Before setting up SSH keys on Ubuntu 22.04, you need to understand SSH and check your Ubuntu version. These steps will help you prepare for the key setup process.

Understanding SSH and Its Importance

SSH stands for Secure Shell. It’s a way to connect to other computers safely over the internet. SSH uses keys instead of passwords, which makes it harder for bad people to break in.

SSH keys come in pairs – a public key and a private key. The public key goes on the computer you want to connect to. The private key stays on your own computer. This system is very secure.

Using SSH keys is better than using passwords. Keys are longer and more complex, so they’re harder to guess. They also let you log in without typing a password each time.

Checking Ubuntu Version

To set up SSH keys, you need to know which version of Ubuntu you’re using. Ubuntu 22.04 is the latest long-term support release.

To check your Ubuntu version:

  1. Open the Terminal
  2. Type this command: lsb_release -a
  3. Press Enter

The output will show your Ubuntu version. Make sure it says 22.04.

If you have an older version, you might need to upgrade first. Upgrading ensures you have the latest security features and software compatibility.

Setting Up SSH Keys

Setting up SSH keys enhances security and simplifies remote server access. This process involves installing the SSH server, generating a key pair, and creating a strong passphrase.

Installing OpenSSH Server

To begin, you’ll need to install the OpenSSH server on your Ubuntu 22.04 system. Open a terminal and run the following command:

sudo apt update
sudo apt install openssh-server

After installation, check the status of the SSH service:

sudo systemctl status ssh

If it’s not running, start it with:

sudo systemctl start ssh

Generating a New SSH Key Pair

With the SSH server installed, the next step is to generate an SSH key pair. This creates a public and private RSA key pair. To do this, use the ssh-keygen command:

ssh-keygen -t rsa -b 4096

The -t flag specifies the key type (RSA), and -b sets the key size to 4096 bits for enhanced security.

When prompted, choose a location to save the key pair. The default location is usually fine for most users.

Creating a Secure Passphrase

During the key generation process, you’ll be asked to enter a passphrase. This adds an extra layer of security to your SSH key.

A strong passphrase should:

  • Be at least 15 characters long
  • Include a mix of uppercase and lowercase letters, numbers, and symbols
  • Not contain personal information or common words

Remember this passphrase, as you’ll need it when using your SSH key to connect to remote servers.

Managing SSH Key Files

SSH key files are crucial for secure remote access. Proper management involves knowing where they’re stored and setting the right permissions.

Locating the SSH Key Files

SSH key files are typically found in the .ssh folder within the user’s home directory. The private key is usually named id_rsa, while the public key is id_rsa.pub. To view these files, open a terminal window and enter:

ls -la ~/.ssh

If the .ssh folder doesn’t exist, it will be created when generating new SSH keys.

Setting File Permissions

Correct file permissions are essential for SSH key security. The private key should be readable only by the owner. To set the right permissions, use these commands in the terminal:

chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_rsa
chmod 644 ~/.ssh/id_rsa.pub

These commands ensure that only the owner can access the private key, while the public key remains readable by others. Incorrect permissions may prevent SSH from working or compromise security.

Deploying SSH Keys to a Server

After creating SSH keys, you need to copy the public key to the remote server. This allows secure, password-free logins. Testing the connection ensures everything works properly.

Copying the Public Key to Remote Host

The easiest way to copy your public key is with the ssh-copy-id command. Use this format:

ssh-copy-id username@remote_host

Replace “username” with your account name and “remote_host” with the server’s IP or domain. You’ll be asked for the remote account password.

If ssh-copy-id isn’t available, you can manually copy the key. Use this command:

cat ~/.ssh/id_rsa.pub | ssh username@remote_host "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"

This adds your public key to the authorized_keys file on the server.

SSH Key Authentication Test

To test your SSH key setup, try logging into the remote server:

ssh username@remote_host

If it works, you’ll log in without a password prompt. The SSH daemon on the server checks your key against the authorized_keys file.

If you still get a password prompt, check these things:

  • Ensure the ~/.ssh directory on the server has 700 permissions
  • Check that ~/.ssh/authorized_keys has 600 permissions
  • Verify the server’s SSH config allows key authentication

With proper setup, SSH keys provide a secure and convenient way to access remote servers.

Configuring SSH for Secure Access

SSH configuration is key to maintaining a secure server. Proper setup prevents unauthorized access and strengthens your system’s defenses.

Editing the SSH Configuration File

The main SSH configuration file is located at /etc/ssh/sshd_config. To edit it, use a text editor with root privileges:

sudo nano /etc/ssh/sshd_config

This file controls SSH server behavior. Common settings include:

  • Port: Change the default SSH port (22) to a custom one.
  • PermitRootLogin: Control root user login via SSH.
  • MaxAuthTries: Limit login attempts.

After making changes, save the file and restart the SSH service:

sudo systemctl restart ssh

Disabling Password-Based SSH Access

Disabling password authentication enhances security. SSH keys are safer than passwords. To disable password login:

  1. Open the SSH config file.
  2. Find the line “PasswordAuthentication yes”.
  3. Change it to “PasswordAuthentication no”.
  4. Save and exit.

This change forces users to use SSH keys for login. It’s crucial to set up SSH keys before disabling passwords. Otherwise, you might lock yourself out of the server.

Limiting Root Login

Root login poses security risks. It’s better to use a regular user account with sudo privileges. To disable root SSH login:

  1. Open the SSH config file.
  2. Find “PermitRootLogin yes”.
  3. Change it to “PermitRootLogin no”.
  4. Save and exit.

Now, users must log in with a regular account and use sudo for admin tasks. This adds an extra layer of security. It prevents direct root access, making it harder for attackers to gain full system control.

Maintaining SSH Key Access

Proper maintenance of SSH keys is crucial for ongoing security. Regular key rotation and secure backups help protect your Ubuntu 22.04 system from unauthorized access.

Periodic Key Rotation

Key rotation involves replacing old SSH keys with new ones. This practice enhances security by limiting the window of opportunity for potential attackers.

To rotate keys:

  1. Generate a new key pair using ssh-keygen
  2. Add the new public key to authorized_keys file
  3. Test the new key
  4. Remove the old public key from authorized_keys

It’s recommended to rotate keys every 6-12 months. During rotation, temporarily enable password login as a fallback.

RSA keys remain popular, but consider using newer algorithms like Ed25519 for improved security.

Backup of Key Files

Backing up SSH key files prevents loss of access to your systems. Store backups securely, as they grant the same access as the original keys.

Key files to back up:

  • Private key (e.g. id_rsa)
  • Public key (e.g. id_rsa.pub)
  • Known_hosts file
  • Authorized_keys file

Use encrypted storage for backups. Cloud storage or external drives work well, but ensure they’re protected with strong encryption.

Regularly test backups by restoring to a test system. This ensures the backup process works correctly and keys remain valid.

Troubleshooting Common SSH Key Issues

Setting up SSH keys can sometimes lead to unexpected problems. These issues often stem from incorrect configurations or misunderstandings about how SSH works. Let’s explore some common roadblocks and their solutions.

Incorrect File Permissions

SSH is very strict about file permissions for security reasons. If your keys have the wrong permissions, SSH will reject them.

For private keys:

  • They should be readable only by you
  • Set permissions to 600 or 400

For public keys and the authorized_keys file:

  • They should be readable by you and others
  • Set permissions to 644

To fix permissions, use these commands:

chmod 600 ~/.ssh/id_rsa
chmod 644 ~/.ssh/id_rsa.pub
chmod 644 ~/.ssh/authorized_keys

Check if the .ssh folder itself has the right permissions (700). If not, run:

chmod 700 ~/.ssh

Invalid Public Key Format

Sometimes, public keys get corrupted during transfer or editing. This can cause SSH connection issues.

A valid public key should look like this:

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDNqqi1mHLnryb... user@host

It starts with the key type, followed by a long string of characters, and ends with a user and host identifier.

If your key doesn’t match this format, regenerate it using:

ssh-keygen -t rsa -b 4096

Then, copy the new public key to the server.

Connection Refused Errors

When SSH refuses your connection, it might be due to server-side issues.

First, check if the SSH service is running on the server:

sudo systemctl status sshd

If it’s not active, start it:

sudo systemctl start sshd

Next, verify the SSH port. The default is 22, but it might have been changed. Check the SSH config file:

sudo nano /etc/ssh/sshd_config

Look for the “Port” line. If it’s not 22, use the specified port when connecting:

ssh -p PORT_NUMBER user@server

Lastly, ensure the server’s firewall allows SSH connections. On Ubuntu, use:

sudo ufw allow ssh

This opens the default SSH port (22). If using a different port, specify it:

sudo ufw allow PORT_NUMBER/tcp

Supplementary Information

SSH keys offer enhanced security and convenience beyond basic authentication. They can integrate with version control systems and provide additional verification methods.

Using SSH Keys with Git

SSH keys make working with Git repositories more secure and efficient. To use SSH keys with Git, add your public key to your GitHub account settings. Then, clone repositories using the SSH URL instead of HTTPS.

For example:

git clone [email protected]:username/repository.git

This method eliminates the need to enter your password for each Git operation. It’s especially useful for frequent commits and pushes.

GitHub allows multiple SSH keys per account. This feature lets you use different keys for various devices or projects.

SSH Key Fingerprint Verification

Key fingerprints help verify the authenticity of SSH connections. They’re unique identifiers for public keys, typically displayed as a string of characters.

To view your key’s fingerprint, use this command:

ssh-keygen -l -f ~/.ssh/id_rsa.pub

Modern systems often use SHA256 hashes for fingerprints. They appear as a series of base64-encoded characters.

ECDSA key fingerprints are another common type. They’re shorter than RSA fingerprints and offer comparable security.

When connecting to a new server, compare its fingerprint to the expected value. This step helps prevent man-in-the-middle attacks.

Advanced SSH Key Management

SSH keys offer powerful features beyond basic authentication. Let’s explore some advanced techniques for managing multiple keys and accounts.

SSH Agent and SSH-Add for Key Management

The SSH agent streamlines key usage by securely storing private keys in memory. To start the agent, run:

eval $(ssh-agent)

Add keys to the agent with ssh-add:

ssh-add ~/.ssh/id_rsa

This eliminates the need to re-enter passphrases. The agent remembers keys for the current terminal session. Users can add multiple keys and specify which one to use for each connection.

To list loaded keys:

ssh-add -l

Remove a key from the agent:

ssh-add -d ~/.ssh/id_rsa

Using SSH for Multiple Accounts on GitHub

GitHub allows multiple SSH keys for different accounts. This is useful for separating work and personal projects.

Create separate keys for each account:

ssh-keygen -t ed25519 -C "[email protected]" -f ~/.ssh/id_ed25519_work
ssh-keygen -t ed25519 -C "[email protected]" -f ~/.ssh/id_ed25519_personal

Add both keys to the SSH agent:

ssh-add ~/.ssh/id_ed25519_work
ssh-add ~/.ssh/id_ed25519_personal

Configure SSH to use the correct key for each account in ~/.ssh/config:

Host github.com-work
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_ed25519_work

Host github.com-personal
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_ed25519_personal

When cloning repositories, use the appropriate Host:

git clone [email protected]:username/repo.git
git clone [email protected]:username/repo.git

This setup enables seamless switching between GitHub accounts.

Frequently Asked Questions

Setting up SSH keys on Ubuntu 22.04 involves several important steps. Users often have questions about the process, from generating keys to troubleshooting authentication issues.

What are the steps to generate an SSH key pair in Ubuntu 22.04?

To generate an SSH key pair, open a terminal and run the ssh-keygen command. The default options create a 3072-bit RSA key pair.

For added security, users can create a 4096-bit key by adding the -b 4096 flag.

How can I configure the sshd_config file to accept key-based authentication?

The sshd_config file controls SSH server settings. To enable key-based authentication, edit the file and set PasswordAuthentication to no.

This change forces SSH to use key-based authentication instead of passwords.

What is the process to copy my SSH key to a remote Ubuntu server?

The ssh-copy-id command simplifies copying SSH keys. Run ssh-copy-id username@remote_host, replacing the placeholders with the actual username and server address.

This command copies the public key to the server’s authorized_keys file.

How do I verify that key-based SSH authentication is working correctly?

To test key-based authentication, try connecting to the remote server using SSH. If it works without asking for a password, key-based authentication is functioning.

Users can also check the server’s auth.log file for successful key-based logins.

What permissions should I set for my .ssh directory and files in Ubuntu 22.04?

The .ssh directory should have 700 permissions (rwx——). SSH key files should have 600 permissions (rw——-).

These restrictive permissions prevent unauthorized access to sensitive SSH files.

How can I troubleshoot issues with SSH key authentication on Ubuntu?

Check the server’s sshd_config file for correct settings. Ensure the client’s private key file has the right permissions.

Review the server’s auth.log file for error messages. Use SSH’s verbose mode (-v flag) for detailed connection information.

Share this article: