Thursday, April 19, 2012

Creating key pairs for Amazon EC2

A few days ago I needed to generate key pairs for an Amazon account again. I thought I'd write down the process.

There are two key pairs that you need: one pair for making API calls (and using the command line tools which make API calls under the covers), and another pair to log into your EC2 machines with SSH. The following works on Linux and Mac clients “out of the box”, Windows users will need to download the appropriate software.

Now, Amazon provides facilities for generating key pairs, why not use those? The first rule of public-key cryptography is that nobody but you ever sees your private key. In fact, that's not just a rule, that's the whole point: the best way to keep a secret is never to share it. If you use Amazon's facilities to generate your private keys, you're violating this rule. Yes, malicious Amazon employees could force the use of key pairs that they have generated themselves, but that should at least be traceable. In the end, when you use Amazon's infrastructure, you are putting a certain level of trust in Amazon, but a basic tenet of security is that having security at multiple levels is A Good Thing.

Ok, with the reasons to do it yourself covered, this is how you do it:

Generating AWS Signing Certificates

 openssl req -x509 -newkey rsa:2048 -passout pass:a -keyout kx -out cert
 openssl rsa -passin pass:a -in kx -out key

The first command produces the key pair and a self-signed certificate; just hit return to accept the defaults at all the certificate request prompts (real information is not required or useful). The second command removes the password “a” from the private key file, which is generally required for automation purposes (make sure that the file and your machines are appropriately secured). The kx file can be deleted.

To use the key pair, upload the cert file as a signing certificate to Amazon and specify the location of the cert and key files in the appropriate environment variables (EC2_CERT and EC2_PRIVATE_KEY) or directly on the command line.

Generating EC2 key pairs

 ssh-keygen -b 2048 -t rsa -f aws-key

This will generate two files, aws-key and containing the private and public keys respectively. Import as a “key pair” (it's only the public key, not really a pair) into AWS. When you launch a Linux instance with this key, this public key is made available to the instance, where it will typically appear in an authorized_keys file for remote access via ssh. If you don't set the key as your default ssh key on your client, you can use the -i option of ssh to specify the location.