How to Fix SSH ‘Permission denied (publickey)’ Authentication Failures

 Encountering a “Permission denied (publickey, …)” error when attempting to connect to a remote server via SSH using key-based authentication is a frequent challenge.

This typically occurs after setting up SSH keys and attempting the initial connection, or when configurations change. This guide explores the common causes behind this error and presents practical solutions derived from established troubleshooting procedures.

Understanding the Common Causes

Several factors can lead to the SSH daemon (sshd) on the server rejecting a public key authentication attempt. These often relate to configuration, permissions, or key management:

  • Incorrect File Permissions: The SSH daemon is strict about permissions on the server, particularly for the user’s home directory, the ~/.ssh directory, and the authorized_keys file. Overly permissive settings will cause authentication to fail. Client-side private key files also require restricted permissions.
  • Incorrect File/Directory Ownership: Similar to permissions, the ownership of the user’s home directory, ~/.ssh directory, and its contents on the server must belong to the connecting user.
  • Key Management Issues: The server might not have the correct public key, the key might be improperly formatted in the authorized_keys file, or the client might be presenting the wrong private key.
  • Client Configuration: The SSH client may not be configured to use the intended private key, especially if non-default key names or multiple keys are involved.
  • Server Configuration (`sshd_config`): Settings within the main SSH daemon configuration file (/etc/ssh/sshd_config) can prevent key authentication. This includes specifying an incorrect path for authorized keys, restricting user access, or disabling certain authentication methods.
  • Username Mismatches: Simple issues like case sensitivity in usernames (e.g., ‘User’ vs. ‘user’) or forgetting to specify the user in the SSH command can lead to denial.
  • Outdated Cryptographic Algorithms: Newer SSH versions may deprecate older algorithms like RSA by default, leading to connection failures if the key type is no longer mutually supported.

SSH Authentication Failures

Read: How to Fix npm EACCES Permission Denied Errors for /usr/local/lib/node_modules

Troubleshooting Steps and Solutions

Addressing the “Permission denied” error involves systematically checking potential causes on both the client and server machines.

SSH Authentication Troubleshooting Flowchart

1. Verify Key Generation and Transfer

Ensure the fundamental key setup is correct.

  • Generate Key Pair (if needed): If starting fresh, generate a new key pair.
    ssh-keygen
  • Copy Public Key to Server: Use `ssh-copy-id` for reliable transfer, which also sets correct permissions for `authorized_keys`. Replace placeholders appropriately.
    ssh-copy-id -i /path/to/your/public_key.pub #USERNAME#@#SERVER_ADDRESS#

    Alternatively, manually append the public key content (ensure the entire key, including the ‘ssh-rsa’ or ‘ssh-ed25519’ prefix, is copied) to the ‘~/.ssh/authorized_keys’ file on the server:

    echo 'public_key_string' >> ~/.ssh/authorized_keys
  • Check Key Format: Manually inspect the `~/.ssh/authorized_keys` file on the server. Ensure each key starts with the algorithm type (e.g., `ssh-rsa`, `ssh-ed25519`) and is on a single line. Accidental omission of the prefix can cause failure.
  • Specify Correct Key during Copy: If multiple keys exist, ensure you copied the intended public key using the `-i` flag with `ssh-copy-id`.
    ssh-copy-id -i /path/to/CORRECT_KEY.pub #USERNAME#@#SERVER_ADDRESS#

2. Correct Server-Side Permissions and Ownership

Incorrect permissions or ownership on the server are very common culprits.

  • Set `~/.ssh` Directory Permissions: Must be readable, writable, and executable only by the user.
    chmod 700 ~/.ssh
  • Set `authorized_keys` File Permissions: Must be readable and writable only by the user.
    chmod 600 ~/.ssh/authorized_keys

    (Note: If using an alternate name like `authorized_keys2`, adjust the command accordingly).

  • Set Ownership: Ensure the user owns their `.ssh` directory and its contents. Replace `#your_user#` with the actual username.
    chown -R #your_user#:#your_user# ~/.ssh
  • Check Home Directory Permissions/Ownership: The user’s home directory itself should generally not be world-writable. Ensure it belongs to the correct user. Excessive permissions (like 777) can cause SSH failure.
    sudo chown #username#:#username# /home/#username#
    # Example: chmod 755 /home/#username# (Avoid 777)
  • Initial User Setup (e.g., Cloud Instances): When setting up a new user on a server initially accessed via root with SSH keys, ensure the root user’s `.ssh` configuration (containing the authorized key) is correctly copied and owned by the new user.
    # Run as root after creating the new user
    rsync --archive --chown=#user#:#user# ~/.ssh /home/#user#/

    Replace `#user#` with the new username.

SSH Key Authentication Lifecycle

SSH Key Authentication Lifecycle

Read: How to Fix SSH ‘Permission denied (publickey)’ Authentication Failures

3. Correct Client-Side Permissions

The private key on the client machine also requires strict permissions.

  • Ensure the ~/.ssh directory has 700 permissions.
  • Ensure the private key file (e.g., ~/.ssh/id_rsa) has 600 permissions. `ssh-keygen` typically sets these correctly.

4. Configure the SSH Client

Tell the client explicitly which key to use, especially if not using default names (`id_rsa`).

  • Specify Key via Command Line: Use the `-i` flag. Ensure you point to the *private* key file.
    ssh -i /path/to/your/private_key #USERNAME#@#SERVER_ADDRESS#
  • Use SSH Config File (`~/.ssh/config`): Define host-specific settings for easier connections.
    Host #SERVER_NICKNAME#
        Hostname #SERVER_ADDRESS_OR_IP#
        User #USERNAME#
        PubKeyAuthentication yes
        IdentityFile /path/to/your/private_key
        # Optional: Use IdentitiesOnly to prevent trying default keys
        IdentitiesOnly yes 

    Ensure `IdentityFile` points to the *private* key. Using `IdentitiesOnly yes` can prevent issues if multiple keys exist and avoids potential authentication failures from trying incorrect keys first. It’s also considered more secure.

  • Add Key to SSH Agent: If the key has a passphrase, add it to the agent to avoid retyping it. The agent manages keys currently in use.
    ssh-add /path/to/your/private_key

    Note: If a key is added, `ssh` might prioritize keys known by the agent. If you add a new default key (`~/.ssh/id_rsa`), you might need to run `ssh-add` again for the agent to recognize it.

SSH File Permissions Reference Table

5. Adjust Server SSH Configuration (`/etc/ssh/sshd_config`)

Server-side settings can override default behaviors.

  • Check `AuthorizedKeysFile` Path: Verify this line points to the correct location relative to the user’s home directory (`%h`). Ensure it’s not commented out. Common paths are `%h/.ssh/authorized_keys` or sometimes `%h/.ssh/authorized_keys2`.
    AuthorizedKeysFile    %h/.ssh/authorized_keys
  • Check User/Group Restrictions: Look for `AllowUsers` or `AllowGroups` directives. If present, ensure the connecting user (or their group) is listed (entries are space-delimited).
    AllowUsers user1 user2 #your_user#
    AllowGroups sshgroup #your_group#
  • Consider `PasswordAuthentication` Setting: While the goal is key-based auth, sometimes temporarily enabling password authentication (`PasswordAuthentication yes`) can help in initial setup or troubleshooting access issues, especially if `ssh-copy-id` failed due to password auth being disabled. Remember to consider security implications and potentially disable it again (`PasswordAuthentication no`) once key auth works.
  • Review `UsePAM` Setting: In some specific scenarios, changing `UsePAM yes` to `UsePAM no` was reported to resolve issues, potentially alongside enabling password authentication temporarily. Evaluate carefully as PAM involves pluggable authentication modules.
  • Restart SSH Service: After any changes to `sshd_config`, reload or restart the SSH service to apply them. The command may vary (e.g., `sudo systemctl reload sshd`, `sudo service ssh reload`, `sudo service sshd reload`).
    sudo service sshd reload

SSH Configuration Parameters Reference

6. Address Username and Command Issues

Simple mistakes in the command can cause failures.

  • Verify Username Case Sensitivity: Some systems (like Cygwin environments) might be case-sensitive regarding usernames in home directory paths. Ensure the username case in the SSH command matches the server’s expected case (e.g., `Administrator` vs. `administrator`).
  • Specify the User: Always include the username in the connection command, especially if the local username differs from the remote one.
    ssh #USERNAME#@#SERVER_ADDRESS# -i /path/to/private_key

7. Check for Algorithm Compatibility

If you encounter `debug1: send_pubkey_test: no mutual signature algorithm` in verbose output, the key type might be outdated (e.g., older RSA keys).

  • Regenerate Key with Modern Algorithm: Use ED25519 or newer RSA standards.
    ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519 -C "Your descriptive comment"

    Remember to copy the new `.pub` key to the server’s `authorized_keys` file.

Verification and Further Diagnosis

To understand why a connection is failing:

  • Client-Side Verbose Output: Use the `-vvv` flag with your SSH command to get detailed debugging information from the client’s perspective. This shows which keys are being attempted and where the process fails.
    ssh -vvv -i /path/to/private_key #USERNAME#@#SERVER_ADDRESS#
  • Server-Side Logs: Monitor the authentication log on the server in real-time as users attempt to connect. This often provides explicit reasons for failure (e.g., bad permissions, user not found, key rejected).
    tail -f /var/log/auth.log

    (The log file path might differ slightly based on the Linux distribution).

  • Increase Server Log Verbosity: For even more detail on the server side, temporarily increase the log level in `/etc/ssh/sshd_config`.
    LogLevel DEBUG2

    Remember to restart the SSH service after changing this setting and revert it later to avoid excessively large log files.

Conclusion

The “Permission denied (publickey)” error during SSH authentication, while common, is usually solvable through systematic checks. The most frequent causes involve incorrect file permissions and ownership on the server, improperly managed SSH keys (missing, corrupted, or wrong key used), or specific server/client configuration directives.

By carefully verifying permissions, ownership, key placement, client configuration, and server settings (`sshd_config`), and utilizing diagnostic tools like verbose output (`-vvv`) and server logs, these authentication issues can typically be identified and resolved effectively.

 


If you like the content, we would appreciate your support by buying us a coffee. Thank you so much for your visit and support.

 

Leave a Reply