Retrieve Public ssh Key From EC2

| 2 Comments

A serverfault poster had a problem that I thought was a cool challenge. I had so much fun coming up with this answer, I figured I’d share it here as it demonstrates a few handy features of EC2.

Challenge

The basic need is to get the public ssh key from a keypair that exists inside of EC2. You don’t have access to the private key at the moment (but somebody else does or you will at a different location).

The AWS console and EC2 API do not let you ask for the public ssh key associated with a keypair. However, EC2 does pass the public ssh key to a new EC2 instance when you run it with a specific keypair.

The problem is that we don’t currently have the private key, so we can’t log in to the EC2 instance to get the public key. (Besides, if we did have the private key, we could extract the public key from it directly.)

Solution

I proposed creating a user-data script that sends the public ssh key to the EC2 instance console output. You can retrieve the console output without logging in to the EC2 instance.

Save the following code to a file named output-ssh-key.userdata on your local computer. DO NOT RUN THESE COMMANDS LOCALLY!

#!/bin/bash -ex
exec> >(tee /var/log/user-data.log|logger -t user -s 2>/dev/console) 2>&1
adminkey=$(GET instance-data/latest/meta-data/public-keys/ | 
  perl -ne 'print $1 if /^0=[^a-z0-9]*([-.@\w]*)/i')
cat <<EOF
SSHKEY:===================================================================
SSHKEY:HERE IS YOUR PUBLIC SSH KEY FOR KEYPAIR "$adminkey":
SSHKEY:$(cat /home/ubuntu/.ssh/authorized_keys)
SSHKEY:===================================================================
SSHKEY:Halting in 50min ($(date --date='+50 minutes' +"%Y-%m-%d %H:%M UTC"))
EOF
sleep 3000
halt

Run a stock Ubuntu 10.04 LTS instance with the above file as a user-data script. Specify the keypair for which you want to retrieve the public ssh key:

ec2-run-instances   --key YOURKEYPAIRHERE   --instance-type t1.micro   --instance-initiated-shutdown-behavior terminate   --user-data-file output-ssh-key.userdata   ami-ab36fbc2

Keep requesting the console output from the instance until it shows your public ssh key. Specify the instance id returned from the run-instances command:

ec2-get-console-output YOURINSTANCEID | grep SSHKEY: | cut -f3- -d:

Repeat the above command a couple times a minute and within 2-10 minutes you will get output like this:

===================================================================
HERE IS YOUR PUBLIC SSH KEY FOR KEYPAIR "erich":
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6rn8cl41CkzaH4ZBhczOJZaR4xBBDI1Kelc2ivzVvCB
THcdJRWpDd5I5hY5W9qke9Tm4fH3KaUVndlcP0ORGvS3PAL4lTpkS4D4goMEFrwMO8BG0NoE8sf2U/7g
aUkdcrDC7jzKYdwleRCI3uibNXiSdeG6RotClAAp7pMflDVp5WjjECDZ+8Jzs2wasdTwQYPhiWSiNcfb
fS97QdtROf0AcoPWElZAgmabaDFBlvvzcqxQRjNp/zbpkFHZBSKp+Sm4+WsRuLu6TDe9lb2Ps0xvBp1F
THlJRUVKP2yeZbVioKnOsXcjLfoJ9TEL7EMnPYinBMIE3kAYw3FzZZFeX3Q== erich
===================================================================
Halting in 50min (2011-12-20 05:58 UTC)

The temporary instance will automatically terminate itself in under an hour, but you can terminate it yourself if you’d like to make sure that you aren’t charged more than the two cents this will cost to run.

Notes

  • If you currently have access to the private ssh key (not true in the above challenge) you can extract the public ssh key using a command like:

    ssh-keygen -y -f KEYFILE.pem
    

    but that’s obviously not as fun.

  • There is no way to retrieve the private ssh key if you have lost it. To protect your security, Amazon EC2 does not store a copy of this. If you are looking to get access to an EC2 instance where you have lost the private ssh key, I recommend following the approach I wrote about in this article: http://alestic.com/2011/02/ec2-fix-ebs-root

  • In seemingly-related-but-not news, Scott Moser is working on an enhancement to cloud-init (used by Ubuntu on EC2, Amazon Linux, and perhaps others) so that the public ssh host keys are output to the console output on instance startup. This cool feature will allow us to add the ssh host keys to our local known_hosts files, safely avoiding that pesky “Are you sure you want to continue connecting (yes/no)?” warning.

2 Comments

I've used this which is even easier for my user-data-file:

#!/bin/bash
/usr/bin/python -mSimpleHTTPServer 9090

Then just browse to the public IP of your instance on port 9090 (and make sure you have your proper security group rules setup) and copy the key from authorized_keys. Just make sure to restrict your security group ingress rules properly or this will expose your instance to outsiders.

stefhen.hovland:

Awesome tip, thanks!

Leave a comment

Ubuntu AMIs

Ubuntu AMIs for EC2:


More Entries

EC2 create-image Does Not Fully "Stop" The Instance
The EC2 create-image API/command/console action is a convenient trigger to create an AMI from a running (or stopped) EBS boot instance. It takes a snapshot of the instance’s EBS volume(s)…
Finding the Region for an AWS Resource ID
use concurrent AWS command line requests to search the world for your instance, image, volume, snapshot, … Background Amazon EC2 and many other AWS services are divided up into various…
Changing The Default "ubuntu" Username On New EC2 Instances
configure your own ssh username in user-data The official Ubuntu AMIs create a default user with the username ubuntu which is used for the initial ssh access, i.e.: ssh ubuntu@<HOST>…
Default ssh Usernames For Connecting To EC2 Instances
Each AMI publisher on EC2 decides what user (or users) should have ssh access enabled by default and what ssh credentials should allow you to gain access as that user.…
New c3.* Instance Types on Amazon EC2 - Nice!
Worth switching. Amazon shared that the new c3.* instance types have been in high demand on EC2 since they were released. I finally had a minute to take a look…
Query EC2 Account Limits with AWS API
Here’s a useful tip mentioned in one of the sessions at AWS re:Invent this year. There is a little known API call that lets you query some of the EC2…
Using aws-cli --query Option To Simplify Output
My favorite session at AWS re:Invent was James Saryerwinnie’s clear, concise, and informative tour of the aws-cli (command line interface), which according to GitHub logs he is enhancing like crazy.…
Reset S3 Object Timestamp for Bucket Lifecycle Expiration
use aws-cli to extend expiration and restart the delete or archive countdown on objects in an S3 bucket Background S3 buckets allow you to specify lifecycle rules that tell AWS…
Installing aws-cli, the New AWS Command Line Tool
consistent control over more AWS services with aws-cli, a single, powerful command line tool from Amazon Readers of this tech blog know that I am a fan of the power…
Using An AWS CloudFormation Stack To Allow "-" Instead Of "+" In Gmail Email Addresses
Launch a CloudFormation template to set up a stack of AWS resources to fill a simple need: Supporting Gmail addresses with “-” instead of “+” separating the user name from…
New Options In ec2-expire-snapshots v0.11
The ec2-expire-snapshots program can be used to expire EBS snapshots in Amazon EC2 on a regular schedule that you define. It can be used as a companion to ec2-consistent-snapshot or…
Replacing a CloudFront Distribution to "Invalidate" All Objects
I was chatting with Kevin Boyd (aka Beryllium) on the ##aws Freenode IRC channel about the challenge of invalidating a large number of CloudFront objects (35,000) due to a problem…
Email Alerts for AWS Billing Alarms
using CloudWatch and SNS to send yourself email messages when AWS costs accrue past limits you define The Amazon documentation describes how to use the AWS console to monitor your…
Cost of Transitioning S3 Objects to Glacier
how I was surprised by a large AWS charge and how to calculate the break-even point Glacier Archival of S3 Objects Amazon recently introduced a fantastic new feature where S3…
Running Ubuntu on Amazon EC2 in Sydney, Australia
Amazon has announced a new AWS region in Sydney, Australia with the name ap-southeast-2. The official Ubuntu AMI lookup pages (1, 2) don’t seem to be showing the new location…
Save Money by Giving Away Unused Heavy Utilization Reserved Instances
You may be able to save on future EC2 expenses by selling an unused Reserved Instance for less than its true value or even $0.01, provided it is in the…
Installing AWS Command Line Tools from Amazon Downloads
When you need an AWS command line toolset not provided by Ubuntu packages, you can download the tools directly from Amazon and install them locally. In a previous article I…
Convert Running EC2 Instance to EBS-Optimized Instance with Provisioned IOPS EBS Volumes
Amazon just announced two related features for getting super-fast, consistent performance with EBS volumes: (1) Provisioned IOPS EBS volumes, and (2) EBS-Optimized Instances. Starting new instances and EBS volumes with…
Which EC2 Availability Zone is Affected by an Outage?
Did you know that Amazon includes status messages about the health of availability zones in the output of the ec2-describe-availability-zones command, the associated API call, and the AWS console? Right…
Installing AWS Command Line Tools Using Ubuntu Packages
See also: Installing AWS Command Line Tools from Amazon Downloads Here are the steps for installing the AWS command line tools that are currently available as Ubuntu packages. These include:…
Ubuntu Developer Summit, May 2012 (Oakland)
I will be attending the Ubuntu Developer Summit (UDS) next week in Oakland, CA. ┬áThis event brings people from around the world together in one place every six months to…
Uploading Known ssh Host Key in EC2 user-data Script
The ssh protocol uses two different keys to keep you secure: The user ssh key is the one we normally think of. This authenticates us to the remote host, proving…
Seeding Torrents with Amazon S3 and s3cmd on Ubuntu
Amazon Web Services is such a huge, complex service with so many products and features that sometimes very simple but powerful features fall through the cracks when you’re reading the…
CloudCamp
There are a number of CloudCamp events coming up in cities around the world. These are free events, organized around the various concepts, technologies, and services that fall under the…
Use the Same Architecture (64-bit) on All EC2 Instance Types
A few hours ago, Amazon AWS announced that all EC2 instance types can now run 64-bit AMIs. Though t1.micro, m1.small, and c1.medium will continue to also support 32-bit AMIs, it…
ec2-consistent-snapshot on GitHub and v0.43 Released
The source for ec2-conssitent-snapshot has historically been available here: ec2-consistent-snapshot on Launchpad.net using Bazaar For your convenience, it is now also available here: ec2-consistent-snapshot on GitHub using Git You are…
You Should Use EBS Boot Instances on Amazon EC2
EBS boot vs. instance-store If you are just getting started with Amazon EC2, then use EBS boot instances and stop reading this article. Forget that you ever heard about instance-store…
Retrieve Public ssh Key From EC2
A serverfault poster had a problem that I thought was a cool challenge. I had so much fun coming up with this answer, I figured I’d share it here as…
Running EC2 Instances on a Recurring Schedule with Auto Scaling
Do you want to run short jobs on Amazon EC2 on a recurring schedule, but don’t want to pay for an instance running all the time? Would you like to…
AWS Virtual MFA and the Google Authenticator for Android
Amazon just announced that the AWS MFA (multi-factor authentication) now supports virtual or software MFA devices in addition to the physical hardware MFA devices like the one that’s been taking…