Connect to Linux EC2 Instance if Key pair is lost after Initial Launch

Use Case

We know that EC2 Linux instances are accessible through the private keys by default. However, SSH is allowed but you cannot use SSH password authentication to access Linux instance as it is disabled by default. So, what would happen if you lose the private key of your Linux instance? In this blog, I will walk you through the easiest ways to login when you lost the Key pair

What is a key-pair file?

Key-pair is a combination of a public and private key. Amazon EC2 uses public-key cryptography to encrypt and decrypt login information. Private key is only the way to get access to the instance, what if you lost the key? Is your servers lost in black hole? Thankfully nothing is lost you still can access your server, let me show you how can you solve this problem.

Things that you should know before to proceed to this topic

  • This procedure will requires start and stop of your instance. Hence, please keep in mind that data in instance store volumes will be lost. Make sure that you backup any data on the instance store volume that you want to keep
  • Stopping and starting the instance changes the public IP address of the instance. Its a best practice to use an Elastic IP address instead of a public IP address when routing external traffic to your instance

Methods

Method 1: Using user data

Create a new key pair. This can be done in two ways
  1. Open Amazon EC2 console, select network and security tab in left navigation pane and choose Key pairs. Choose create key pair and enter a name for the key pair and choose the format (PEM/PPK) according to your requirement and choose create key pair, key pair will be automatically download. keep the key pair in secured place.

    Retrieve the public key for the key-pair downloaded from AWS. generate the public key with below command:
    ssh-keygen -y -f recover-key-par.pem

  2. Generate a key pair with a third party tool of your choice. For example, you can use ssh-keygen. Alternatively, Java, Ruby, Python and many other programming language provide standard libraries that you can use to create RSA key pair.

    Save the public key to a local file. For example, ~/.ssh/id_rsa.pub
    Note that file name extension for this file is not important
In AWS management console, navigate to EC2 console and select the instance which you have lost the key-pair. Stop the instance


Once, instance is stopped. Select the Actions and choose Instance settings and select Edit user data. Copy the below script and paste it in user data

Content-Type: multipart/mixed; boundary="//"
MIME-Version: 1.0

--//
Content-Type: text/cloud-config; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="cloud-config.txt"

#cloud-config
cloud_final_modules:
- [users-groups, once]
users:
 - name:ec2-user
   ssh-authorized-keys:
   - PublicKeypair
Replace PublicKeypair with the ssh rsa keys which we generated above and save the user data and start the instance.

Once Instance is Up and running, connect to the EC2 instance with the key which you have passed in the user data. In this example, I will connect via Putty with PPK. In order to login to the Instance via Putty, you need to generate PPK via PuttyGen.

Open PuttyGen, select load and locate the PEM file and click on save private Key.
Open Putty, enter the IP address of the instance and in SSH and Auth browse the PPK file and click Open. Login with ec2-user and you should be able to authenticate with the Linux instance

Please note that since the script contains a key-pair, it is necessary to remove the script from the user data field after verifying that you are able to connect to the EC2 instance.

Method 2: Using AWS Systems Manager

If the instance is a managed instance in AWS Systems Manager, you can use the AWSSupport-ResetAccess document to recover the lost key pair.

Open the AWS Systems Manager console, select Automation in left navigation pane, click execute Automation. In automation document section select owned by Amazon. In the run book list, search for AWSSupport-ResetAccess

In Execute automation document page, choose Simple execution. In document details section, verify Document version is set to Default. In the input parameter section, specify the following parameter and execute.

InstanceId: Instance ID which is not reachable
SubnetId: Subnet ID where Unreachable instance is hosted
EC2RescueInstanceType: Specify the Instance Type for the EC2 Rescue Instance

When Automation is finished, choose the description tab and choose view outputs to validate the output.


For Linux instances, the new ssh private key is saved and encrypted in parameter store and the parameter store named as /ec2rl/openssh/<InstanceID>/key

You can ssh to the instance by using this key.
Note: The Automation workflow creates a backup, password-enabled Amazon Machine Images(AMI) that you may want to remove. To locate these AMI, In EC2 console, choose AMI from left navigation pane. Enter the automation execution ID in search field and locate the AMI.

Conclusion

In this blog post, I have shown you how to login to the Linux EC2 Instance if you have lost the key pair. Hope this blog helped you in your similar use case.

Thank you for reading!

Comments

Popular posts from this blog

Setup Grafana on AWS EKS and integrate with AWS Cloudwatch

Start or Stop services in multiple Windows EC2 Instances using AWS Systems Manager

Concourse CI Installation and Configuration in Windows

Install SSM Agent in Amazon EC2 Instance

AWS Route 53 Inbound Resolver to resolve DNS for Multi Account Organization

Automate Permission Boundary Attachment to IAM roles and Users

Deploy AWS infrastructure using Terraform and GitHub Actions

Import Existing Resources using Terraform

Hosting AWS VPC Interface Endpoints in Shared Model