AWSJunior

EC2 SSH: Permission denied (publickey) and unprotected key file

Permission denied (publickey) means the server refused your key. Check the username for the AMI, the right .pem file, its 0400 permissions and the .ssh modes.

What you see

  • Permission denied (publickey).
  • Host key not found in [directory]
  • Connection closed by [instance] port 22
  • WARNING: UNPROTECTED PRIVATE KEY FILE! followed by Permissions 0777 for '.ssh/my_private_key.pem' are too open.

What it means

You reached the instance, but authentication failed. Three things cause nearly all of it: the wrong username for the AMI, the wrong private key, or key file permissions that are too open, in which case SSH ignores the key.

How to confirm the cause

  1. 1
    Run SSH with maximum detail
    ssh -vvv -i /path/key-pair-name.pem USER@ec2-203-0-113-25.compute-1.amazonaws.com

    A key the server does not accept ends with Permission denied (publickey).

  2. 2
    Check which key pair the instance was launched with
    aws ec2 describe-instances --instance-ids INSTANCE_ID --query 'Reservations[].Instances[].KeyName'

Causes and fixes

  • Wrong username for the AMI

    HOW TO TELL
    Connecting as the wrong user.
    FIX
    Use the default user for the image: Amazon Linux ec2-user, Ubuntu ubuntu, Debian admin, RHEL ec2-user or root, SUSE ec2-user or root, Rocky Linux rocky, Bitnami bitnami. For other images check with the AMI provider.
  • Private key file is too open

    HOW TO TELL
    The UNPROTECTED PRIVATE KEY FILE warning, or the key is silently ignored.
    FIX
    Make the key readable only by you.
    chmod 0400 .ssh/my_private_key.pem
  • Wrong key pair

    HOW TO TELL
    The key name on the instance differs from the .pem you are using.
    FIX
    Use the file that matches the key pair shown for the instance. If you generated your own key, it must be RSA; DSA keys are not accepted.
  • Permissions changed on the instance

    HOW TO TELL
    It used to work and nothing else is wrong.
    FIX
    authorized_keys must be limited to the owner. Stop the instance, attach its root volume to a temporary instance in the same Availability Zone, and fix the modes, then reattach the volume.
    chmod 600 MOUNT/home/USER/.ssh/authorized_keys
    chmod 700 MOUNT/home/USER/.ssh
    chmod 700 MOUNT/home/USER

How to stop it coming back

  • Store the .pem with 0400 from the day you download it.
  • Document the default user per image your team uses.
  • Keep a break-glass path, such as Session Manager, so a lost key is not an outage.

Keep going

Sources

AWS documentation (docs.aws.amazon.com), read 18 Nov 2026.

Search

Search cheat sheets and projects