diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2CreateKeyPairTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2CreateKeyPairTest.java new file mode 100644 index 0000000000..b7f8a43764 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2CreateKeyPairTest.java @@ -0,0 +1,165 @@ +package com.floci.test; + +import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters; +import org.bouncycastle.crypto.util.OpenSSHPrivateKeyUtil; +import org.bouncycastle.crypto.util.OpenSSHPublicKeyUtil; +import org.bouncycastle.util.io.pem.PemReader; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.ec2.Ec2Client; +import software.amazon.awssdk.services.ec2.model.CreateKeyPairResponse; +import software.amazon.awssdk.services.ec2.model.Ec2Exception; +import software.amazon.awssdk.services.ec2.model.KeyFormat; +import software.amazon.awssdk.services.ec2.model.KeyPairInfo; +import software.amazon.awssdk.services.ec2.model.KeyType; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import java.io.ByteArrayOutputStream; +import java.io.StringReader; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Base64; +import java.util.HexFormat; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +@DisplayName("EC2 CreateKeyPair KeyType and KeyFormat") +class Ec2CreateKeyPairTest { + + @Test + @DisplayName("KeyType ed25519 returns an OpenSSH ED25519 private key fingerprinted with SHA-256") + void ed25519ReturnsAnOpenSshPrivateKey() throws Exception { + try (Ec2Client ec2 = TestFixtures.ec2Client()) { + String name = TestFixtures.uniqueName("ed25519-key"); + CreateKeyPairResponse created = ec2.createKeyPair(r -> r.keyName(name).keyType(KeyType.ED25519)); + try { + assertThat(created.keyMaterial()).startsWith("-----BEGIN OPENSSH PRIVATE KEY-----\n"); + Ed25519PrivateKeyParameters key; + try (PemReader reader = new PemReader(new StringReader(created.keyMaterial()))) { + key = (Ed25519PrivateKeyParameters) OpenSSHPrivateKeyUtil.parsePrivateKeyBlob( + reader.readPemObject().getContent()); + } + byte[] blob = OpenSSHPublicKeyUtil.encodePublicKey(key.generatePublicKey()); + + assertThat(created.keyFingerprint()) + .isEqualTo(Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA-256").digest(blob))); + assertThat(describedPublicKey(ec2, created.keyPairId(), KeyType.ED25519)) + .isEqualTo("ssh-ed25519 " + Base64.getEncoder().encodeToString(blob) + " " + name); + } finally { + ec2.deleteKeyPair(r -> r.keyPairId(created.keyPairId())); + } + } + } + + @Test + @DisplayName("KeyFormat ppk returns a PuTTY version 2 key file of the key, named in its comment") + void ppkReturnsAPuttyKeyFile() throws Exception { + try (Ec2Client ec2 = TestFixtures.ec2Client()) { + for (KeyType keyType : List.of(KeyType.RSA, KeyType.ED25519)) { + String name = TestFixtures.uniqueName("ppk-key"); + CreateKeyPairResponse created = ec2.createKeyPair(r -> r.keyName(name).keyType(keyType) + .keyFormat(KeyFormat.PPK)); + try { + String algorithm = keyType == KeyType.RSA ? "ssh-rsa" : "ssh-ed25519"; + List lines = created.keyMaterial().lines().toList(); + assertThat(lines.subList(0, 3)).containsExactly("PuTTY-User-Key-File-2: " + algorithm, + "Encryption: none", "Comment: " + name); + + int publicLines = Integer.parseInt(lines.get(3).substring("Public-Lines: ".length())); + byte[] publicBlob = Base64.getDecoder().decode(String.join("", lines.subList(4, 4 + publicLines))); + int privateHeader = 4 + publicLines; + int privateLines = Integer.parseInt(lines.get(privateHeader).substring("Private-Lines: ".length())); + byte[] privateBlob = Base64.getDecoder().decode( + String.join("", lines.subList(privateHeader + 1, privateHeader + 1 + privateLines))); + String mac = lines.get(privateHeader + 1 + privateLines).substring("Private-MAC: ".length()); + + assertThat(mac).isEqualTo(puttyMac(algorithm, name, publicBlob, privateBlob)); + assertThat(describedPublicKey(ec2, created.keyPairId(), keyType)) + .isEqualTo(algorithm + " " + Base64.getEncoder().encodeToString(publicBlob) + " " + name); + if (keyType == KeyType.ED25519) { + assertThat(created.keyFingerprint()).isEqualTo(Base64.getEncoder().encodeToString( + MessageDigest.getInstance("SHA-256").digest(publicBlob))); + } else { + assertThat(created.keyFingerprint()).matches("([0-9a-f]{2}:){19}[0-9a-f]{2}"); + } + } finally { + ec2.deleteKeyPair(r -> r.keyPairId(created.keyPairId())); + } + } + } + } + + @Test + @DisplayName("A KeyType or KeyFormat outside its enum is InvalidParameterValue") + void unknownTypeOrFormatIsRefused() { + try (Ec2Client ec2 = TestFixtures.ec2Client()) { + String name = TestFixtures.uniqueName("bad-key"); + + assertThatThrownBy(() -> ec2.createKeyPair(r -> r.keyName(name).keyType("ecdsa"))) + .isInstanceOfSatisfying(Ec2Exception.class, e -> { + assertThat(e.awsErrorDetails().errorCode()).isEqualTo("InvalidParameterValue"); + assertThat(e.awsErrorDetails().errorMessage()).isEqualTo("1 validation error detected: " + + "Value 'ecdsa' at 'keyType' failed to satisfy constraint: " + + "Member must satisfy enum value set: [rsa, ed25519]"); + }); + assertThatThrownBy(() -> ec2.createKeyPair(r -> r.keyName(name).keyFormat("der"))) + .isInstanceOfSatisfying(Ec2Exception.class, e -> { + assertThat(e.awsErrorDetails().errorCode()).isEqualTo("InvalidParameterValue"); + assertThat(e.awsErrorDetails().errorMessage()).isEqualTo("1 validation error detected: " + + "Value 'der' at 'keyFormat' failed to satisfy constraint: " + + "Member must satisfy enum value set: [ppk, pem]"); + }); + assertThatThrownBy(() -> ec2.describeKeyPairs(r -> r.keyNames(name))) + .isInstanceOfSatisfying(Ec2Exception.class, e -> + assertThat(e.awsErrorDetails().errorCode()).isEqualTo("InvalidKeyPair.NotFound")); + } + } + + @Test + @DisplayName("DryRun is answered before the key type is checked, and creates nothing") + void dryRunIsAnsweredFirst() { + try (Ec2Client ec2 = TestFixtures.ec2Client()) { + String name = TestFixtures.uniqueName("dry-run-key"); + + assertThatThrownBy(() -> ec2.createKeyPair(r -> r.keyName(name).keyType("ecdsa").dryRun(true))) + .isInstanceOfSatisfying(Ec2Exception.class, e -> { + assertThat(e.statusCode()).isEqualTo(412); + assertThat(e.awsErrorDetails().errorCode()).isEqualTo("DryRunOperation"); + }); + assertThatThrownBy(() -> ec2.describeKeyPairs(r -> r.keyNames(name))) + .isInstanceOfSatisfying(Ec2Exception.class, e -> + assertThat(e.awsErrorDetails().errorCode()).isEqualTo("InvalidKeyPair.NotFound")); + } + } + + /** + * The described public key, without the line break AWS ends it with and Floci does not, once the + * key pair is seen described with the type it was created with. + */ + private static String describedPublicKey(Ec2Client ec2, String keyPairId, KeyType keyType) { + KeyPairInfo described = ec2.describeKeyPairs(r -> r.keyPairIds(keyPairId).includePublicKey(true)) + .keyPairs().get(0); + assertThat(described.keyType()).isEqualTo(keyType); + return described.publicKey().strip(); + } + + /** PuTTY's version 2 MAC of an unencrypted key file, as its sshpubk.c computes it. */ + private static String puttyMac(String algorithm, String comment, byte[] publicBlob, byte[] privateBlob) + throws Exception { + ByteArrayOutputStream data = new ByteArrayOutputStream(); + for (byte[] field : List.of(algorithm.getBytes(StandardCharsets.UTF_8), "none".getBytes(StandardCharsets.UTF_8), + comment.getBytes(StandardCharsets.UTF_8), publicBlob, privateBlob)) { + data.writeBytes(ByteBuffer.allocate(4).putInt(field.length).array()); + data.writeBytes(field); + } + byte[] key = MessageDigest.getInstance("SHA-1") + .digest("putty-private-key-file-mac-key".getBytes(StandardCharsets.US_ASCII)); + Mac hmac = Mac.getInstance("HmacSHA1"); + hmac.init(new SecretKeySpec(key, "HmacSHA1")); + return HexFormat.of().formatHex(hmac.doFinal(data.toByteArray())); + } +} diff --git a/docs/services/ec2.md b/docs/services/ec2.md index 6edcb1609e..7232b137ba 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -113,7 +113,7 @@ The Java metadata-driven builder lives at `io.github.hectorvent.floci.tools.ami. If `KeyName` is specified at launch, Floci looks up the stored key pair's public key (generated by `CreateKeyPair` or supplied to `ImportKeyPair`) and copies it into `/root/.ssh/authorized_keys` inside the container at boot. It then attempts to start `sshd` if present. The SSH port (container port 22) is mapped to a host port from the configured range (default 2200–2299). -Key pairs created with `CreateKeyPair` return real RSA private key material, and the matching public key is injected at launch, so either a created or an imported key pair works for SSH. +Key pairs created with `CreateKeyPair` return real RSA or ED25519 private key material (see [Key Pairs](#key-pairs)), and the matching public key is injected at launch, so either a created or an imported key pair works for SSH. When the image lacks `sshd` or `scp`, Floci first installs OpenSSH with the image's package manager, from a shell that clears `LD_LIBRARY_PATH`, `PYTHONPATH` and `PYTHONHOME` as the IMDS proxy's helper shells do. @@ -336,10 +336,10 @@ imported with; a name holding a control character, such as a line break, is left returns private key material. A key pair saved by an earlier version of Floci is described from what it stored. It has no -`createTime`, and its `keyType` is read from the stored key: `rsa` for a created key pair, -otherwise the type of the imported key, left out when that material would not import now or cannot -be read. Its imported material is kept as it was given, and is what `RunInstances` copies into -`authorized_keys`. Material that is not exactly one whole OpenSSH public key is described without +`createTime`, and its `keyType` is read from the stored public key, created or imported, and is +`rsa` for a created key pair saved before Floci kept its public key; it is left out when imported +material would not import now or cannot be read. Its imported material is kept as it was given, +and is what `RunInstances` copies into `authorized_keys`. Material that is not exactly one whole OpenSSH public key is described without one: PEM, DER or RFC 4716 text, material of more than one line, a line whose blob lacks a field its type requires (such as an `ssh-rsa` blob with no modulus), has bytes after its key or declares a different type than the line names, and a key of any type but `ssh-rsa`, `ssh-ed25519`, @@ -348,11 +348,21 @@ and `sk-ecdsa-sha2-nistp256@openssh.com`. | Action | Description | |--------|-------------| -| CreateKeyPair | Creates and stores a local key pair. | +| CreateKeyPair | Creates an RSA or ED25519 key pair and returns its private key as PEM or as a PuTTY `.ppk` file. | | DescribeKeyPairs | Lists or returns stored key pairs. | | DeleteKeyPair | Deletes a key pair from the local EC2 store. | | ImportKeyPair | Imports a public key as a local key pair. | +`CreateKeyPair` creates a 2048-bit RSA key unless `KeyType=ed25519` asks for an ED25519 key, and +returns its private key as PEM unless `KeyFormat=ppk` asks for a PuTTY key file, in the forms AWS +returns: the PKCS#1 `BEGIN RSA PRIVATE KEY` block for an RSA key, OpenSSH's own +`BEGIN OPENSSH PRIVATE KEY` format for an ED25519 key, and for `ppk` PuTTY's version 2 format, +unencrypted, with the key pair's name as its comment. The fingerprint follows the key's type rather +than its format: the SHA-1 of the DER private key for RSA, as colon-separated hex, and the base64 +SHA-256 of the public key for ED25519, with the `=` padding that `ssh-keygen -l` leaves off. Any other +`KeyType` or `KeyFormat` is `InvalidParameterValue`, and nothing is created. `DryRun=true` is answered +with `DryRunOperation` before any of these checks, and creates nothing either. + ### AMIs | Action | Description | 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 index 6141bbd3de..f5fb53bf00 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2KeyMaterial.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2KeyMaterial.java @@ -9,15 +9,20 @@ import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters; +import org.bouncycastle.crypto.util.OpenSSHPrivateKeyUtil; +import org.bouncycastle.crypto.util.OpenSSHPublicKeyUtil; import org.bouncycastle.openssl.jcajce.JcaPEMWriter; import java.io.IOException; import java.io.StringWriter; +import java.io.UncheckedIOException; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.security.GeneralSecurityException; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; import java.security.interfaces.RSAPublicKey; import java.util.Base64; import java.util.HexFormat; @@ -51,12 +56,18 @@ public final class Ec2KeyMaterial { private static final String RFC_4716_BEGIN = "---- BEGIN SSH2 PUBLIC KEY ----"; private static final String RFC_4716_END = "---- END SSH2 PUBLIC KEY ----"; + /** The base64 line length of ssh-keygen's private key files; readers take any. */ + private static final int OPENSSH_LINE_LENGTH = 70; + 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 + * @param privateKeyPem the private key as KeyMaterial returns it: for an RSA key as PEM, the PKCS#1 + * "BEGIN RSA PRIVATE KEY" form AWS returns, for an ED25519 key as an OpenSSH + * private key, and for KeyFormat ppk as a PuTTY key file + * @param openSshPublicKey the matching "ssh-rsa AAAA..." or "ssh-ed25519 AAAA..." line, for authorized_keys + * @param fingerprint for an RSA key the SHA-1 of the DER private key, colon-separated hex; for an + * ED25519 key the base64 SHA-256 of the public key blob */ public record Generated(String privateKeyPem, String openSshPublicKey, String fingerprint) {} @@ -198,8 +209,7 @@ public final class Ec2KeyMaterial { || !fillsTheBlob(blob, type, key)) { return null; } - return new Imported("ed25519", Base64.getEncoder().encodeToString(Digests.sha256(blob)), - "ssh-ed25519 " + base64(blob)); + return new Imported("ed25519", ed25519Fingerprint(blob), "ssh-ed25519 " + base64(blob)); } private static Imported importedRsa(RSAPublicKey key, String openSshPublicKey) { @@ -290,7 +300,64 @@ public final class Ec2KeyMaterial { return Base64.getEncoder().encodeToString(bytes); } - private static String colonHex(byte[] digest) { + static String colonHex(byte[] digest) { return HexFormat.of().withDelimiter(":").formatHex(digest); } + + /** + * The fingerprint EC2 gives an ED25519 key, created or imported: the base64-encoded SHA-256 of the + * public key blob, the value {@code ssh-keygen -l} prints after {@code SHA256:}, with the {@code =} + * padding AWS keeps and ssh-keygen drops. + */ + private static String ed25519Fingerprint(byte[] blob) { + return base64(Digests.sha256(blob)); + } + + /** A new ED25519 key pair for CreateKeyPair's {@code KeyType=ed25519}. */ + static Generated generateEd25519() { + return ed25519(new Ed25519PrivateKeyParameters(new SecureRandom())); + } + + /** + * The material CreateKeyPair returns for an ED25519 private key: the key in OpenSSH's own private + * key format, the {@code BEGIN OPENSSH PRIVATE KEY} block AWS returns for one, since PKCS#1, the + * RSA form, has no ED25519 encoding. + */ + static Generated ed25519(Ed25519PrivateKeyParameters privateKey) { + byte[] blob; + byte[] encoded; + try { + blob = OpenSSHPublicKeyUtil.encodePublicKey(privateKey.generatePublicKey()); + encoded = OpenSSHPrivateKeyUtil.encodePrivateKey(privateKey); + } catch (IOException e) { + throw new UncheckedIOException("Could not encode an ED25519 key pair", e); + } + String body = base64(encoded); + StringBuilder pem = new StringBuilder("-----BEGIN OPENSSH PRIVATE KEY-----\n"); + for (int i = 0; i < body.length(); i += OPENSSH_LINE_LENGTH) { + pem.append(body, i, Math.min(i + OPENSSH_LINE_LENGTH, body.length())).append('\n'); + } + pem.append("-----END OPENSSH PRIVATE KEY-----\n"); + return new Generated(pem.toString(), "ssh-ed25519 " + base64(blob), ed25519Fingerprint(blob)); + } + + /** + * The key pair CreateKeyPair returns for a KeyType, {@code rsa} or {@code ed25519}, and a + * KeyFormat, {@code pem} or {@code ppk}: a new key of that type, its private half in that format. + * The request has already been refused for any other value. + * + * @param keyName the key pair's name, which a PuTTY key file carries as its comment + */ + public static Generated generate(String keyType, String keyFormat, String keyName) { + Generated pem = switch (keyType) { + case "rsa" -> generateRsa(); + case "ed25519" -> generateEd25519(); + default -> throw new IllegalArgumentException("Unsupported key type: " + keyType); + }; + return switch (keyFormat) { + case "pem" -> pem; + case "ppk" -> Ec2PuttyKeys.of(pem, keyName); + default -> throw new IllegalArgumentException("Unsupported key format: " + keyFormat); + }; + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2PuttyKeys.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2PuttyKeys.java new file mode 100644 index 0000000000..307f4bb61e --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2PuttyKeys.java @@ -0,0 +1,146 @@ +package io.github.hectorvent.floci.services.ec2; + +import io.github.hectorvent.floci.core.common.Digests; +import io.github.hectorvent.floci.core.common.Pem; +import io.github.hectorvent.floci.core.common.SshPublicKeys; +import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters; +import org.bouncycastle.crypto.util.OpenSSHPrivateKeyUtil; +import org.bouncycastle.util.io.pem.PemReader; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.StringReader; +import java.io.UncheckedIOException; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.KeyFactory; +import java.security.interfaces.RSAPrivateCrtKey; +import java.security.spec.RSAPrivateCrtKeySpec; +import java.util.Base64; +import java.util.HexFormat; + +/** + * The key pair CreateKeyPair returns for {@code KeyFormat=ppk}: the key it creates for PEM, written + * as a PuTTY private key file instead. + * + *

The file is version 2 of PuTTY's format, unencrypted, with the key pair's name as its comment, + * which is what AWS returns for an RSA and an ED25519 key alike; every PuTTY release since 0.52 reads + * version 2, and since 0.68 for an ED25519 key. It is laid out as PuTTY's sshpubk.c writes it: a line + * naming the key's algorithm, {@code Encryption: none}, the comment, the public key blob and the + * private fields as counted lines of base64, 64 characters to a line, and a {@code Private-MAC}, the + * HMAC-SHA1 of the algorithm, the encryption, the comment and both blobs, each as an SSH string, keyed + * with the SHA-1 of {@code putty-private-key-file-mac-key} followed by the passphrase, empty here. + * + *

The public key and the fingerprint are the PEM key's, but for the order of an RSA key's primes: + * PuTTY keeps the larger first, which Java's key generator does not ensure, so the key is written in + * that order and fingerprinted, by the SHA-1 of its DER private key, as written. That is the key + * PuTTYgen exports from the file. + * + * @see PuTTY's key file format + */ +final class Ec2PuttyKeys { + + private static final int LINE_LENGTH = 64; + + private Ec2PuttyKeys() {} + + /** + * {@code pem} as a PuTTY key file whose comment is {@code keyName}, or empty for a name holding a + * control character, such as a line break, since the comment is a line of the file. + */ + static Ec2KeyMaterial.Generated of(Ec2KeyMaterial.Generated pem, String keyName) { + byte[] publicBlob = SshPublicKeys.decodeBlob(pem.openSshPublicKey()); + String algorithm = SshPublicKeys.keyType(publicBlob); + String comment = keyName == null || keyName.chars().anyMatch(Character::isISOControl) ? "" : keyName; + return switch (algorithm) { + case "ssh-rsa" -> { + RSAPrivateCrtKey key = largerPrimeFirst((RSAPrivateCrtKey) Pem.parsePrivateKey(pem.privateKeyPem())); + // PuTTY's ssh-rsa private fields: the private exponent, the primes and the inverse of the + // second prime modulo the first. + byte[] privateBlob = strings(key.getPrivateExponent().toByteArray(), key.getPrimeP().toByteArray(), + key.getPrimeQ().toByteArray(), key.getCrtCoefficient().toByteArray()); + yield new Ec2KeyMaterial.Generated(file(algorithm, comment, publicBlob, privateBlob), + pem.openSshPublicKey(), Ec2KeyMaterial.colonHex(Digests.sha1(key.getEncoded()))); + } + // PuTTY's ssh-ed25519 private field: the 32-byte private key, without OpenSSH's copy of the public key. + case "ssh-ed25519" -> new Ec2KeyMaterial.Generated( + file(algorithm, comment, publicBlob, strings(ed25519PrivateKey(pem.privateKeyPem()))), + pem.openSshPublicKey(), pem.fingerprint()); + default -> throw new IllegalArgumentException("No PuTTY key file for a " + algorithm + " key"); + }; + } + + private static String file(String algorithm, String comment, byte[] publicBlob, byte[] privateBlob) { + StringBuilder file = new StringBuilder() + .append("PuTTY-User-Key-File-2: ").append(algorithm).append('\n') + .append("Encryption: none\n") + .append("Comment: ").append(comment).append('\n'); + appendLines(file, "Public-Lines", publicBlob); + appendLines(file, "Private-Lines", privateBlob); + byte[] mac = mac(strings(ascii(algorithm), ascii("none"), comment.getBytes(StandardCharsets.UTF_8), + publicBlob, privateBlob)); + return file.append("Private-MAC: ").append(HexFormat.of().formatHex(mac)).append('\n').toString(); + } + + private static void appendLines(StringBuilder file, String header, byte[] blob) { + String base64 = Base64.getEncoder().encodeToString(blob); + file.append(header).append(": ").append((base64.length() + LINE_LENGTH - 1) / LINE_LENGTH).append('\n'); + for (int i = 0; i < base64.length(); i += LINE_LENGTH) { + file.append(base64, i, Math.min(i + LINE_LENGTH, base64.length())).append('\n'); + } + } + + private static byte[] mac(byte[] data) { + try { + Mac hmac = Mac.getInstance("HmacSHA1"); + hmac.init(new SecretKeySpec(Digests.sha1(ascii("putty-private-key-file-mac-key")), "HmacSHA1")); + return hmac.doFinal(data); + } catch (GeneralSecurityException e) { + throw new IllegalStateException("HMAC-SHA1 is unavailable", e); + } + } + + /** The key with its larger prime first, the order PuTTY stores, and its CRT values for that order. */ + private static RSAPrivateCrtKey largerPrimeFirst(RSAPrivateCrtKey key) { + if (key.getPrimeP().compareTo(key.getPrimeQ()) > 0) { + return key; + } + BigInteger p = key.getPrimeQ(); + BigInteger q = key.getPrimeP(); + BigInteger d = key.getPrivateExponent(); + try { + return (RSAPrivateCrtKey) KeyFactory.getInstance("RSA").generatePrivate(new RSAPrivateCrtKeySpec( + key.getModulus(), key.getPublicExponent(), d, p, q, d.mod(p.subtract(BigInteger.ONE)), + d.mod(q.subtract(BigInteger.ONE)), q.modInverse(p))); + } catch (GeneralSecurityException e) { + throw new IllegalStateException("Could not reorder the RSA key's primes", e); + } + } + + private static byte[] ed25519PrivateKey(String openSshPem) { + try (PemReader reader = new PemReader(new StringReader(openSshPem))) { + return ((Ed25519PrivateKeyParameters) OpenSSHPrivateKeyUtil.parsePrivateKeyBlob( + reader.readPemObject().getContent())).getEncoded(); + } catch (IOException e) { + throw new UncheckedIOException("Could not read the ED25519 key", e); + } + } + + /** SSH strings: each field as a four-byte length and then its bytes. */ + private static byte[] strings(byte[]... fields) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + for (byte[] field : fields) { + out.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(field.length).array()); + out.writeBytes(field); + } + return out.toByteArray(); + } + + private static byte[] ascii(String text) { + return text.getBytes(StandardCharsets.US_ASCII); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java index fdc778fc93..a7774a8061 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java @@ -3419,8 +3419,10 @@ public class Ec2QueryHandler { } private Response handleCreateKeyPair(MultivaluedMap p, String region) { + // AWS answers DryRun before it checks the name or the key type. + checkDryRun(p); String keyName = requireKeyName(p); - KeyPair kp = service.createKeyPair(region, keyName); + KeyPair kp = service.createKeyPair(region, keyName, p.getFirst("KeyType"), p.getFirst("KeyFormat")); XmlBuilder xml = new XmlBuilder() .start("CreateKeyPairResponse", AwsNamespaces.EC2) .elem("requestId", UUID.randomUUID().toString()) 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 0516f4589c..5923f58a1d 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 @@ -14,6 +14,7 @@ import io.github.hectorvent.floci.core.common.PaginatedResult; import io.github.hectorvent.floci.core.common.RequestContext; import io.github.hectorvent.floci.core.common.RequestScopes; import io.github.hectorvent.floci.core.common.Resettable; +import io.github.hectorvent.floci.core.common.SmithyValidationErrors; import io.github.hectorvent.floci.core.resource.ExplorerResource; import io.github.hectorvent.floci.core.resource.ResourceProvider; import io.github.hectorvent.floci.core.resource.SupportedResourceType; @@ -7411,20 +7412,33 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab // ─── Key Pairs ───────────────────────────────────────────────────────────── public KeyPair createKeyPair(String region, String keyName) { + return createKeyPair(region, keyName, null, null); + } + + /** + * Creates a key pair of {@code keyType}, {@code rsa} when null, and returns its private key in + * {@code keyFormat}, {@code pem} when null. A value outside either enum is refused with the message + * AWS's request validation gives; Floci checks the values after the name is found present and + * valid and before it is found taken. + */ + public KeyPair createKeyPair(String region, String keyName, String keyType, String keyFormat) { ensureDefaultResources(region); requireKeyName(keyName); + String type = keyType != null ? keyType : "rsa"; + String format = keyFormat != null ? keyFormat : "pem"; + requireKeyTypeAndFormat(type, format); rejectDuplicateKeyName(region, keyName); String keyPairId = "key-" + randomHex(17); KeyPair kp = new KeyPair(); kp.setKeyPairId(keyPairId); kp.setKeyName(keyName); - Ec2KeyMaterial.Generated generated = Ec2KeyMaterial.generateRsa(); + Ec2KeyMaterial.Generated generated = Ec2KeyMaterial.generate(type, format, keyName); 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.setKeyType("rsa"); + kp.setKeyType(type); kp.setCreateTime(Instant.now()); kp.setRegion(region); keyPairs.put(key(region, keyPairId), kp); @@ -7480,26 +7494,27 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab /** * The key type DescribeKeyPairs reports. A key pair stored before the type was recorded has it - * read from what it holds: rsa when CreateKeyPair made it, since that has only ever generated - * RSA keys, and otherwise the type of its imported key, or none when ImportKeyPair would now - * refuse that material or reading it fails, which is logged. + * read from the public key it holds, whether CreateKeyPair made it or ImportKeyPair took it. A + * created key pair saved before created key pairs kept their public key is rsa, the only type + * CreateKeyPair made then. Otherwise it has none, when ImportKeyPair would now refuse the + * material or reading it fails, which is logged. */ static String keyTypeOf(KeyPair keyPair) { if (keyPair.getKeyType() != null) { return keyPair.getKeyType(); } - if (keyPair.getKeyMaterial() != null) { - return "rsa"; - } try { - Ec2KeyMaterial.Imported imported = Ec2KeyMaterial.readImportedKey(keyPair.getPublicKey()); - return imported != null ? imported.keyType() : null; + Ec2KeyMaterial.Imported key = Ec2KeyMaterial.readImportedKey(keyPair.getPublicKey()); + if (key != null) { + return key.keyType(); + } } catch (RuntimeException e) { // The record may hold any text an earlier ImportKeyPair stored. Text the reader cannot // handle leaves the type out instead of failing every description in the region. LOG.warnv(e, "Could not read the key type of stored key pair {0}", keyPair.getKeyPairId()); return null; } + return keyPair.getKeyMaterial() != null ? "rsa" : null; } /** @@ -7631,6 +7646,22 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab } } + /** KeyType and KeyFormat take only the values AWS's model lists; each other value is reported. */ + private static void requireKeyTypeAndFormat(String keyType, String keyFormat) { + List violations = new ArrayList<>(); + if (!List.of("rsa", "ed25519").contains(keyType)) { + violations.add("Value '" + keyType + "' at 'keyType' failed to satisfy constraint: " + + "Member must satisfy enum value set: [rsa, ed25519]"); + } + if (!List.of("ppk", "pem").contains(keyFormat)) { + violations.add("Value '" + keyFormat + "' at 'keyFormat' failed to satisfy constraint: " + + "Member must satisfy enum value set: [ppk, pem]"); + } + if (!violations.isEmpty()) { + throw SmithyValidationErrors.exception("InvalidParameterValue", violations); + } + } + public KeyPair findKeyPair(String region, String keyName) { if (keyName == null) { return null; diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CreateKeyPairIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CreateKeyPairIntegrationTest.java new file mode 100644 index 0000000000..15cc49282d --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CreateKeyPairIntegrationTest.java @@ -0,0 +1,246 @@ +package io.github.hectorvent.floci.services.ec2; + +import io.github.hectorvent.floci.core.common.Digests; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.path.xml.XmlPath; +import io.restassured.specification.RequestSpecification; +import org.bouncycastle.openssl.PEMKeyPair; +import org.bouncycastle.openssl.PEMParser; +import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.io.IOException; +import java.io.StringReader; +import java.security.interfaces.RSAPrivateCrtKey; +import java.util.Base64; +import java.util.HexFormat; +import java.util.UUID; + +import static io.github.hectorvent.floci.services.ec2.Ec2KeyPairFixtures.createKeyPair; +import static io.github.hectorvent.floci.services.ec2.Ec2KeyPairFixtures.deleteKeyPair; +import static io.github.hectorvent.floci.services.ec2.Ec2KeyPairFixtures.ec2; +import static io.github.hectorvent.floci.services.ec2.Ec2KeyPairFixtures.firstLine; +import static io.github.hectorvent.floci.services.ec2.Ec2KeyPairFixtures.importKeyPair; +import static io.github.hectorvent.floci.services.ec2.Ec2KeyPairFixtures.openSshEd25519Key; +import static io.github.hectorvent.floci.services.ec2.Ec2KeyPairFixtures.sshEd25519Blob; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * CreateKeyPair's KeyType and KeyFormat over the Query protocol. AWS creates an ED25519 key for + * KeyType=ed25519 and returns either type as a PuTTY file for KeyFormat=ppk; the fingerprint + * follows the key's type, not its format, and a value outside either parameter's enum is refused. + * + *

The material is parsed and checked against the fingerprint and the public key DescribeKeyPairs + * reports, rather than matched against a header alone. + */ +@QuarkusTest +class Ec2CreateKeyPairIntegrationTest { + + @Test + void ed25519IsAnOpenSshPrivateKeyFingerprintedWithSha256() throws IOException { + String name = uniqueName(); + XmlPath created = createKeyPair(name, "ed25519", null).statusCode(200).extract().xmlPath(); + String id = created.getString("CreateKeyPairResponse.keyPairId"); + try { + String material = created.getString("CreateKeyPairResponse.keyMaterial"); + assertEquals("-----BEGIN OPENSSH PRIVATE KEY-----", firstLine(material)); + assertTrue(material.endsWith("-----END OPENSSH PRIVATE KEY-----\n"), "the block ends its last line"); + byte[] blob = sshEd25519Blob(openSshEd25519Key(material)); + + // "the base64-encoded SHA-256 digest", padded as AWS reports it + assertEquals(Base64.getEncoder().encodeToString(Digests.sha256(blob)), + created.getString("CreateKeyPairResponse.keyFingerprint")); + assertDescribedAs(name, id, blob, "ed25519"); + } finally { + deleteKeyPair(id); + } + } + + @Test + void anEd25519KeyImportedAfterItWasCreatedHasTheSameFingerprint() throws IOException { + // AWS fingerprints an ED25519 key the same way whether it created the key or was given it. + String name = uniqueName(); + XmlPath created = createKeyPair(name, "ed25519", null).statusCode(200).extract().xmlPath(); + String importedId = null; + try { + String publicKey = "ssh-ed25519 " + Base64.getEncoder().encodeToString( + sshEd25519Blob(openSshEd25519Key(created.getString("CreateKeyPairResponse.keyMaterial")))); + XmlPath imported = importKeyPair(name + "-imported", publicKey).statusCode(200).extract().xmlPath(); + importedId = imported.getString("ImportKeyPairResponse.keyPairId"); + + assertEquals(created.getString("CreateKeyPairResponse.keyFingerprint"), + imported.getString("ImportKeyPairResponse.keyFingerprint")); + } finally { + deleteKeyPair(created.getString("CreateKeyPairResponse.keyPairId")); + if (importedId != null) { + deleteKeyPair(importedId); + } + } + } + + @ParameterizedTest + @ValueSource(strings = {"rsa", "ed25519"}) + void ppkIsAPuttyFileOfTheKeyWithTheNameAsItsComment(String keyType) throws Exception { + String name = uniqueName(); + XmlPath created = createKeyPair(name, keyType, "ppk").statusCode(200).extract().xmlPath(); + String id = created.getString("CreateKeyPairResponse.keyPairId"); + try { + PuttyKeyFile file = PuttyKeyFile.parse(created.getString("CreateKeyPairResponse.keyMaterial")); + assertEquals("rsa".equals(keyType) ? "ssh-rsa" : "ssh-ed25519", file.algorithm()); + assertEquals("none", file.encryption()); + assertEquals(name, file.comment()); + assertTrue(file.macIsValid(), "Private-MAC is PuTTY's HMAC-SHA1 over the file"); + + // A key EC2 creates is fingerprinted from the key, whichever format it is returned in. + String fingerprint = "rsa".equals(keyType) + ? colonHex(Digests.sha1(file.rsaKey().getEncoded())) + : Base64.getEncoder().encodeToString(Digests.sha256(sshEd25519Blob(file.ed25519Key()))); + assertEquals(fingerprint, created.getString("CreateKeyPairResponse.keyFingerprint")); + assertDescribedAs(name, id, file.publicBlob(), keyType); + } finally { + deleteKeyPair(id); + } + } + + @Test + void rsaPemIsStillThePkcs1KeyFingerprintedWithSha1() throws IOException { + String name = uniqueName(); + XmlPath created = createKeyPair(name, "rsa", "pem").statusCode(200).extract().xmlPath(); + String id = created.getString("CreateKeyPairResponse.keyPairId"); + try { + String material = created.getString("CreateKeyPairResponse.keyMaterial"); + assertEquals("-----BEGIN RSA PRIVATE KEY-----", firstLine(material)); + Object parsed = new PEMParser(new StringReader(material)).readObject(); + RSAPrivateCrtKey key = (RSAPrivateCrtKey) new JcaPEMKeyConverter() + .getKeyPair((PEMKeyPair) parsed).getPrivate(); + assertEquals(2048, key.getModulus().bitLength()); + // "the SHA-1 digest of the DER encoded private key", PKCS#8 as openssl pkcs8 -topk8 writes it + assertEquals(colonHex(Digests.sha1(key.getEncoded())), + created.getString("CreateKeyPairResponse.keyFingerprint")); + } finally { + deleteKeyPair(id); + } + } + + @Test + void anUnknownKeyTypeIsRefusedAndNothingIsCreated() { + String name = uniqueName(); + createKeyPair(name, "ecdsa", null) + .statusCode(400) + .body("Response.Errors.Error.Code", equalTo("InvalidParameterValue")) + .body("Response.Errors.Error.Message", equalTo("1 validation error detected: Value 'ecdsa' at " + + "'keyType' failed to satisfy constraint: Member must satisfy enum value set: [rsa, ed25519]")); + assertNotCreated(name); + } + + @Test + void anUnknownKeyFormatIsRefusedAndNothingIsCreated() { + String name = uniqueName(); + createKeyPair(name, null, "der") + .statusCode(400) + .body("Response.Errors.Error.Code", equalTo("InvalidParameterValue")) + .body("Response.Errors.Error.Message", equalTo("1 validation error detected: Value 'der' at " + + "'keyFormat' failed to satisfy constraint: Member must satisfy enum value set: [ppk, pem]")); + assertNotCreated(name); + } + + /** Floci's order for two violations: KeyType's before KeyFormat's, the model's member order. */ + @Test + void anUnknownKeyTypeAndFormatAreReportedTogether() { + String name = uniqueName(); + createKeyPair(name, "ecdsa", "der") + .statusCode(400) + .body("Response.Errors.Error.Code", equalTo("InvalidParameterValue")) + .body("Response.Errors.Error.Message", equalTo("2 validation errors detected: Value 'ecdsa' at " + + "'keyType' failed to satisfy constraint: Member must satisfy enum value set: [rsa, ed25519]; " + + "Value 'der' at 'keyFormat' failed to satisfy constraint: Member must satisfy enum value set: " + + "[ppk, pem]")); + assertNotCreated(name); + } + + /** Floci checks the values before it looks for a key pair with that name. */ + @Test + void anUnknownKeyTypeIsRefusedBeforeTheNameIsFoundTaken() { + String name = uniqueName(); + String id = createKeyPair(name, null, null).statusCode(200).extract().path("CreateKeyPairResponse.keyPairId"); + try { + createKeyPair(name, "dsa", null) + .statusCode(400) + .body("Response.Errors.Error.Code", equalTo("InvalidParameterValue")); + } finally { + deleteKeyPair(id); + } + } + + /** + * AWS answers DryRun before any other check on the request, a taken or empty name and an unknown + * type included, and creates nothing. + */ + @ParameterizedTest + @CsvSource(value = {"new,NULL", "taken,NULL", "empty,NULL", "new,ecdsa"}, nullValues = "NULL") + void aDryRunIsAnsweredBeforeAnyOtherCheckAndCreatesNothing(String nameKind, String keyType) { + String name = "empty".equals(nameKind) ? "" : uniqueName(); + String takenId = "taken".equals(nameKind) + ? createKeyPair(name, null, null).statusCode(200).extract().path("CreateKeyPairResponse.keyPairId") + : null; + try { + RequestSpecification dryRun = ec2("CreateKeyPair") + .formParam("KeyName", name) + .formParam("DryRun", "true"); + if (keyType != null) { + dryRun.formParam("KeyType", keyType); + } + dryRun.post("/").then() + .statusCode(412) + .body("Response.Errors.Error.Code", equalTo("DryRunOperation")) + .body("Response.Errors.Error.Message", + equalTo("Request would have succeeded, but DryRun flag is set.")); + if ("new".equals(nameKind)) { + assertNotCreated(name); + } + } finally { + if (takenId != null) { + deleteKeyPair(takenId); + } + } + } + + /** + * DescribeKeyPairs reports the public half of the created key with the key-pair name as its + * comment and the type that was created. AWS ends the reported key with a line break and Floci + * does not, so the line is compared without it. + */ + private static void assertDescribedAs(String name, String id, byte[] blob, String keyType) { + String type = "rsa".equals(keyType) ? "ssh-rsa" : "ssh-ed25519"; + XmlPath described = ec2("DescribeKeyPairs") + .formParam("KeyPairId.1", id) + .formParam("IncludePublicKey", "true") + .post("/").then().statusCode(200) + .body("DescribeKeyPairsResponse.keySet.item.keyName", equalTo(name)) + .extract().xmlPath(); + assertEquals(type + " " + Base64.getEncoder().encodeToString(blob) + " " + name, + described.getString("DescribeKeyPairsResponse.keySet.item.publicKey").strip()); + assertEquals(keyType, described.getString("DescribeKeyPairsResponse.keySet.item.keyType"), + "the type of an " + keyType + " key pair"); + } + + private static void assertNotCreated(String name) { + ec2("DescribeKeyPairs") + .formParam("KeyName.1", name) + .post("/").then().statusCode(400) + .body("Response.Errors.Error.Code", equalTo("InvalidKeyPair.NotFound")); + } + + private static String colonHex(byte[] digest) { + return HexFormat.of().withDelimiter(":").formatHex(digest); + } + + private static String uniqueName() { + return "create-key-pair-" + UUID.randomUUID(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CreateKeyPairLaunchIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CreateKeyPairLaunchIntegrationTest.java new file mode 100644 index 0000000000..af95cd65ff --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CreateKeyPairLaunchIntegrationTest.java @@ -0,0 +1,83 @@ +package io.github.hectorvent.floci.services.ec2; + +import io.github.hectorvent.floci.services.ec2.model.Instance; +import io.quarkus.test.InjectMock; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.path.xml.XmlPath; +import jakarta.inject.Inject; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.ArgumentCaptor; + +import java.util.Base64; +import java.util.List; +import java.util.UUID; + +import static io.github.hectorvent.floci.services.ec2.Ec2KeyPairFixtures.REGION; +import static io.github.hectorvent.floci.services.ec2.Ec2KeyPairFixtures.createKeyPair; +import static io.github.hectorvent.floci.services.ec2.Ec2KeyPairFixtures.deleteKeyPair; +import static io.github.hectorvent.floci.services.ec2.Ec2KeyPairFixtures.openSshEd25519Key; +import static io.github.hectorvent.floci.services.ec2.Ec2KeyPairFixtures.sshEd25519Blob; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * RunInstances copies a key pair's stored public key into the guest's authorized_keys, so an ED25519 + * key pair from CreateKeyPair has to be launched with the public half of the ED25519 key it returned, + * in either format. + * + *

It shares the application of {@link Ec2CapturedImageReclaimIntegrationTest}, which turns EC2's + * mock mode off so that a launch reaches the container manager, mocked here as there. + */ +@QuarkusTest +@TestProfile(Ec2CapturedImageReclaimIntegrationTest.ContainerBackedEc2.class) +class Ec2CreateKeyPairLaunchIntegrationTest { + + @Inject + Ec2Service service; + + @InjectMock + Ec2ContainerManager containerManager; + + @InjectMock + AmiImageResolver amiImageResolver; + + @BeforeEach + void resolveEveryAmiToABaseImage() { + when(amiImageResolver.resolveImage(anyString())).thenReturn(ResolvedAmiImage.minimal("floci/base:latest")); + } + + @ParameterizedTest + @ValueSource(strings = {"pem", "ppk"}) + void anEd25519KeyPairIsLaunchedWithThePublicHalfOfTheKeyItReturned(String keyFormat) throws Exception { + String name = "launch-key-" + UUID.randomUUID(); + XmlPath created = createKeyPair(name, "ed25519", keyFormat).statusCode(200).extract().xmlPath(); + Instance instance = null; + try { + String material = created.getString("CreateKeyPairResponse.keyMaterial"); + byte[] blob = "pem".equals(keyFormat) + ? sshEd25519Blob(openSshEd25519Key(material)) + : PuttyKeyFile.parse(material).publicBlob(); + + instance = service.runInstances(REGION, "ami-amazonlinux2023", "t3.micro", 1, 1, name, + List.of(), null, null, List.of(), null, null).getInstances().getFirst(); + + ArgumentCaptor injected = ArgumentCaptor.forClass(String.class); + verify(containerManager).launch(eq(instance), any(), injected.capture(), anyString(), any(), any(), any()); + assertEquals("ssh-ed25519 " + Base64.getEncoder().encodeToString(blob), injected.getValue()); + } finally { + // The application is shared with another class: the key pair goes, and the instance gives + // back its address and volume, though the mocked container manager leaves its record pending. + if (instance != null) { + service.terminateInstances(REGION, List.of(instance.getInstanceId())); + } + deleteKeyPair(created.getString("CreateKeyPairResponse.keyPairId")); + } + } +} 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 index 6ef617f7b4..c031bd0d39 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2KeyMaterialTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2KeyMaterialTest.java @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.services.ec2; +import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters; import org.bouncycastle.openssl.PEMKeyPair; import org.bouncycastle.openssl.PEMParser; import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; @@ -8,6 +9,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; +import java.io.IOException; import java.io.StringReader; import java.math.BigInteger; import java.nio.ByteBuffer; @@ -27,12 +29,18 @@ import static io.github.hectorvent.floci.services.ec2.Ec2KeyPairFixtures.ECDSA_P import static io.github.hectorvent.floci.services.ec2.Ec2KeyPairFixtures.ED25519_BLOB; import static io.github.hectorvent.floci.services.ec2.Ec2KeyPairFixtures.ED25519_FINGERPRINT; import static io.github.hectorvent.floci.services.ec2.Ec2KeyPairFixtures.ED25519_KEY; +import static io.github.hectorvent.floci.services.ec2.Ec2KeyPairFixtures.PUTTY_TEST_KEY; +import static io.github.hectorvent.floci.services.ec2.Ec2KeyPairFixtures.PUTTY_TEST_PUBLIC_KEY; import static io.github.hectorvent.floci.services.ec2.Ec2KeyPairFixtures.RSA_FINGERPRINT; import static io.github.hectorvent.floci.services.ec2.Ec2KeyPairFixtures.RSA_KEY; +import static io.github.hectorvent.floci.services.ec2.Ec2KeyPairFixtures.openSshEd25519Key; +import static io.github.hectorvent.floci.services.ec2.Ec2KeyPairFixtures.sshEd25519Blob; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; 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.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; /** @@ -591,4 +599,47 @@ class Ec2KeyMaterialTest { blob.get(field); return field; } + + @Test + void theFingerprintIsSshKeygensSha256WithThePaddingAwsKeeps() { + // Derived outside this code: "ssh-keygen -l -f" on the public key prints + // 256 SHA256:Mv99xcHfjQuHbqmIs0Qx5I9kr7lX7Yw97eh4jZtoS70 no comment (ED25519) + Ec2KeyMaterial.Generated key = Ec2KeyMaterial.ed25519(new Ed25519PrivateKeyParameters(PUTTY_TEST_KEY, 0)); + + assertEquals("Mv99xcHfjQuHbqmIs0Qx5I9kr7lX7Yw97eh4jZtoS70=", key.fingerprint()); + assertEquals(PUTTY_TEST_PUBLIC_KEY, key.openSshPublicKey()); + } + + @Test + void thePrivateKeyIsAnOpenSshKeyFileOfTheSameKey() throws IOException { + Ec2KeyMaterial.Generated key = Ec2KeyMaterial.ed25519(new Ed25519PrivateKeyParameters(PUTTY_TEST_KEY, 0)); + + List lines = key.privateKeyPem().lines().toList(); + assertEquals("-----BEGIN OPENSSH PRIVATE KEY-----", lines.getFirst()); + assertEquals("-----END OPENSSH PRIVATE KEY-----", lines.getLast()); + assertTrue(key.privateKeyPem().endsWith("\n")); + // ssh-keygen's line length, though OpenSSH reads any + lines.subList(1, lines.size() - 2).forEach(line -> assertEquals(70, line.length(), line)); + assertArrayEquals(PUTTY_TEST_KEY, openSshEd25519Key(key.privateKeyPem()).getEncoded()); + } + + @Test + void everyGeneratedKeyIsNewAndMatchesItsPublicHalf() throws IOException { + Ec2KeyMaterial.Generated first = Ec2KeyMaterial.generate("ed25519", "pem", "first"); + Ec2KeyMaterial.Generated second = Ec2KeyMaterial.generate("ed25519", "pem", "second"); + + assertNotEquals(first.openSshPublicKey(), second.openSshPublicKey()); + assertNotEquals(first.fingerprint(), second.fingerprint()); + for (Ec2KeyMaterial.Generated key : List.of(first, second)) { + byte[] blob = sshEd25519Blob(openSshEd25519Key(key.privateKeyPem())); + assertEquals("ssh-ed25519 " + Base64.getEncoder().encodeToString(blob), key.openSshPublicKey()); + } + } + + @Test + void aTypeOrFormatAwsDoesNotOfferIsNotGenerated() { + // The request is refused before this point; reaching it with another value is a bug, not a default. + assertThrows(IllegalArgumentException.class, () -> Ec2KeyMaterial.generate("ecdsa", "pem", "name")); + assertThrows(IllegalArgumentException.class, () -> Ec2KeyMaterial.generate("rsa", "der", "name")); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2KeyPairFixtures.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2KeyPairFixtures.java index aa74d3be51..f0b8de10e8 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2KeyPairFixtures.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2KeyPairFixtures.java @@ -2,16 +2,28 @@ package io.github.hectorvent.floci.services.ec2; import io.restassured.response.ValidatableResponse; import io.restassured.specification.RequestSpecification; +import org.bouncycastle.crypto.params.AsymmetricKeyParameter; +import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters; +import org.bouncycastle.crypto.util.OpenSSHPrivateKeyUtil; +import org.bouncycastle.crypto.util.OpenSSHPublicKeyUtil; +import org.bouncycastle.util.io.pem.PemObject; +import org.bouncycastle.util.io.pem.PemReader; +import java.io.IOException; +import java.io.StringReader; import java.nio.charset.StandardCharsets; import java.util.Base64; +import java.util.HexFormat; import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** The key pair calls and the throwaway keys shared by the EC2 key pair tests. */ final class Ec2KeyPairFixtures { - static final String AUTH = "AWS4-HMAC-SHA256 Credential=test/20261020/us-east-1/ec2/aws4_request"; + static final String REGION = "us-east-1"; + static final String AUTH = "AWS4-HMAC-SHA256 Credential=test/20261020/" + REGION + "/ec2/aws4_request"; /** A throwaway 2048-bit RSA key. */ static final String RSA_KEY = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCp7mGC9" @@ -40,6 +52,15 @@ final class Ec2KeyPairFixtures { */ static final String ED25519_FINGERPRINT = "UOyzahv0Ty520U89wfCvKdTlp2TbtpmnlpJHPW3MbMk="; + /** + * The throwaway ED25519 key of the version 2 key file in PuTTY's test suite (test/cryptsuite.py, + * testPPKLoadSave): its 32-byte private key, and its public key line. + */ + static final byte[] PUTTY_TEST_KEY = + HexFormat.of().parseHex("6bef22997c8f2aa7f17b9f930eafdc59c41ad5c5dca5b0e7900fdff006101a58"); + static final String PUTTY_TEST_PUBLIC_KEY = + "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHJCszOHaI9X/yGLtjn22f0hO6VPMQDVtctkym6FJH1W"; + /** A throwaway DSA key from {@code ssh-keygen -t dsa}. */ static final String DSA_KEY = "ssh-dss AAAAB3NzaC1kc3MAAACBAOFToDsRbL7Z8AqAZOKXROc1Cy5SA1ZgM5odRC57" + "MSEruUjfUv2//jGbOLemgQBFsqZY1dyKlrpR3dm+tpfXGQR26Pkqm+5BF8kaykQZAYdwCzRhwzM7c8pei36Qi2XJ1s+MeLbIXZ2TTf" @@ -66,7 +87,19 @@ final class Ec2KeyPairFixtures { /** CreateKeyPair with this name, whatever the answer. */ static ValidatableResponse createKeyPair(String name) { - return ec2("CreateKeyPair").formParam("KeyName", name).post("/").then(); + return createKeyPair(name, null, null); + } + + /** CreateKeyPair with this name, and the KeyType and KeyFormat when they are not null. */ + static ValidatableResponse createKeyPair(String name, String keyType, String keyFormat) { + RequestSpecification request = ec2("CreateKeyPair").formParam("KeyName", name); + if (keyType != null) { + request.formParam("KeyType", keyType); + } + if (keyFormat != null) { + request.formParam("KeyFormat", keyFormat); + } + return request.post("/").then(); } /** ImportKeyPair with this name and material, the material base64-encoded as the API takes it. */ @@ -100,4 +133,25 @@ final class Ec2KeyPairFixtures { static void deleteKeyPair(String id) { ec2("DeleteKeyPair").formParam("KeyPairId", id).post("/").then().statusCode(200); } + + /** The ED25519 key of an OpenSSH private key file, read with Bouncy Castle's OpenSSH reader. */ + static Ed25519PrivateKeyParameters openSshEd25519Key(String material) throws IOException { + try (PemReader reader = new PemReader(new StringReader(material))) { + PemObject pem = reader.readPemObject(); + assertEquals("OPENSSH PRIVATE KEY", pem.getType()); + AsymmetricKeyParameter key = OpenSSHPrivateKeyUtil.parsePrivateKeyBlob(pem.getContent()); + assertTrue(key instanceof Ed25519PrivateKeyParameters, "expected an ED25519 key, got " + key); + return (Ed25519PrivateKeyParameters) key; + } + } + + /** The OpenSSH public key blob of an ED25519 key. */ + static byte[] sshEd25519Blob(Ed25519PrivateKeyParameters key) throws IOException { + return OpenSSHPublicKeyUtil.encodePublicKey(key.generatePublicKey()); + } + + /** The first line of key material, which a failure message can show without disclosing the key. */ + static String firstLine(String material) { + return material.lines().findFirst().orElse(""); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2PuttyKeysTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2PuttyKeysTest.java new file mode 100644 index 0000000000..08fd33f43f --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2PuttyKeysTest.java @@ -0,0 +1,136 @@ +package io.github.hectorvent.floci.services.ec2; + +import io.github.hectorvent.floci.core.common.Digests; +import io.github.hectorvent.floci.core.common.Pem; +import io.github.hectorvent.floci.core.common.SshPublicKeys; +import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.security.interfaces.RSAPrivateCrtKey; +import java.util.HexFormat; + +import static io.github.hectorvent.floci.services.ec2.Ec2KeyPairFixtures.PUTTY_TEST_KEY; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class Ec2PuttyKeysTest { + + /** + * The unencrypted version 2 file PuTTY's own test suite (test/cryptsuite.py, testPPKLoadSave) + * checks its writer against, byte for byte, for {@link Ec2KeyPairFixtures#PUTTY_TEST_KEY}. + */ + private static final String PUTTY_TEST_FILE = """ + PuTTY-User-Key-File-2: ssh-ed25519 + Encryption: none + Comment: ed25519-key-20200105 + Public-Lines: 2 + AAAAC3NzaC1lZDI1NTE5AAAAIHJCszOHaI9X/yGLtjn22f0hO6VPMQDVtctkym6F + JH1W + Private-Lines: 1 + AAAAIGvvIpl8jyqn8Xufkw6v3FnEGtXF3KWw55AP3/AGEBpY + Private-MAC: 2a629acfcfbe28488a1ba9b6948c36406bc28422 + """; + + @Test + void anEd25519KeyIsWrittenExactlyAsPuttyWritesIt() { + Ec2KeyMaterial.Generated pem = Ec2KeyMaterial.ed25519(new Ed25519PrivateKeyParameters(PUTTY_TEST_KEY, 0)); + + Ec2KeyMaterial.Generated ppk = Ec2PuttyKeys.of(pem, "ed25519-key-20200105"); + + assertEquals(PUTTY_TEST_FILE, ppk.privateKeyPem()); + assertEquals(pem.openSshPublicKey(), ppk.openSshPublicKey()); + assertEquals(pem.fingerprint(), ppk.fingerprint()); + } + + @Test + void anEd25519FileHoldsTheKeyOfThePem() throws Exception { + Ec2KeyMaterial.Generated pem = Ec2KeyMaterial.generate("ed25519", "pem", "name"); + + PuttyKeyFile file = PuttyKeyFile.parse(Ec2PuttyKeys.of(pem, "name").privateKeyPem()); + + assertEquals("ssh-ed25519", file.algorithm()); + assertTrue(file.macIsValid()); + assertArrayEquals(Ec2KeyPairFixtures.openSshEd25519Key(pem.privateKeyPem()).getEncoded(), + file.ed25519Key().getEncoded()); + assertArrayEquals(SshPublicKeys.decodeBlob(pem.openSshPublicKey()), file.publicBlob()); + } + + /** + * PuTTY keeps an RSA key's larger prime first, and Java's generator puts either first, so both + * orders are checked: the file holds the PEM key with the larger prime first, and is + * fingerprinted by the SHA-1 of that key's DER, which is what PuTTYgen exports from it. + */ + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void anRsaFileHoldsTheKeyOfThePemWithTheLargerPrimeFirst(boolean largerPrimeFirstInThePem) throws Exception { + Ec2KeyMaterial.Generated pem = rsaPemWithLargerPrimeFirst(largerPrimeFirstInThePem); + RSAPrivateCrtKey generated = (RSAPrivateCrtKey) Pem.parsePrivateKey(pem.privateKeyPem()); + + Ec2KeyMaterial.Generated ppk = Ec2PuttyKeys.of(pem, "rsa-name"); + PuttyKeyFile file = PuttyKeyFile.parse(ppk.privateKeyPem()); + + assertEquals("ssh-rsa", file.algorithm()); + assertEquals("none", file.encryption()); + assertEquals("rsa-name", file.comment()); + assertTrue(file.macIsValid()); + RSAPrivateCrtKey written = file.rsaKey(); + assertEquals(generated.getModulus(), written.getModulus()); + assertEquals(generated.getPrivateExponent(), written.getPrivateExponent()); + assertEquals(generated.getPrimeP().max(generated.getPrimeQ()), written.getPrimeP()); + assertArrayEquals(SshPublicKeys.decodeBlob(pem.openSshPublicKey()), file.publicBlob()); + assertEquals(pem.openSshPublicKey(), ppk.openSshPublicKey()); + assertEquals(colonHex(Digests.sha1(written.getEncoded())), ppk.fingerprint()); + if (largerPrimeFirstInThePem) { + // The same key with the same DER, so the fingerprint CreateKeyPair gives the PEM. + assertEquals(pem.fingerprint(), ppk.fingerprint()); + } + } + + @Test + void aGeneratedRsaKeyFileHoldsA2048BitKeyFingerprintedAsWritten() throws Exception { + Ec2KeyMaterial.Generated ppk = Ec2KeyMaterial.generate("rsa", "ppk", "name"); + RSAPrivateCrtKey key = PuttyKeyFile.parse(ppk.privateKeyPem()).rsaKey(); + + assertEquals(2048, key.getModulus().bitLength()); + assertEquals(colonHex(Digests.sha1(key.getEncoded())), ppk.fingerprint()); + } + + /** + * PuTTY ends a line at a line feed or a carriage return, so a name holding either cannot be the + * comment; a tab or any other control character is left out with them. + */ + @ParameterizedTest + @ValueSource(strings = {"two\nlines", "two\rlines", "a\ttab", "a\177delete"}) + void aNameThatCannotBeOneLineOfTheFileIsLeftOut(String name) throws Exception { + Ec2KeyMaterial.Generated pem = Ec2KeyMaterial.generate("ed25519", "pem", "ignored"); + + PuttyKeyFile file = PuttyKeyFile.parse(Ec2PuttyKeys.of(pem, name).privateKeyPem()); + + assertEquals("", file.comment()); + assertTrue(file.macIsValid()); + } + + /** + * A key from generateRsa with its primes in the given order, which Java's generator picks at + * random. A generator that never puts the smaller prime first leaves that order unreachable, + * so the case is skipped rather than failed. + */ + private static Ec2KeyMaterial.Generated rsaPemWithLargerPrimeFirst(boolean largerPrimeFirst) { + for (int attempt = 0; attempt < 64; attempt++) { + Ec2KeyMaterial.Generated pem = Ec2KeyMaterial.generateRsa(); + RSAPrivateCrtKey key = (RSAPrivateCrtKey) Pem.parsePrivateKey(pem.privateKeyPem()); + if ((key.getPrimeP().compareTo(key.getPrimeQ()) > 0) == largerPrimeFirst) { + return pem; + } + } + return Assumptions.abort("64 generated keys in a row had their primes in the other order"); + } + + private static String colonHex(byte[] digest) { + return HexFormat.of().withDelimiter(":").formatHex(digest); + } +} 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 40efcf5a70..e8e9829acf 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 @@ -4762,8 +4762,9 @@ class Ec2ServiceTest { /** * A key pair stored before its type was recorded has none, so DescribeKeyPairs reads it from - * what the record holds: a created key pair is RSA, an imported one has the type of its key, - * and material ImportKeyPair would now refuse has no type. key-type filters by the same answer. + * the key the record holds, created or imported, and material ImportKeyPair would now refuse has + * no type; a created key pair saved before it kept its public key is RSA, all CreateKeyPair made + * then. key-type filters by the same answer. */ @Test void theTypeOfAKeyPairStoredWithoutOneIsReadFromItsKey() throws Exception { @@ -4795,6 +4796,18 @@ class Ec2ServiceTest { } keyPairStore.put("us-east-1::" + record.getKey(), keyPair); } + Ec2KeyMaterial.Generated ed25519 = Ec2KeyMaterial.generate("ed25519", "pem", "key-created-ed25519"); + Ec2KeyMaterial.Generated rsa = Ec2KeyMaterial.generateRsa(); + for (String id : List.of("key-created-ed25519", "key-created-without-public-key")) { + KeyPair keyPair = new KeyPair(); + keyPair.setKeyPairId(id); + keyPair.setKeyName(id); + keyPair.setRegion("us-east-1"); + boolean isEd25519 = id.equals("key-created-ed25519"); + keyPair.setKeyMaterial(isEd25519 ? ed25519.privateKeyPem() : rsa.privateKeyPem()); + keyPair.setPublicKey(isEd25519 ? ed25519.openSshPublicKey() : null); + keyPairStore.put("us-east-1::" + id, keyPair); + } Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class), mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(), @@ -4816,9 +4829,12 @@ class Ec2ServiceTest { expected.put("key-garbage", null); expected.put("key-pad-bits", null); expected.put("key-empty-bit-string", null); + expected.put("key-created-ed25519", "ed25519"); + expected.put("key-created-without-public-key", "rsa"); assertEquals(expected, types); - assertEquals(List.of("key-ed25519"), service.describeKeyPairs("us-east-1", List.of(), List.of(), - Map.of("key-type", List.of("ed25519"))).stream().map(KeyPair::getKeyPairId).toList()); + assertEquals(Set.of("key-ed25519", "key-created-ed25519"), service.describeKeyPairs("us-east-1", + List.of(), List.of(), Map.of("key-type", List.of("ed25519"))) + .stream().map(KeyPair::getKeyPairId).collect(Collectors.toSet())); } /** diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/PuttyKeyFile.java b/src/test/java/io/github/hectorvent/floci/services/ec2/PuttyKeyFile.java new file mode 100644 index 0000000000..fe1e47b034 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/PuttyKeyFile.java @@ -0,0 +1,135 @@ +package io.github.hectorvent.floci.services.ec2; + +import io.github.hectorvent.floci.core.common.Digests; +import io.github.hectorvent.floci.core.common.SshPublicKeys; +import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters; +import org.bouncycastle.crypto.util.OpenSSHPublicKeyUtil; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.KeyFactory; +import java.security.interfaces.RSAPrivateCrtKey; +import java.security.interfaces.RSAPublicKey; +import java.security.spec.RSAPrivateCrtKeySpec; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * A PuTTY private key file, version 2, read the way PuTTY reads one, for the key pair tests: written + * apart from Ec2PuttyKeys, so a test checks the format rather than the writer's own idea of it. The + * layout and the MAC follow PuTTY's sshpubk.c: a version line, an encryption line and a comment, the + * public blob and the private fields as counted lines of base64, and an HMAC-SHA1, keyed with the + * SHA-1 of "putty-private-key-file-mac-key" when unencrypted, over the algorithm, the encryption, the + * comment and both blobs, each as an SSH string. Its fields and the RSA public key are read with + * SshPublicKeys, which SshPublicKeysTest checks on its own. + */ +record PuttyKeyFile(String algorithm, String encryption, String comment, byte[] publicBlob, byte[] privateBlob, + String mac) { + + static PuttyKeyFile parse(String text) { + assertTrue(text.startsWith("PuTTY-User-Key-File-2: "), + "not a PuTTY version 2 key file: " + text.lines().findFirst().orElse("")); + assertTrue(text.endsWith("\n"), "a PuTTY key file ends its last line"); + List lines = text.lines().toList(); + Map headers = new LinkedHashMap<>(); + Map blobs = new LinkedHashMap<>(); + for (int i = 0; i < lines.size(); i++) { + String line = lines.get(i); + int colon = line.indexOf(": "); + assertTrue(colon > 0, "line " + (i + 1) + " is not a header line"); + String name = line.substring(0, colon); + headers.put(name, line.substring(colon + 2)); + if (name.endsWith("-Lines")) { + List body = lines.subList(i + 1, i + 1 + Integer.parseInt(headers.get(name))); + body.subList(0, body.size() - 1).forEach(row -> + assertEquals(64, row.length(), "PuTTY writes 64 base64 characters to a line")); + blobs.put(name, Base64.getDecoder().decode(String.join("", body))); + i += body.size(); + } + } + assertEquals(List.of("PuTTY-User-Key-File-2", "Encryption", "Comment", "Public-Lines", "Private-Lines", + "Private-MAC"), new ArrayList<>(headers.keySet())); + return new PuttyKeyFile(headers.get("PuTTY-User-Key-File-2"), headers.get("Encryption"), + headers.get("Comment"), blobs.get("Public-Lines"), blobs.get("Private-Lines"), + headers.get("Private-MAC")); + } + + boolean macIsValid() throws GeneralSecurityException { + Mac hmac = Mac.getInstance("HmacSHA1"); + hmac.init(new SecretKeySpec(Digests.sha1(utf8("putty-private-key-file-mac-key")), "HmacSHA1")); + byte[] expected = hmac.doFinal(strings(utf8(algorithm), utf8(encryption), utf8(comment), publicBlob, privateBlob)); + return HexFormat.of().formatHex(expected).equals(mac); + } + + /** + * The RSA key the file holds, rebuilt from its public exponent and modulus and its private exponent, + * primes and coefficient, after checking they make one key, with the larger prime first. + */ + RSAPrivateCrtKey rsaKey() throws GeneralSecurityException { + assertEquals("ssh-rsa", algorithm); + RSAPublicKey publicKey = SshPublicKeys.rsaKeyOf(publicBlob); + List fields = privateFields(4).stream().map(BigInteger::new).toList(); + BigInteger e = publicKey.getPublicExponent(); + BigInteger n = publicKey.getModulus(); + BigInteger d = fields.get(0); + BigInteger p = fields.get(1); + BigInteger q = fields.get(2); + BigInteger iqmp = fields.get(3); + assertEquals(n, p.multiply(q)); + assertTrue(p.compareTo(q) > 0, "PuTTY keeps the larger prime first"); + assertEquals(BigInteger.ONE, iqmp.multiply(q).mod(p), "the coefficient is the inverse of q modulo p"); + assertEquals(BigInteger.ONE, e.multiply(d).mod(p.subtract(BigInteger.ONE))); + assertEquals(BigInteger.ONE, e.multiply(d).mod(q.subtract(BigInteger.ONE))); + return (RSAPrivateCrtKey) KeyFactory.getInstance("RSA").generatePrivate(new RSAPrivateCrtKeySpec(n, e, d, p, q, + d.mod(p.subtract(BigInteger.ONE)), d.mod(q.subtract(BigInteger.ONE)), iqmp)); + } + + /** The ED25519 key the file holds, after checking its public blob is that key's public half. */ + Ed25519PrivateKeyParameters ed25519Key() throws IOException { + assertEquals("ssh-ed25519", algorithm); + Ed25519PrivateKeyParameters key = new Ed25519PrivateKeyParameters(privateFields(1).getFirst(), 0); + assertTrue(Arrays.equals(publicBlob, OpenSSHPublicKeyUtil.encodePublicKey(key.generatePublicKey())), + "the public blob is the public half of the private key"); + return key; + } + + /** The private blob's fields, which have to be exactly {@code count} with nothing after them. */ + private List privateFields(int count) { + SshPublicKeys.Reader reader = SshPublicKeys.reader(privateBlob); + List fields = new ArrayList<>(); + int length = 0; + for (int i = 0; i < count; i++) { + fields.add(reader.readField()); + length += Integer.BYTES + fields.getLast().length; + } + assertEquals(privateBlob.length, length, "nothing follows the private fields of an unencrypted file"); + return fields; + } + + private static byte[] strings(byte[]... fields) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + for (byte[] field : fields) { + out.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(field.length).array()); + out.writeBytes(field); + } + return out.toByteArray(); + } + + private static byte[] utf8(String text) { + return text.getBytes(StandardCharsets.UTF_8); + } +}