From 2fbe2b7c647c924be9586170a5fb5527850829f7 Mon Sep 17 00:00:00 2001 From: Allen Sanborn Date: Wed, 9 Sep 2026 15:35:40 -0500 Subject: [PATCH] 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 --- .../floci/services/ec2/Ec2KeyMaterial.java | 198 ++++++++++++++++ .../floci/services/ec2/Ec2Service.java | 16 +- .../services/ec2/Ec2KeyMaterialTest.java | 222 ++++++++++++++++++ .../floci/services/ec2/Ec2ServiceTest.java | 76 ++++++ 4 files changed, 509 insertions(+), 3 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/services/ec2/Ec2KeyMaterial.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/ec2/Ec2KeyMaterialTest.java diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2KeyMaterial.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2KeyMaterial.java new file mode 100644 index 0000000000..58e2d2e6e3 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2KeyMaterial.java @@ -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. + * + *

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 CreateKeyPair + * @see ImportKeyPair + */ +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. + * + *

ImportKeyPair does not fingerprint every key the same way, and it does not agree + * with CreateKeyPair either: + * + *

+ * + *

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. + * + *

Returns null for material that does not parse, so the caller can decide rather than + * getting a fingerprint of garbage. + * + * @see Verify the fingerprint of your key pair + */ + 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; + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java index 3f956118e2..1360b6a77d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java @@ -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); diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2KeyMaterialTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2KeyMaterialTest.java new file mode 100644 index 0000000000..6fdb717ab3 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2KeyMaterialTest.java @@ -0,0 +1,222 @@ +package io.github.hectorvent.floci.services.ec2; + +import org.bouncycastle.openssl.PEMKeyPair; +import org.bouncycastle.openssl.PEMParser; +import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; +import org.junit.jupiter.api.Test; + +import java.io.StringReader; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.interfaces.RSAPrivateCrtKey; +import java.security.interfaces.RSAPublicKey; +import java.util.Base64; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * CreateKeyPair previously returned a fixed 63-character string literal as KeyMaterial. It + * looked like a PEM but did not parse ("ssh-keygen -y -f key.pem: invalid format"), so no + * caller could ever use it -- and it was byte-identical for every key pair. + * + *

These tests deliberately parse and use the material rather than matching it against a + * pattern: a placeholder passes any shape check, which is how the original went unnoticed. + */ +class Ec2KeyMaterialTest { + + /** Throwaway keys, kept fixed so their fingerprints can be pinned to known good values. */ + private static final String RSA_PUBLIC_KEY = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCp7mGC9" + + "NkQI+loxf1G9bM6HnCs9iR1nnzZA/f/o7hx/Wv1oDhx03k6H83I+Q49eE1XO56WBPxnr8/2G6UmS9D0R" + + "FKe9L+HJrfiZF7oLQ09JwEK91VLNSkD0Bq2zhnfWJe/ULkaPQ7FgHEghRi8aI5PsATH6VCaJDKWxl+2b" + + "zM7MWlbKRAo8uuu2evnGrgnu+RmuXJQCRYz6lG+JESVzm6MnHXYxme+UD+7c/tTYwzoswfXh8VN8QVzX" + + "mjfHi2Ve3PJ+YuF2X2gKpRMNMf7cLWMCTOhZI2AgXX+NLDlCG0dEUm/DXdSKRTDhm3mIJmF67eGYuff+" + + "zHusBZ9cSBkW9i9"; + + private static final String ED25519_PUBLIC_KEY = + "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAII0fBPBUZHaEOBc2mySfmI5btu4mkvFfNRujmF7RH2fj"; + + @Test + void generatedPrivateKeyParsesAsA2048BitRsaKey() throws Exception { + Ec2KeyMaterial.Generated generated = Ec2KeyMaterial.generateRsa(); + + Object parsed = new PEMParser(new StringReader(generated.privateKeyPem())).readObject(); + assertTrue(parsed instanceof PEMKeyPair, "expected a PEM key pair, got: " + parsed); + RSAPrivateCrtKey privateKey = (RSAPrivateCrtKey) new JcaPEMKeyConverter() + .getKeyPair((PEMKeyPair) parsed).getPrivate(); + + assertEquals(2048, privateKey.getModulus().bitLength()); + } + + @Test + void generatedPrivateKeyUsesThePkcs1HeaderAwsReturns() { + // AWS returns the traditional "BEGIN RSA PRIVATE KEY" block. Java's own encoding is + // PKCS#8 ("BEGIN PRIVATE KEY"); OpenSSH reads both, but tooling that matches on the + // header only reads the former. + String pem = Ec2KeyMaterial.generateRsa().privateKeyPem(); + assertTrue(pem.startsWith("-----BEGIN RSA PRIVATE KEY-----"), pem.lines().findFirst().orElse("")); + assertTrue(pem.contains("-----END RSA PRIVATE KEY-----")); + } + + @Test + void publicKeyMatchesThePrivateKeyItWasGeneratedWith() throws Exception { + // The whole point of the pair: what gets written to authorized_keys has to be the + // other half of what the caller receives, or SSH still fails. + Ec2KeyMaterial.Generated generated = Ec2KeyMaterial.generateRsa(); + + PEMKeyPair parsed = (PEMKeyPair) new PEMParser( + new StringReader(generated.privateKeyPem())).readObject(); + RSAPrivateCrtKey privateKey = (RSAPrivateCrtKey) new JcaPEMKeyConverter() + .getKeyPair(parsed).getPrivate(); + + String[] fields = generated.openSshPublicKey().split(" "); + assertEquals("ssh-rsa", fields[0]); + ByteBuffer blob = ByteBuffer.wrap(Base64.getDecoder().decode(fields[1])); + + assertEquals("ssh-rsa", new String(read(blob), StandardCharsets.UTF_8)); + assertEquals(privateKey.getPublicExponent(), new BigInteger(read(blob))); + assertEquals(privateKey.getModulus(), new BigInteger(read(blob))); + } + + @Test + void everyKeyPairIsDistinct() { + // The literal made all key pairs identical, so a second key silently authenticated + // as the first. + Ec2KeyMaterial.Generated first = Ec2KeyMaterial.generateRsa(); + Ec2KeyMaterial.Generated second = Ec2KeyMaterial.generateRsa(); + + assertNotEquals(first.privateKeyPem(), second.privateKeyPem()); + assertNotEquals(first.openSshPublicKey(), second.openSshPublicKey()); + assertNotEquals(first.fingerprint(), second.fingerprint()); + } + + @Test + void fingerprintIsTheColonSeparatedSha1OfTheDerPrivateKey() { + // "The SHA-1 digest of the DER encoded private key" -- 20 bytes, so 20 hex pairs. + String fingerprint = Ec2KeyMaterial.generateRsa().fingerprint(); + + assertTrue(fingerprint.matches("([0-9a-f]{2}:){19}[0-9a-f]{2}"), fingerprint); + } + + @Test + void importedKeyFingerprintIsPerKeyRatherThanAConstant() { + String first = Ec2KeyMaterial.fingerprintOf(Ec2KeyMaterial.generateRsa().openSshPublicKey()); + String second = Ec2KeyMaterial.fingerprintOf(Ec2KeyMaterial.generateRsa().openSshPublicKey()); + + assertNotNull(first); + // MD5 of the DER public key: 16 bytes. + assertTrue(first.matches("([0-9a-f]{2}:){15}[0-9a-f]{2}"), first); + assertNotEquals(first, second); + } + + @Test + void importedKeyFingerprintIsStableAndIgnoresTheTrailingComment() { + // ssh-keygen writes "ssh-rsa AAAA... user@host"; the comment is not part of the key, + // so re-importing the same key under a different comment must not change its identity. + String publicKey = Ec2KeyMaterial.generateRsa().openSshPublicKey(); + + assertEquals(Ec2KeyMaterial.fingerprintOf(publicKey), + Ec2KeyMaterial.fingerprintOf(publicKey + " someone@example.com")); + } + + @Test + void unparseableImportedMaterialYieldsNoFingerprintRatherThanADigestOfGarbage() { + assertEquals(null, Ec2KeyMaterial.fingerprintOf("not-a-key")); + assertEquals(null, Ec2KeyMaterial.fingerprintOf("")); + assertEquals(null, Ec2KeyMaterial.fingerprintOf(null)); + } + + @Test + void openSshEncodingRoundTripsAnArbitraryRsaPublicKey() throws Exception { + // Guards the length-prefixed framing: a wrong length here produces a line that looks + // right and that sshd silently ignores. + Ec2KeyMaterial.Generated generated = Ec2KeyMaterial.generateRsa(); + PEMKeyPair parsed = (PEMKeyPair) new PEMParser( + new StringReader(generated.privateKeyPem())).readObject(); + RSAPublicKey publicKey = (RSAPublicKey) new JcaPEMKeyConverter() + .getKeyPair(parsed).getPublic(); + + assertEquals(generated.openSshPublicKey(), Ec2KeyMaterial.openSshPublicKey(publicKey)); + } + + @Test + void importedRsaFingerprintMatchesTheSchemeAwsDocuments() { + // Pinned against a value derived outside this code, from a throwaway key: + // openssl rsa -in rsa.pem -pubout -outform DER | openssl md5 -c + // which is the command AWS gives for verifying an imported RSA key pair. A test that + // compared the service against fingerprintOf, or that only checked the digest shape, + // would pass under either scheme and so could not tell them apart. + String expected = "4d:1a:39:2e:6a:18:60:9a:c5:2a:cb:cc:6c:de:22:b5"; + + assertEquals(expected, Ec2KeyMaterial.fingerprintOf(RSA_PUBLIC_KEY)); + assertEquals(expected, Ec2KeyMaterial.fingerprintOf(RSA_PUBLIC_KEY + " someone@example.com")); + + // The other candidate scheme for the same key: MD5 over the SSH wire blob, which is + // what "ssh-keygen -l -E md5" reports. AWS does not use it for imported RSA keys, and + // it is a different value, which is what makes the assertion above load bearing. + assertNotEquals("e7:d6:55:60:68:18:8f:b7:4f:2a:72:20:0b:2f:f2:d9", + Ec2KeyMaterial.fingerprintOf(RSA_PUBLIC_KEY)); + } + + @Test + void importedEd25519FingerprintIsTheBase64Sha256AwsReports() { + // EC2 fingerprints ed25519 keys with SHA-256, not MD5, whichever way the key arrived. + // Derived independently with "ssh-keygen -l -f ed25519.pub", which prints + // SHA256:UOyzahv0Ty520U89wfCvKdTlp2TbtpmnlpJHPW3MbMk + // AWS reports the same digest without the prefix and with base64 padding kept. + String fingerprint = Ec2KeyMaterial.fingerprintOf(ED25519_PUBLIC_KEY); + + assertEquals("UOyzahv0Ty520U89wfCvKdTlp2TbtpmnlpJHPW3MbMk=", fingerprint); + assertEquals(fingerprint, + Ec2KeyMaterial.fingerprintOf(ED25519_PUBLIC_KEY + " someone@example.com")); + } + + @Test + void ed25519MaterialThatIsNotA32ByteKeyYieldsNoFingerprint() { + assertEquals(null, Ec2KeyMaterial.fingerprintOf( + "ssh-ed25519 " + Base64.getEncoder().encodeToString(blobOf("ssh-ed25519", new byte[31])))); + } + + @Test + void aFieldLongerThanTheBlobIsRejectedRatherThanAllocated() { + // ImportKeyPair passes the caller's material to this parser, so the declared field + // length is attacker controlled. A blob that announces a two-gigabyte field is a few + // bytes on the wire; allocating first turns that into an OutOfMemoryError, which is an + // Error and so escapes the catch inside fingerprintOf and takes the request thread + // with it. The length has to be rejected before the array exists. + ByteBuffer overstated = ByteBuffer.allocate(15); + byte[] type = "ssh-rsa".getBytes(StandardCharsets.UTF_8); + overstated.putInt(type.length).put(type).putInt(Integer.MAX_VALUE); + + assertEquals(null, Ec2KeyMaterial.fingerprintOf( + "ssh-rsa " + Base64.getEncoder().encodeToString(overstated.array()))); + } + + @Test + void negativeAndTruncatedFieldLengthsYieldNoFingerprint() { + ByteBuffer negative = ByteBuffer.allocate(4).putInt(-1); + assertEquals(null, Ec2KeyMaterial.fingerprintOf( + "ssh-rsa " + Base64.getEncoder().encodeToString(negative.array()))); + + // Fewer than four bytes left: not even a length prefix. + assertEquals(null, Ec2KeyMaterial.fingerprintOf( + "ssh-rsa " + Base64.getEncoder().encodeToString(new byte[]{0, 0, 1}))); + } + + private static byte[] blobOf(String type, byte[] key) { + byte[] typeBytes = type.getBytes(StandardCharsets.UTF_8); + return ByteBuffer.allocate(8 + typeBytes.length + key.length) + .putInt(typeBytes.length).put(typeBytes) + .putInt(key.length).put(key) + .array(); + } + + private static byte[] read(ByteBuffer blob) { + byte[] field = new byte[blob.getInt()]; + blob.get(field); + return field; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java index 181de19b5a..ef441add17 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java @@ -15,6 +15,7 @@ import io.github.hectorvent.floci.services.ec2.model.Instance; import io.github.hectorvent.floci.services.ec2.model.NetworkInterfaceListResult; import io.github.hectorvent.floci.services.ec2.model.IpPermission; import io.github.hectorvent.floci.services.ec2.model.Ipv6Range; +import io.github.hectorvent.floci.services.ec2.model.KeyPair; import io.github.hectorvent.floci.services.ec2.model.SecurityGroupRule; import io.github.hectorvent.floci.services.ec2.model.UserIdGroupPair; import io.github.hectorvent.floci.services.ec2.model.InstanceState; @@ -43,8 +44,13 @@ import io.github.hectorvent.floci.services.ec2.model.Vpc; import io.github.hectorvent.floci.services.ec2.model.VpcEndpoint; import io.github.hectorvent.floci.services.ec2.model.Volume; import io.github.hectorvent.floci.services.ec2.model.VolumeAttachment; +import org.bouncycastle.openssl.PEMKeyPair; +import org.bouncycastle.openssl.PEMParser; +import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; import org.junit.jupiter.api.Test; +import java.io.StringReader; +import java.security.interfaces.RSAPrivateCrtKey; import java.time.Duration; import java.util.List; import java.util.Map; @@ -789,6 +795,76 @@ class Ec2ServiceTest { assertEquals("InvalidAMIName.Duplicate", error.getErrorCode()); } + @Test + void createKeyPairReturnsUsableMaterialRatherThanAPlaceholder() throws Exception { + Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class), + mock(Ec2PortForwardManager.class), + mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(), + new InMemoryStorageFactory()); + + KeyPair first = service.createKeyPair("us-east-1", "usable-key"); + KeyPair second = service.createKeyPair("us-east-1", "usable-key-2"); + + // Parse the material rather than shape-match it: the placeholder this replaced was a + // well-formed PEM envelope around 63 bytes of nothing, so any regex check passed. + Object parsed = new PEMParser(new StringReader(first.getKeyMaterial())).readObject(); + assertTrue(parsed instanceof PEMKeyPair, "expected a PEM key pair, got: " + parsed); + assertEquals(2048, ((RSAPrivateCrtKey) new JcaPEMKeyConverter() + .getKeyPair((PEMKeyPair) parsed).getPrivate()).getModulus().bitLength()); + // The public half is what RunInstances injects into authorized_keys. + assertNotNull(first.getPublicKey()); + assertTrue(first.getPublicKey().startsWith("ssh-rsa ")); + // A constant is not a fingerprint; two key pairs must differ in every disclosed field. + assertNotEquals(first.getKeyMaterial(), second.getKeyMaterial()); + assertNotEquals(first.getPublicKey(), second.getPublicKey()); + assertNotEquals(first.getKeyFingerprint(), second.getKeyFingerprint()); + } + + @Test + void importKeyPairFingerprintsTheSuppliedKeyRatherThanReportingAConstant() { + Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class), + mock(Ec2PortForwardManager.class), + mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(), + new InMemoryStorageFactory()); + + String firstKey = Ec2KeyMaterial.generateRsa().openSshPublicKey(); + String secondKey = Ec2KeyMaterial.generateRsa().openSshPublicKey(); + + KeyPair first = service.importKeyPair("us-east-1", "imported-a", firstKey); + KeyPair second = service.importKeyPair("us-east-1", "imported-b", secondKey); + + assertNotEquals(first.getKeyFingerprint(), second.getKeyFingerprint()); + assertEquals(Ec2KeyMaterial.fingerprintOf(firstKey), first.getKeyFingerprint()); + } + + @Test + void importKeyPairReportsTheFingerprintAwsWouldReportForTheSameKey() { + // The assertion above compares the service against the same helper it calls, so it + // cannot see a wrong fingerprinting scheme. These two are pinned to values derived + // outside this codebase from fixed throwaway keys: + // RSA: openssl rsa -in rsa.pem -pubout -outform DER | openssl md5 -c + // ed25519: ssh-keygen -l -f ed25519.pub, minus its "SHA256:" prefix, padding kept + // matching the two schemes AWS documents for ImportKeyPair. + Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class), + mock(Ec2PortForwardManager.class), + mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(), + new InMemoryStorageFactory()); + + String rsaKey = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCp7mGC9NkQI+loxf1G9bM6HnCs9iR1nn" + + "zZA/f/o7hx/Wv1oDhx03k6H83I+Q49eE1XO56WBPxnr8/2G6UmS9D0RFKe9L+HJrfiZF7oLQ09Jw" + + "EK91VLNSkD0Bq2zhnfWJe/ULkaPQ7FgHEghRi8aI5PsATH6VCaJDKWxl+2bzM7MWlbKRAo8uuu2e" + + "vnGrgnu+RmuXJQCRYz6lG+JESVzm6MnHXYxme+UD+7c/tTYwzoswfXh8VN8QVzXmjfHi2Ve3PJ+Y" + + "uF2X2gKpRMNMf7cLWMCTOhZI2AgXX+NLDlCG0dEUm/DXdSKRTDhm3mIJmF67eGYuff+zHusBZ9cS" + + "BkW9i9"; + String ed25519Key = + "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAII0fBPBUZHaEOBc2mySfmI5btu4mkvFfNRujmF7RH2fj"; + + assertEquals("4d:1a:39:2e:6a:18:60:9a:c5:2a:cb:cc:6c:de:22:b5", + service.importKeyPair("us-east-1", "pinned-rsa", rsaKey).getKeyFingerprint()); + assertEquals("UOyzahv0Ty520U89wfCvKdTlp2TbtpmnlpJHPW3MbMk=", + service.importKeyPair("us-east-1", "pinned-ed25519", ed25519Key).getKeyFingerprint()); + } + @Test void importKeyPairRejectsDuplicateKeyName() { Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),