mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(ec2): create the key type and format CreateKeyPair asks for (#6112)
* fix(ec2): create the key type and format CreateKeyPair asks for CreateKeyPair ignored KeyType and KeyFormat, so asking for an ED25519 key or a PuTTY key file returned a 2048-bit RSA key as PEM, and any value of either was accepted. Now, as AWS answers: - KeyType=ed25519 creates an ED25519 key, returned in OpenSSH's own BEGIN OPENSSH PRIVATE KEY format and fingerprinted by the padded base64 SHA-256 of its public key blob. - KeyFormat=ppk returns the key as an unencrypted PuTTY version 2 key file whose comment is the key pair's name. An RSA key keeps the SHA-1 fingerprint of its DER private key, taken over the key with its larger prime first, the order PuTTY stores. - Any other KeyType or KeyFormat is InvalidParameterValue with AWS's validation message, checked before the name is found taken, and nothing is created. RunInstances injects the ED25519 public key of such a key pair, and DescribeKeyPairs reports it. Follow-up to the review of #6093. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * test(ec2): keep the CreateKeyPair test helpers in one place The launch test and the key unit tests use the Query helpers and the ED25519 readers of Ec2CreateKeyPairIntegrationTest instead of their own, PuttyKeyFile reads fields and RSA public keys with SshPublicKeys, the digests come from Digests, and the RSA prime-order test takes its keys from Ec2KeyMaterial.generateRsa instead of building them itself. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): answer a CreateKeyPair DryRun before its other checks AWS answers CreateKeyPair with DryRun=true by DryRunOperation (412) before it looks at the name or the key type, so a DryRun with an unknown KeyType is DryRunOperation rather than InvalidParameterValue. Floci ignored DryRun and created the key pair; it now answers it first and creates nothing. The CreateKeyPair tests share their requests and key readers through Ec2CreateKeyPairFixtures rather than an integration test class, the launch test shares the container-backed application of Ec2CapturedImageReclaimIntegrationTest, a described public key is compared without the line break AWS ends it with, a created ED25519 key imports with the same fingerprint, the PuTTY comment rule is checked for CR, tab and DEL as well as LF, and the case of a key with its smaller prime first is skipped rather than failed under a generator that never makes one. The orders AWS documents nowhere are described as Floci's. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * test(ec2): clean up after the CreateKeyPair tests The launch test terminates its instance and deletes its key pair, since it now shares an application with another class, and the import test deletes what it made even when a step before its assertion fails. A test comment and the DryRun comment no longer claim an order AWS does not document. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * test(ec2): say what the launch test's cleanup leaves behind With the container manager mocked, TerminateInstances releases the instance's address and volume but leaves its record pending, so the comment says so instead of claiming the instance goes. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): record the key type CreateKeyPair created With #6093 merged, CreateKeyPair stored every key pair's type as rsa, so an ED25519 key pair was described as rsa and the key-type filter found it under rsa. It now stores the type it created. The guard test now requires the reported type and checks the key-type filter. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * test(ec2): share Ec2KeyPairFixtures and keep the type check to what AWS does The CreateKeyPair tests now use the key pair fixture #6093 added, which gains the type-and-format CreateKeyPair and the ED25519 key readers, and their own fixture class goes. The described-type check no longer looks the key pair up with the key-type filter, which AWS answers with InvalidParameterValue. The createKeyPair Javadoc says the name is checked as present and valid before the values. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): read a stored key pair's type from its public key A key pair saved before its type was recorded was described as rsa whenever it held key material, which would misreport a created ED25519 key pair. Its type is now read from its stored public key, created or imported; a created key pair saved before Floci kept its public key is still rsa, the only type CreateKeyPair made then. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * refactor(ec2): generate ED25519 key pairs in Ec2KeyMaterial Ec2KeyMaterial already reads imported ED25519 keys, so the created ones move there too and share its base64 and fingerprint rule instead of a class of their own. Ec2PuttyKeys uses its colon-hex fingerprint, and the PuTTY test key moves into Ec2KeyPairFixtures with the other test keys. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * test(ec2): check the described key type through the SDK The SDK test now checks DescribeKeyPairs returns the type each key pair was created with, which the hardcoded rsa would have failed. The key pair fixture exports the region it signs for, and the legacy keyType paragraph in the EC2 docs is re-wrapped. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> --------- Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
This commit is contained in:
1 parent
ac7371fb33
commit
ff813c6f34
13 files changed
+1171
-29
No files matched your search
+246
@@ -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.
|
||||
*
|
||||
* <p>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();
|
||||
}
|
||||
}
|
||||
+83
@@ -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.
|
||||
*
|
||||
* <p>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<String> 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"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<String> 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"));
|
||||
}
|
||||
}
|
||||
@@ -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("");
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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()));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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<String> lines = text.lines().toList();
|
||||
Map<String, String> headers = new LinkedHashMap<>();
|
||||
Map<String, byte[]> 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<String> 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<BigInteger> 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<byte[]> privateFields(int count) {
|
||||
SshPublicKeys.Reader reader = SshPublicKeys.reader(privateBlob);
|
||||
List<byte[]> 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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user