How to Fix Permission Error When SSH into Amazon EC2 Instance

Are you new to AWS and facing the dreaded “unprotected private key file” error when connecting to your EC2 instance via SSH? This guide will troubleshoot the issue and ensure a secure connection.

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ WARNING: UNPROTECTED PRIVATE KEY FILE! @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions for 'aws-key.pem' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
Load key "aws-key.pem": bad permissions ubuntu@ec2-255-255-255-255.compute-1.amazonaws.com: Permission denied (publickey).

Why You Get This Error

For security reasons, EC2 instances reject private key files (.pem) with public read permissions. By default, these files might reside in easily accessible folders like Desktop or Downloads, making them vulnerable. This security measure by the server prevents unauthorized access.

Fixing the Error: Step-by-Step

macOS:

  1. Locate Your Key File: Find the .pem file you use for SSH access. Its location doesn’t matter, but remember it for the next step.

  2. Open Terminal and Set Permissions: Launch the Terminal application. Here, type chmod 400 followed by a space.

  3. Drag and Drop for Efficiency (Optional): Drag and drop your .pem file directly onto the Terminal window after the space you created in step 2. This automatically fills the file path.

  4. Verify the Command (Optional): The command should resemble chmod 400 /Users/username/Documents/aws-key.pem (replace placeholders with your actual details).

  5. Execute the Command: Press Enter. Terminal won’t provide any confirmation, but the process is complete.

Choosing the Right Permissions

  • chmod 400 (Recommended): This grants read-only access only to the file owner, offering the highest security (unless you need to edit the file).
  • chmod 600 (For Editing): If you plan to modify the .pem file later, use this option. It allows read-write access for the owner.

Windows:

  1. Locate Your Key File: Find the .pem file you use for SSH access. Load the location in a variable $path as below.
    $path = ".\aws-key.pem"
  2. Reset: remove explict permissions on the file
    icacls.exe $path /reset
  3. Permission: Give current user explicit read-permission
    icacls.exe $path /GRANT:R "%username%:(r)"
  4. Disable inheritance: Remove files inherited permissions
    icacls.exe $path /inheritance:r