fix(ec2): generate real key material in CreateKeyPair and fingerprint imported keys (#3307)

* fix(ec2): generate real key material in CreateKeyPair

CreateKeyPair returned a fixed string literal as KeyMaterial:

    -----BEGIN RSA PRIVATE KEY-----
    MIIEpAIBAAKCAQEA0Z3VS5JJcds3xHn/ygWep4Ib/ue7YiKbCIZgYpYDe0+FAKE
    -----END RSA PRIVATE KEY-----

That is a 63-character body -- a placeholder, not a truncated key. It does
not parse:

    $ ssh-keygen -y -f key.pem
    Load key "key.pem": invalid format

and it was byte-identical for every key pair in every region. No public
half was stored either, so Ec2ContainerManager.injectSshKey() had nothing
to write to authorized_keys for a created key.

The AWS API reference for CreateKeyPair describes the response as "an
unencrypted PEM encoded RSA or ED25519 private key", with KeyFingerprint
being "the SHA-1 digest of the DER encoded private key" for a key pair AWS
created. This is the only call that ever discloses the private key, and
callers are expected to use it directly: the Packer amazon-ebs builder
creates a temporary key pair, writes the returned material to a file, and
SSHes in with it. A placeholder cannot serve that, so no Packer build --
and no test that SSHes into an instance -- could work.

Generates a real 2048-bit RSA key pair (the size and type AWS uses for the
default KeyType=rsa), returns it as a PKCS#1 "BEGIN RSA PRIVATE KEY" PEM to
match AWS's encoding rather than Java's native PKCS#8, stores the matching
OpenSSH public key so injection has something to inject, and reports a real
SHA-1 fingerprint. KeyPairGenerator is already used this way in KmsService,
CognitoService and EksOidcService, and bcpkix is already a dependency.

ImportKeyPair reported the same constant fingerprint for every key. It now
reports the MD5 of the DER public key, which is what AWS reports for
imported keys. Only ssh-rsa is decoded back to a SubjectPublicKeyInfo; for
other key types the digest is taken over the wire-format blob, which is
stable and distinct per key but not byte-identical to AWS. Material that
does not parse yields no fingerprint rather than a digest of garbage, and
the caller falls back to the old placeholder.

Tests parse and use the material rather than pattern-matching it -- the
original literal would satisfy any shape check, which is how it survived.
They assert the PEM parses as a 2048-bit RSA key, that the emitted public
key is genuinely the other half of the returned private key, that distinct
calls yield distinct keys, that the OpenSSH length-prefix framing round
trips, and that an imported key's fingerprint ignores the trailing comment.

Related: the SSH path is also blocked by sshd never starting; see the
companion fix for Ec2ContainerManager.startSshd().

* test(ec2): cover the CreateKeyPair and ImportKeyPair wiring

Ec2KeyMaterialTest exercises the generator directly, so reverting the Ec2Service
side of the change left the whole EC2 suite green: 821 tests passed with
createKeyPair still handing out the placeholder literal. The production wiring
was the part with no coverage.

These two go through Ec2Service. The first parses what createKeyPair returns
rather than matching its shape, since the placeholder was a well formed PEM
envelope around 63 bytes and satisfied any pattern check, and asserts the public
half is stored, because that is what RunInstances injects into authorized_keys.
The second asserts two imported keys get different fingerprints, which the old
constant could not.

With the Ec2Service change reverted these fail as
"malformed PEM data: unable to decode base64 string: Index 63 out of bounds for
length 63" and "expected: not equal but was:
<00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00>".

* fix(ec2): bound imported key blob fields and fingerprint ed25519 as AWS does

Two problems in the ImportKeyPair path, both reachable with caller supplied
PublicKeyMaterial.

SshReader.readBytes allocated an array sized by a length read straight out of
the blob, and only then checked that the bytes were there. An eleven byte
request could declare a two gigabyte field, and the resulting OutOfMemoryError
is an Error, so the catch inside fingerprintOf did not contain it. The declared
length is now rejected before it is allocated when it is negative, larger than
what remains in the buffer, or over an absolute ceiling of 64 KiB. Bounding by
the remainder ties the allocation to the size of the request that carried it.

ed25519 imports were fingerprinted with MD5 over the wire blob. EC2 reports the
base64 encoded SHA-256 digest for ed25519 key pairs however they were created,
which is the ssh-keygen value without its SHA256: prefix and with the base64
padding kept.

The RSA import path is unchanged and was already right: AWS documents the check
as "openssl rsa -pubout -outform DER | openssl md5 -c", which is MD5 over the
DER SubjectPublicKeyInfo rather than over the SSH blob, and that is what
RSAPublicKey.getEncoded produces.

The existing fingerprint tests asserted digest shape, or compared the service
against the same helper it calls, so neither could see a wrong scheme. The new
ones pin both key types to values derived outside this codebase from fixed
throwaway keys, and assert the RSA value is not the MD5 of the SSH blob, which
is the scheme it could plausibly be confused with.

Refs: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/verify-keys.html
This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-09-09 16:35:40 -04:00
1 parent a339f3ae70
commit 2fbe2b7c64
4 files changed
+509 -3

No files matched your search

@@ -0,0 +1,198 @@
package io.github.hectorvent.floci.services.ec2;
import org.bouncycastle.openssl.jcajce.JcaPEMWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.RSAPublicKeySpec;
import java.util.Base64;
import java.util.HexFormat;
/**
* Real key material for EC2 key pairs.
*
* <p>CreateKeyPair is the only time AWS ever discloses a private key, and callers are
* expected to write the response straight to a file and use it: the Packer amazon-ebs
* builder, for one, creates a temporary key pair, saves the returned material, and SSHes
* in with it. A placeholder string cannot serve that, so the key is generated here.
*
* @see <a href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateKeyPair.html">CreateKeyPair</a>
* @see <a href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ImportKeyPair.html">ImportKeyPair</a>
*/
public final class Ec2KeyMaterial {
/** AWS generates 2048-bit RSA keys for KeyType=rsa, which is the default. */
private static final int RSA_KEY_SIZE = 2048;
/** An ed25519 public key is a fixed 32-byte value, so any other length is not one. */
private static final int ED25519_KEY_LENGTH = 32;
private Ec2KeyMaterial() {}
/**
* @param privateKeyPem PKCS#1 PEM, the "BEGIN RSA PRIVATE KEY" form AWS returns
* @param openSshPublicKey the matching "ssh-rsa AAAA..." line, for authorized_keys
* @param fingerprint SHA-1 of the DER private key, colon-separated hex
*/
public record Generated(String privateKeyPem, String openSshPublicKey, String fingerprint) {}
public static Generated generateRsa() {
try {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(RSA_KEY_SIZE);
java.security.KeyPair pair = generator.generateKeyPair();
StringWriter out = new StringWriter();
try (JcaPEMWriter pem = new JcaPEMWriter(out)) {
// Writes the traditional PKCS#1 "RSA PRIVATE KEY" block rather than Java's
// native PKCS#8 "PRIVATE KEY", matching what AWS actually returns. OpenSSH
// reads both, but tooling that pattern-matches the header only reads the former.
pem.writeObject(pair.getPrivate());
}
// "The SHA-1 digest of the DER encoded private key" for a key pair AWS created.
// (Imported keys use the MD5 of the public key instead -- see fingerprintOf.)
String fingerprint = colonHex(
MessageDigest.getInstance("SHA-1").digest(pair.getPrivate().getEncoded()));
return new Generated(
out.toString(),
openSshPublicKey((RSAPublicKey) pair.getPublic()),
fingerprint);
} catch (NoSuchAlgorithmException | IOException e) {
throw new IllegalStateException("Could not generate an EC2 key pair", e);
}
}
/**
* Fingerprint for an imported public key, in the scheme AWS uses for that key type.
*
* <p>ImportKeyPair does not fingerprint every key the same way, and it does not agree
* with CreateKeyPair either:
*
* <ul>
* <li><b>ssh-rsa</b>: "the MD5 public key fingerprint", taken over the DER
* SubjectPublicKeyInfo rather than over the SSH wire blob. AWS documents the check
* as {@code openssl rsa -in key -pubout -outform DER | openssl md5 -c}, and
* {@link java.security.Key#getEncoded()} produces exactly that DER, so the blob is
* decoded back to a public key first. Colon-separated hex, as AWS reports it.</li>
* <li><b>ssh-ed25519</b>: the base64-encoded SHA-256 digest of the wire blob, "which is
* the default for OpenSSH". This is the {@code ssh-keygen -l} value without its
* {@code SHA256:} prefix, and padded: AWS keeps the trailing {@code =} that
* ssh-keygen drops.</li>
* </ul>
*
* <p>Any other key type keeps the MD5 of the wire blob: stable and distinct per key,
* which is what callers depend on, but not a value AWS would report. AWS accepts only
* RSA and ed25519 material for import, so nothing else has a documented answer to match.
*
* <p>Returns null for material that does not parse, so the caller can decide rather than
* getting a fingerprint of garbage.
*
* @see <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/verify-keys.html">Verify the fingerprint of your key pair</a>
*/
public static String fingerprintOf(String openSshPublicKey) {
byte[] blob = decodeOpenSshBlob(openSshPublicKey);
if (blob == null) {
return null;
}
try {
byte[] der = blob;
SshReader reader = new SshReader(blob);
String type = new String(reader.readBytes(), StandardCharsets.UTF_8);
if ("ssh-ed25519".equals(type)) {
if (reader.readBytes().length != ED25519_KEY_LENGTH) {
return null;
}
return Base64.getEncoder().encodeToString(
MessageDigest.getInstance("SHA-256").digest(blob));
}
if ("ssh-rsa".equals(type)) {
BigInteger exponent = new BigInteger(reader.readBytes());
BigInteger modulus = new BigInteger(reader.readBytes());
der = KeyFactory.getInstance("RSA")
.generatePublic(new RSAPublicKeySpec(modulus, exponent))
.getEncoded();
}
return colonHex(MessageDigest.getInstance("MD5").digest(der));
} catch (Exception e) { // malformed material is the caller's problem, not a crash
return null;
}
}
static String openSshPublicKey(RSAPublicKey key) {
byte[] type = "ssh-rsa".getBytes(StandardCharsets.US_ASCII);
byte[] exponent = key.getPublicExponent().toByteArray();
byte[] modulus = key.getModulus().toByteArray();
ByteBuffer blob = ByteBuffer.allocate(
12 + type.length + exponent.length + modulus.length);
for (byte[] field : new byte[][]{type, exponent, modulus}) {
blob.putInt(field.length).put(field);
}
return "ssh-rsa " + Base64.getEncoder().encodeToString(blob.array());
}
private static byte[] decodeOpenSshBlob(String openSshPublicKey) {
if (openSshPublicKey == null) {
return null;
}
// "ssh-rsa AAAAB3Nza... comment" -- the middle field is the blob.
String[] fields = openSshPublicKey.trim().split("\\s+");
if (fields.length < 2) {
return null;
}
try {
return Base64.getDecoder().decode(fields[1]);
} catch (IllegalArgumentException e) {
return null;
}
}
private static String colonHex(byte[] digest) {
return HexFormat.of().withDelimiter(":").formatHex(digest);
}
/** Reads the length-prefixed fields of an OpenSSH public key blob. */
private static final class SshReader {
/**
* Absolute ceiling on a single field, well clear of anything a real key carries: the
* largest is the modulus of a 16384-bit RSA key, 2049 bytes with its sign byte.
*/
private static final int MAX_FIELD_LENGTH = 64 * 1024;
private final ByteBuffer buffer;
SshReader(byte[] blob) {
this.buffer = ByteBuffer.wrap(blob);
}
byte[] readBytes() {
if (buffer.remaining() < Integer.BYTES) {
throw new IllegalArgumentException("truncated OpenSSH key blob");
}
int length = buffer.getInt();
// ImportKeyPair hands the caller's PublicKeyMaterial straight to this parser, so
// the declared length is attacker-controlled and has to be checked before it is
// allocated. Reading it first meant an eleven-byte blob could declare a
// two-gigabyte field and the array was built before anything noticed the bytes
// were not there; the resulting OutOfMemoryError is an Error, so the catch around
// fingerprintOf did not contain it either. Bounding by what is left in the buffer
// ties the allocation to the size of the request that carried it.
if (length < 0 || length > MAX_FIELD_LENGTH || length > buffer.remaining()) {
throw new IllegalArgumentException("invalid OpenSSH key field length: " + length);
}
byte[] field = new byte[length];
buffer.get(field);
return field;
}
}
}
@@ -3936,8 +3936,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
KeyPair kp = new KeyPair();
kp.setKeyPairId(keyPairId);
kp.setKeyName(keyName);
kp.setKeyFingerprint("00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00");
kp.setKeyMaterial("-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEA0Z3VS5JJcds3xHn/ygWep4Ib/ue7YiKbCIZgYpYDe0+FAKE\n-----END RSA PRIVATE KEY-----");
Ec2KeyMaterial.Generated generated = Ec2KeyMaterial.generateRsa();
kp.setKeyFingerprint(generated.fingerprint());
kp.setKeyMaterial(generated.privateKeyPem());
// The public half is what RunInstances injects into the guest's authorized_keys.
// Without storing it, a key pair created here could never authenticate anything.
kp.setPublicKey(generated.openSshPublicKey());
kp.setRegion(region);
keyPairs.put(key(region, keyPairId), kp);
return kp;
@@ -3997,7 +4001,13 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
KeyPair kp = new KeyPair();
kp.setKeyPairId(keyPairId);
kp.setKeyName(keyName);
kp.setKeyFingerprint("00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00");
// A per-key fingerprint, not a constant: callers compare it to detect that the key
// under a given name has been replaced. Falls back to the old placeholder only when
// the material does not parse, rather than reporting a digest of garbage.
String fingerprint = Ec2KeyMaterial.fingerprintOf(publicKeyMaterial);
kp.setKeyFingerprint(fingerprint != null
? fingerprint
: "00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00");
kp.setPublicKey(publicKeyMaterial);
kp.setRegion(region);
keyPairs.put(key(region, keyPairId), kp);