ag@linux:~$

history 12 of 36

Fixing Amazon AWS SSH Permission Denied Errors

Why SSH to an AWS EC2 Linux instance fails with Permission denied, and how to fix it with the right .pem file permissions and login user name.

Written

From my Linux study notes, 2014. Some commands and versions here are old, so please reuse them carefully. Anything marked "added later", and the notes at the end, explain what has changed since.

These are the most asked questions when setting up Linux on Amazon AWS. When you launch an EC2 instance, AWS gives you a key pair file ending in .pem. You log in with that file instead of a password, and SSH is strict about how the file is stored.

The fix

  1. Store the .pem file in your .ssh folder and set its file permissions to 600:

    Terminal window
    chmod 600 ~/path/my-key-pair.pem

    600 means only you can read and write the file. If other users can read your private key, SSH refuses to use it and you get a warning such as UNPROTECTED PRIVATE KEY FILE! followed by Permission denied. AWS’s own guides also accept 400 (read-only for you).

  2. Now log in:

    Terminal window
    ssh -i /path/my-key-pair.pem [email protected]
    • -i tells SSH which private key file to use.
    • ec2-user is the login user name.
    • The last part is your instance’s public DNS name (or public IP), shown in the EC2 console. The address above is only an example.

Other common causes of Permission denied

  • Wrong user name. The user depends on the image (AMI) you launched. ec2-user is used on Amazon Linux, ubuntu on Ubuntu images and admin on Debian images. For other images, check the image’s documentation. root login is normally not allowed.
  • Wrong key. You must use the key pair that was chosen when the instance was launched.
  • Key file on a Windows or shared drive. Some file systems cannot store Linux permissions, so chmod 600 has no effect. Keep the key in your home folder.
  • Connection timed out (rather than Permission denied) usually means the instance’s security group does not allow inbound SSH on port 22 from your IP address.

To see more detail about what is failing, add -v:

Terminal window
ssh -v -i /path/my-key-pair.pem ec2-user@your-instance-address

Making it easier

If you connect often, add an entry to ~/.ssh/config on your computer:

Host myserver
HostName ec2-198-51-100-1.compute-1.amazonaws.com
User ec2-user
IdentityFile ~/.ssh/my-key-pair.pem

Then you can connect with just ssh myserver. The ~/.ssh folder itself should have permissions 700 (chmod 700 ~/.ssh).

Notes for today

  • Security: keep your .pem file private and backed up somewhere safe. AWS does not keep a copy, so if you lose it you cannot download it again.
  • Only allow SSH from the IP addresses that need it in the security group, rather than from everywhere.
  • Documentation: https://docs.aws.amazon.com/