Secure Shell (SSH) is a fundamental protocol for secure remote access to servers and devices. However, when attempting to connect, users often encounter the frustrating “Permission Denied (publickey)” error.

In this article, we’ll explore the reasons behind this error, offer practical solutions, and highlight best practices to prevent its occurrence in the future. Understanding and resolving the “Permission Denied (publickey)” error is essential for system administrators and developers.

Causes of SSH Permission Denied Publickey Error

One of the most common reasons for this error is an incorrect configuration of the public key. Ensure that your SSH server is set to accept the public key you’re using for authentication. Double-check the authorized_keys file in the ~/.ssh directory to ensure your public key is correctly listed.

Other reasons include:

  • Incorrect Key Pair: If key pairs are used for authentication, make sure you’re using the correct private key that matches the public key stored on the server. Mixing up key pairs can lead to authentication failures;
  • File Permissions: SSH has strict file permission requirements. The private key file (~/.ssh/id_rsa or ~/.ssh/id_dsa) should not be readable or writable by anyone except the owner. You can set the correct permissions using the chmod command (chmod 600 ~/.ssh/id_rsa);
  • Incorrect Username: Ensure that you’re using the correct username to log in to the server. If you’re unsure, you can explicitly specify the username in the SSH command (e.g., ssh username@hostname);
  • Firewall Rules: Sometimes, firewall rules can block SSH connections. Check your server’s firewall settings to ensure that SSH traffic is allowed.

In some systems, Security-Enhanced Linux (SELinux) or AppArmor modules may restrict SSH access. Check the status of these security modules and adjust policies if necessary.

Solutions to the SSH Permission Denied Publickey Error

On the server side, various configuration issues can contribute to the ‘SSH Permission Denied Publickey’ error. These can include incorrect permissions in the server’s home directory, improper configuration of the authorized_keys file, or disabling public key authentication in SSH server settings. Fortunately, resolving these issues often involves making changes to the sshd_config file.

Since we’ve already discussed the possible causes of this error, it’s equally important to understand why you encountered the ‘ssh permission denied publickey’ problem from your end. By identifying the specific factors at play in your situation, you can effectively choose the most suitable solution to address it.

Solution 1: Generate and Add SSH Key Pair

Now, let’s proceed with generating and adding an SSH key pair.

Step 1: Check for Existing Keys

Before generating a new SSH key pair, it’s important to check if you already have one. Open a terminal and enter the following command:

ls -al ~/.ssh

This command will display the contents of the ~/.ssh directory. If you see files named id_rsa (private key) and id_rsa.pub (public key), you most likely already have an SSH key pair. You can proceed to Step 3: “Adding Your SSH Key.”

Step 2: Generate an SSH Key Pair

If you don’t have an SSH key pair or want to create a new one, follow these steps:

Open a terminal.

Use the ssh-keygen command to generate a new SSH key pair. By default, a 2048-bit RSA key pair is created, which is secure for most purposes. You can also specify a different key type using the -t option (e.g., -t ed25519 for an Ed25519 key).

ssh-keygen -t rsa -b 2048

You’ll be prompted to choose a location to save the key pair. Press Enter to save it in the default ~/.ssh directory.

Optionally, you can set a passphrase for the private key. While not mandatory, it adds an extra layer of security. If you choose to use a passphrase, make sure it’s strong and memorable.

A new SSH key pair is generated. The private key is saved in the ~/.ssh/id_rsa file, and the public key is saved in the ~/.ssh/id_rsa.pub file.

Step 3: Adding Your SSH Key

Now that you have an SSH key pair, you need to add the public key to the remote server or service where authentication is required. Here’s how to do it:

Copy the public key to your clipboard. You can display it using the cat command and then select and copy it.

cat ~/.ssh/id_rsa.pub

Navigate to the location where you can add SSH keys. This depends on the service or server. For example, on a remote Linux server, you typically add the key to the ~/.ssh/authorized_keys file in the user’s home directory.

If the ~/.ssh directory or the authorized_keys file doesn’t exist, you can create them with the following commands:

mkdir -p ~/.ssh

touch ~/.ssh/authorized_keys

Save your changes and exit the text editor.

Set the correct permissions for the ~/.ssh directory and the authorized_keys file:

chmod 700 ~/.ssh

chmod 600 ~/.ssh/authorized_keys

Step 4: Test Your SSH Key

To ensure that your SSH key is set up correctly and working, follow these steps:

Open a terminal.

Use the ssh command to connect to the remote server or service:

ssh username@hostname

Replace the username with the remote server’s username and hostname with the server’s address or domain name.

If you set a passphrase for your private key, you’ll be prompted to enter it. Otherwise, you’ll log in without entering a password.

Now you’ve successfully generated and added an SSH key pair. You can now enjoy the security and convenience of SSH key-based authentication for your remote connections.

Solution 2: Set the Correct Permissions

When it comes to data and system security, setting the correct file permissions is one of the fundamental aspects of file management. Properly configuring file and directory access permissions not only ensures the protection of confidential information but also guarantees that users and processes can access the files they need while preventing unauthorized access. 

We’ll discuss the importance of permissions, how they work, and best practices for configuring them on different platforms.

Understanding File and Directory Permissions

File and directory permissions determine who can perform specific actions on files and directories. These actions typically include:

  • Read: The ability to view the contents of a file or list the contents of a directory;
  • Write: The ability to modify the contents of a file or create, delete, and modify files within a directory;
  • Execute: The ability to run a file or access the contents of a directory.

Permissions are usually assigned to three categories of users:

  • Owner (User): The user who owns the file or directory;
  • Group: A specific group of users who have similar access rights;
  • Others (World): All other system users who are neither the owners nor members of the specified group.

Setting Permissions on Unix-like Systems (Linux, macOS)

On Unix-like systems, permission management can be done using symbolic notation or numerical values. Here’s how to use symbolic notation:

Symbolic Notation:

  • r: Permission to read;
  • w: Permission to write;
  • x: Permission to execute;
  • +: Adds permission;
  • -: Removes permission;
  • =: Sets permission explicitly.

For example, to grant the owner read and write permissions for a file named example.txt, you can use the following command:

  • chmod u+rw example.txt;
  • 4 represents read permission;
  • 2 represents write permission;
  • 1 represents execute permission.

To set permissions for reading and writing for the owner, writing for the group, and execution for others, you can use the following command:

chmod 741 example.txt

Solution 3: Configure the SSH Config File at Server’s End (sshd_config)

When it comes to securing remote access to a server, the configuration of the SSH server is of paramount importance. The sshd_config file plays a central role in defining the behavior and security settings of the SSH server. 

We will explore the significance of sshd_config, its key directives, and the best methods for configuring it to enhance server security and functionality.

Accessing sshd_config

To access and edit the sshd_config file on Unix-like systems, root or superuser privileges are typically required. Text editors like vi, nano, or gedit can be used to make changes. The location of the sshd_config file may vary slightly depending on the Linux distribution, but it is commonly found at /etc/ssh/sshd_config.

Here is an example of opening sshd_config for editing using nano:

sudo nano /etc/ssh/sshd_config

Key Directives in sshd_config

sshd_config contains numerous directives that define the behavior of the SSH server. Let’s explore some of the most important ones:

  • Port: This directive specifies the port number on which the SSH server operates. The default value is 22, but changing it to a non-standard port can enhance security by reducing the number of automated scanning attempts;
  • Port 2222;
  • PermitRootLogin: Determines whether the root user can log in directly via SSH. It is usually recommended to set this to “no” and use sudo for administrative tasks;
  • PermitRootLogin no;
  • PasswordAuthentication: Sets whether password authentication is allowed. To enhance security, set this to “no” and use key-based authentication;
  • PasswordAuthentication no;
  • AllowUsers and AllowGroups: These directives specify which users or groups are allowed to access the system via SSH. By default, SSH allows access to all users, so it is advisable to restrict access to specific accounts;
  • AllowUsers alice bob;
  • AllowTcpForwarding: Determines whether SSH tunneling is allowed. Tunneling can be used for secure access to remote resources, but it should be restricted to trusted users;
  • AllowTcpForwarding yes;
  • X11Forwarding: Specifies whether X11 graphics forwarding is allowed. Disable this option for security reasons if it’s not needed;
  • X11Forwarding no;
  • PubkeyAuthentication: Ensure that authentication is allowed only with public keys. This is a recommended security measure;
  • PubkeyAuthentication yes;
  • Banner: Specifies the text file to display before the login prompt. Useful for showing legal notices or warnings;
  • Banner /etc/ssh/banner.txt;
  • Best Practices for sshd_config;

To maximize the security and efficiency of your SSH server configuration, consider the following best practices:

  • Regular Backups: Before making changes, create a backup of the sshd_config file. This will make it easy to restore the configuration in case of errors;
  • Minimize Open Ports: Limit the number of open ports by configuring only the necessary services. This reduces the attack surface;
  • Use Strong Passwords: If password authentication is enabled, ensure that users have strong and unique passwords;
  • Implement Two-Factor Authentication (2FA): If possible, enable 2FA for SSH access to provide an additional layer of security;
  • Monitor Logs: Regularly review SSH server logs for unusual activity or login attempts. Tools like fail2ban can help combat brute-force attacks;
  • Stay Updated: Keep your SSH server software and operating system up to date with security patches;
  • Limit User Count: Restrict the number of users with SSH access and regularly review and remove unnecessary accounts;
  • Maintain Clear Documentation: Keep clear documentation of changes made to sshd_config and the reasons behind those changes for future reference.

Conclusion

The “Permission Denied (publickey)” error in SSH can be frustrating, but with a clear understanding of its causes and the right troubleshooting steps, it can be effectively resolved. By following best practices for SSH key management and server configuration, you can minimize the likelihood of encountering this error in the future.

SSH remains a critical tool for secure remote access, and proficiency in authentication methods, including public key authentication, is essential for those working in system administration and managing secure servers. 

Armed with the knowledge presented in this article, users can confidently overcome challenges related to SSH authentication errors, ensuring secure and reliable access to their remote servers and devices.