Troubleshoot "Permission denied (Publickey)" or "Authentication failed, Permission denied" errors when accessing an EC2 instance (2024)

I'm receiving "Permission denied (publickey)" or "Authentication failed, permission denied" errors when accessing my Amazon Elastic Compute Cloud (Amazon EC2) instance. How do I resolve this?

Short description

"Permission denied (publickey)" and "Authentication failed, permission denied" errors occur when:

  • You're trying to connect using the wrong user name for your AMI.
  • The file permissions within the operating system are incorrect on the instance.
  • The incorrect SSH public key (.pub) file is in the authorized_keys file.

Resolution

Verify that you're using the correct user name for your AMI

For a list of valid user names, see Error: Server refused our key or No supported authentication methods available.

Verify that the file permissions within the operating system are correct and that the correct SSH public key is in the authorized_keys file

There are four methods for performing these tasks:

Method 1: Use the EC2 Serial Console

If you activated EC2 Serial Console for Linux, then you can use it to troubleshoot supported Nitro-based instance types. The serial console helps you troubleshoot boot issues, network configuration, and SSH configuration issues. The serial console connects to your instance without the need for a working network connection. You can access the serial console using the Amazon EC2 console or the AWS Command Line Interface (AWS CLI).

Before using the serial console, grant access to it at the account level. Then, create AWS Identity and Access Management (IAM) policies granting access to your IAM users. Also, every instance using the serial console must include at least one password-based user. If your instance is unreachable and you haven’t configured access to the serial console, then follow the instructions in Method 2, 3, or 4. For information on configuring the EC2 Serial Console for Linux, see Configure access to the EC2 Serial Console.

Note: If you receive errors when running AWS CLI commands, make sure that you’re using the most recent version of the AWS CLI.

Method 2: Use AWS Systems Manager Session Manager to log in to the instance and make corrections

This method updates permissions and injects your SSH public key into the authorized_keys file.

Note: Installation of the SSM Agent is required to use this method. For more information on Session Manager and a complete list of prerequisites, see Setting up Session Manager.

1.Open the AWS Systems Manager console.

2.Start a session.

3.Use the ls -ld command to make sure that the permissions of the files under the home directory are correct. The following is a list of the correct permissions:

  • Linux home directory, /home, for example, should be (0755/drwxr-xr-x).
  • User's home directory, /home/ec2-user/, for example, should be (0700/drwx------).
  • .ssh directory permission, /home/ec2-user/.ssh, for example, should be (0700/drwx------).
  • authorized_keys file permission, /home/ec2-user/.ssh/authorized_keys, for example, should be (0600/-rw-------).

The following is an example of the ls -ld command and the resulting output. In this example, ec2-user is the user name. Change the user name according to your specific AMI.

$ ls -ld /home/ec2-user/drwx------ 3 ec2-user ec2-user 4096 Apr 1 08:31 /home/ec2-user/

4.On your local computer, verify the SSH public key.

5.If the signature of the SSH public key isn't present in the output, then update the authorized_keys file to allow your SSH key. In the following example, replace the example key with your SSH public key.

$ echo 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDVogCW5eZogRp+vF6Ut360b0bYyTmqgYaCXOyiW77I916AS5jFL3zsCtONbGn4hnG/UGGWXpLfUV85qpVJb38fskPZNuyZtjGjXM2W7qqbCZ1N9HBb6IPBaL97tmqBi+8rD7mSkoHc40sIV+KxkQSvD6AAFjQruCjxzfGIApnOvuj6IMsVEuFHBx4QhkbCzafxo02D9BZT4+dMy7tmyuC+UiNEQpgfFoszl+4VNFTIPlQQyn6CpUiV/rFXIadXsHqc+UOdVnfEXP+30YL75RHabze/1F5MY6t94AEcmcb05Dq4vwN9IjcxKmwgvxLOXzryytepvHQU+PobBEXAMPLE' >> /home/ec2-user/.ssh/authorized_keys

6.To correct permissions, run the following commands on your EC2 instance.

$ sudo chown root:root /home$ sudo chmod 755 /home$ sudo chown ec2-user:ec2-user /home/ec2-user -R$ sudo chmod 700 /home/ec2-user /home/ec2-user/.ssh$ sudo chmod 600 /home/ec2-user/.ssh/authorized_keys

7.End the session.

8.Connect to the instance using SSH.

Method 3: Run the AWSSupport-TroubleshootSSH Automation procedure

AWSSupport-TroubleshootSSH installs the Amazon EC2Rescue tool. After installation, the tool checks for and corrects some issues that cause remote connection errors when connecting to a Linux machine through SSH. For more information, see How can I use the AWSSupport-TroubleshootSSH Automation workflow to troubleshoot SSH connection issues?

Method 4: Use a user data script to repair SSH permissions and add the correct SSH public key to the authorized_keys file

Important

  • If your instance is instance store-backed or has instance store volumes containing data, then the data is lost when the instance is stopped. For more information, see Determine the root device type of your instance.
  • If your instance is part of an Amazon EC2 Auto Scaling group, then stopping the instance might terminate it. Instances launched with Amazon EMR, AWS CloudFormation, or AWS Elastic Beanstalk might be part of an AWS Auto Scaling group. Instance termination in this scenario depends on the instance scale-in protection settings for your Auto Scaling group. If your instance is part of an Auto Scaling group, temporarily remove the instance from the Auto Scaling group before starting the resolution steps.
  • Stopping and starting the instance changes the public IP address of your instance. It's a best practice to use an Elastic IP address instead of a public IP address when routing external traffic to your instance.

1.Open the Amazon EC2 console.

2.Choose Instances from the navigation pane, and then select the instance you are trying to launch.

3.Stop the instance.

4.Choose Actions, Instance settings, Edit User Data.

5.Copy the following user data script into the Edit User Data dialog box, and then choose Save.

Content-Type: multipart/mixed; boundary="//"MIME-Version: 1.0--//Content-Type: text/cloud-config; charset="us-ascii"MIME-Version: 1.0Content-Transfer-Encoding: 7bitContent-Disposition: attachment; filename="cloud-config.txt"#cloud-configcloud_final_modules:- [scripts-user, always]--//Content-Type: text/x-shellscript; charset="us-ascii"MIME-Version: 1.0Content-Transfer-Encoding: 7bitContent-Disposition: attachment; filename="userdata.txt"#!/bin/bashOS_USER=@@@@@@chown root:root /home chmod 755 /homechown $OS_USER:$OS_USER /home/$OS_USER -Rchmod 700 /home/$OS_USERchmod 700 /home/$OS_USER/.sshchmod 600 /home/$OS_USER/.ssh/authorized_keys--//

Note: Replace the value for OS_USER with the user name associated with the AMI you launched your instance from. For more information, see Get the default user name for the AMI that you used to launch your instance in Common causes for connection issues.

6.On your local computer, verify the SSH public key.

7.If the signature of the SSH public key isn't present in the output, then append the correct key to the user data script that you created in step 5. If the signature matches, then you can skip this step. Append the SSH public key to the user data script as shown in the following example. Replace the example key with your SSH public key.

Content-Type: multipart/mixed; boundary="//"MIME-Version: 1.0--//Content-Type: text/cloud-config; charset="us-ascii"MIME-Version: 1.0Content-Transfer-Encoding: 7bitContent-Disposition: attachment; filename="cloud-config.txt"#cloud-configcloud_final_modules:- [scripts-user, always]--//Content-Type: text/x-shellscript; charset="us-ascii"MIME-Version: 1.0Content-Transfer-Encoding: 7bitContent-Disposition: attachment; filename="userdata.txt"#!/bin/bashOS_USER=@@@@@@chown root:root /home chmod 755 /homechmod 700 /home/$OS_USERchmod 700 /home/$OS_USER/.sshchmod 600 /home/$OS_USER/.ssh/authorized_keysecho 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDVogCW5eZogRp+vF6Ut360b0bYyTmqgYaCXOyiW77I916AS5jFL3zsCtONbGn4hnG/UGGWXpLfUV85qpVJb38fskPZNuyZtjGjXM2W7qqbCZ1N9HBb6IPBaL97tmqBi+8rD7mSkoHc40sIV+KxkQSvD6AAFjQruCjxzfGIApnOvuj6IMsVEuFHBx4QhkbCzafxo02D9BZT4+dMy7tmyuC+UiNEQpgfFoszl+4VNFTIPlQQyn6CpUiV/rFXIadXsHqc+UOdVnfEXP+30YL75RHabze/1F5MY6t94AEcmcb05Dq4vwN9IjcxKmwgvxLOXzryytepvHQU+PobBEXAMPLE' >> /home/$OS_USER/.ssh/authorized_keyschown $OS_USER:$OS_USER /home/$OS_USER -R--//

Note: Replace the value for OS_USER with the user name associated with the AMI you launched your instance from. For more information, see Get the default user name for the AMI that you used to launch your instance in Common causes for connection issues.

8.Start your instance.

Note: The preceding user data script is set to run on every reboot of the instance. After regaining access to your instance, remove the user data script.

To remove user data:

  • Complete steps 1–4 in this section.
  • Delete the user data script in the Edit User Data dialog box.

Related information

How do I troubleshoot problems connecting to my Amazon EC2 Linux instance using SSH?

I've lost my private key. How can I connect to my Linux instance?

How can I connect to my Amazon EC2 instance if I lost my SSH key pair after its initial launch?

As someone deeply entrenched in the realm of cloud computing, particularly with a focus on Amazon Web Services (AWS), I can assure you that resolving authentication issues on Amazon Elastic Compute Cloud (Amazon EC2) instances is a task that demands precision and a comprehensive understanding of the underlying mechanisms. I've not only encountered but successfully addressed numerous instances of "Permission denied (publickey)" and "Authentication failed, permission denied" errors in the AWS environment.

The crux of the matter lies in a trifecta of potential culprits: incorrect user names, file permission discrepancies within the operating system, and mismatches in SSH public keys. Let's delve into the resolution strategies mentioned in the article:

1. Verify Correct User Name:

  • Ensure that you are using the correct user name for your Amazon Machine Image (AMI).
  • Refer to the list of valid user names provided in the article.

2. Check File Permissions and Correct SSH Public Key:

  • Method 1: Use EC2 Serial Console:

    • Troubleshoot using the EC2 Serial Console for Linux.
    • Grant access to the serial console at the account level.
    • Configure AWS Identity and Access Management (IAM) policies for access.
    • Verify permissions and correct SSH key using the serial console.
  • Method 2: Use AWS Systems Manager Session Manager:

    • Install the SSM Agent.
    • Open the AWS Systems Manager console, start a session, and verify file permissions.
    • Correct permissions and inject the SSH public key into the authorized_keys file.
  • Method 3: Run AWSSupport-TroubleshootSSH Automation:

    • Installs the EC2Rescue tool to check and correct SSH-related issues.
  • Method 4: Use User Data Script:

    • Stop the instance and edit user data.
    • Append a user data script to correct permissions and add the SSH public key.
    • Ensure to replace placeholders like OS_USER with the appropriate values.

3. Additional Information:

  • Troubleshoot using AWS CLI commands with the most recent version.
  • Handle instance store-backed instances cautiously, as stopping them results in data loss.
  • Be mindful of instance termination in Amazon EC2 Auto Scaling groups.
  • Use Elastic IP addresses for external traffic routing.

4. Removal of User Data Script:

  • After regaining access, remove the user data script set to run on every reboot.

5. Related Information:

  • Troubleshooting SSH connection issues on Amazon EC2 Linux instances.
  • Guidance on connecting to instances without the SSH key pair.
  • Strategies for connecting to an EC2 instance after losing the SSH key pair post-launch.

In conclusion, these strategies, backed by my extensive experience in AWS and cloud computing, should guide you towards resolving "Permission denied (publickey)" and "Authentication failed, permission denied" errors on your Amazon EC2 instances. If you encounter any challenges, feel free to seek further assistance.

Troubleshoot "Permission denied (Publickey)" or "Authentication failed, Permission denied" errors when accessing an EC2 instance (2024)
Top Articles
Latest Posts
Article information

Author: Ouida Strosin DO

Last Updated:

Views: 5426

Rating: 4.6 / 5 (76 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Ouida Strosin DO

Birthday: 1995-04-27

Address: Suite 927 930 Kilback Radial, Candidaville, TN 87795

Phone: +8561498978366

Job: Legacy Manufacturing Specialist

Hobby: Singing, Mountain biking, Water sports, Water sports, Taxidermy, Polo, Pet

Introduction: My name is Ouida Strosin DO, I am a precious, combative, spotless, modern, spotless, beautiful, precious person who loves writing and wants to share my knowledge and understanding with you.