mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
fix(ec2): honor IncludePublicKey when describing key pairs (#6055)
* fix(ec2): honor IncludePublicKey when describing key pairs DescribeKeyPairs ignored IncludePublicKey. With IncludePublicKey=true each key pair now carries its OpenSSH public key, with the key-pair name as the comment in place of any comment an imported key had; omitted or false leaves it out. Imported material that is not a whole OpenSSH key, such as PEM or RFC 4716 text, a blob missing a field its type needs, a line that names another type than its blob, or a key type other than RSA, ED25519, ECDSA and their security-key forms, is kept as given and described without a public key. SshPublicKeys.carriesAKey checks the fields each type needs. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): describe a key pair's key only when it is exactly one key DescribeKeyPairs with IncludePublicKey=true still described a blob with bytes after its key, which OpenSSH and Go's ssh package refuse, and the first of several key lines, although an instance launched with the key pair trusts every line. Both are now described without a public key. A key pair stored before KeyName was required gets no comment instead of "null". carriesAKey reads the RSA fields once through the reader. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): leave a key-pair name that cannot be a comment off the key ImportKeyPair accepts a key-pair name with a line break, and as the comment of the described key such a name split it into lines that authorized_keys reads as further keys. A name holding a control character is now left off. carriesAKey names each ECDSA curve's coordinate size and reads a security key's application field directly, and its docs say it checks the format only. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * docs(ec2): name the key types and formats a described key pair needs The Key Pairs section now names DER beside PEM and RFC 4716, and the two security-key types OpenSSH has, instead of a security-key form for every type. The SshPublicKeys class comment covers the whole-key check, and a test comment no longer says a tab would split the described key. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * docs(ec2): list the described key types by their wire names The Key Pairs section lists the key types a key pair is described with by their OpenSSH names, which reads one way only, and the SshPublicKeys comments name the two security-key types instead of implying a security-key form for every key type. 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
cbdeb0c8dc
commit
9f9c16a181
7 files changed
+506
-4
No files matched your search
+55
@@ -0,0 +1,55 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.core.SdkBytes;
|
||||
import software.amazon.awssdk.services.ec2.Ec2Client;
|
||||
import software.amazon.awssdk.services.ec2.model.KeyPairInfo;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@DisplayName("EC2 DescribeKeyPairs IncludePublicKey")
|
||||
class Ec2KeyPairPublicKeyTest {
|
||||
|
||||
/** A throwaway ed25519 public key, imported under a comment that the description replaces. */
|
||||
private static final String ED25519_KEY =
|
||||
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIIj7azlDjVHAsSxgcpCRZ3oWnTm0nAFM64y9jd22ioI/";
|
||||
|
||||
@Test
|
||||
@DisplayName("DescribeKeyPairs returns the public key only when IncludePublicKey is true")
|
||||
void describeKeyPairsReturnsThePublicKeyOnlyWhenAsked() {
|
||||
try (Ec2Client ec2 = TestFixtures.ec2Client()) {
|
||||
String name = TestFixtures.uniqueName("public-key");
|
||||
String keyPairId = ec2.createKeyPair(r -> r.keyName(name)).keyPairId();
|
||||
try {
|
||||
KeyPairInfo without = ec2.describeKeyPairs(r -> r.keyPairIds(keyPairId)).keyPairs().get(0);
|
||||
KeyPairInfo with = ec2.describeKeyPairs(r -> r.keyPairIds(keyPairId).includePublicKey(true))
|
||||
.keyPairs().get(0);
|
||||
|
||||
assertThat(without.publicKey()).isNull();
|
||||
assertThat(with.publicKey()).startsWith("ssh-rsa ").endsWith(" " + name);
|
||||
} finally {
|
||||
ec2.deleteKeyPair(r -> r.keyPairId(keyPairId));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("An imported key is described with the key-pair name as its comment")
|
||||
void anImportedKeyIsDescribedWithTheKeyPairNameAsItsComment() {
|
||||
try (Ec2Client ec2 = TestFixtures.ec2Client()) {
|
||||
String name = TestFixtures.uniqueName("public-key");
|
||||
String keyPairId = ec2.importKeyPair(r -> r.keyName(name)
|
||||
.publicKeyMaterial(SdkBytes.fromUtf8String(ED25519_KEY + " someone@example.com")))
|
||||
.keyPairId();
|
||||
try {
|
||||
KeyPairInfo with = ec2.describeKeyPairs(r -> r.keyNames(name).includePublicKey(true))
|
||||
.keyPairs().get(0);
|
||||
|
||||
assertThat(with.publicKey()).isEqualTo(ED25519_KEY + " " + name);
|
||||
} finally {
|
||||
ec2.deleteKeyPair(r -> r.keyPairId(keyPairId));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -312,6 +312,17 @@ private gateway lifecycles are not modelled.
|
||||
|
||||
### Key Pairs
|
||||
|
||||
`DescribeKeyPairs` omits the public key unless `IncludePublicKey=true`. When requested,
|
||||
it returns the OpenSSH public key with the key-pair name as its comment, including for
|
||||
imported keys, whatever comment they were imported with; a name holding a control character,
|
||||
such as a line break, is left off. It never returns private key material. `ImportKeyPair`
|
||||
stores the material as it was given, and a key pair whose material 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`, `ecdsa-sha2-nistp256`, `ecdsa-sha2-nistp384`,
|
||||
`ecdsa-sha2-nistp521`, `sk-ssh-ed25519@openssh.com` and `sk-ecdsa-sha2-nistp256@openssh.com`.
|
||||
|
||||
| Action | Description |
|
||||
|--------|-------------|
|
||||
| CreateKeyPair | Creates and stores a local key pair. |
|
||||
|
||||
@@ -14,7 +14,8 @@ import java.util.HexFormat;
|
||||
|
||||
/**
|
||||
* The OpenSSH public key wire form, {@code "ssh-rsa AAAA..."}: decoding a line into its
|
||||
* length-prefixed fields, and reading or writing the RSA key they carry.
|
||||
* length-prefixed fields, reading or writing the RSA key they carry, and telling whether a blob
|
||||
* holds a whole RSA, ed25519, ECDSA or security-key public key of the type it declares.
|
||||
*
|
||||
* <p>Extracted from {@code Ec2KeyMaterial} rather than left there because it is key-format
|
||||
* handling rather than anything EC2 owns. The digest helper is here for the same reason, and
|
||||
@@ -32,6 +33,9 @@ public final class SshPublicKeys {
|
||||
|
||||
private static final int PEM_LINE_LENGTH = 64;
|
||||
|
||||
/** The length of an ed25519 public key, the one field after its type. */
|
||||
private static final int ED25519_KEY_LENGTH = 32;
|
||||
|
||||
private SshPublicKeys() {}
|
||||
|
||||
/**
|
||||
@@ -101,6 +105,11 @@ public final class SshPublicKeys {
|
||||
buffer.get(field);
|
||||
return field;
|
||||
}
|
||||
|
||||
/** Whether every byte of the blob has been read. */
|
||||
private boolean atEnd() {
|
||||
return !buffer.hasRemaining();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -117,6 +126,11 @@ public final class SshPublicKeys {
|
||||
if (!"ssh-rsa".equals(type)) {
|
||||
throw new SshPublicKeyException("not an ssh-rsa blob: " + type);
|
||||
}
|
||||
return rsaKeyFrom(reader);
|
||||
}
|
||||
|
||||
/** The RSA public key whose exponent and then modulus are the reader's next two fields. */
|
||||
private static RSAPublicKey rsaKeyFrom(Reader reader) {
|
||||
BigInteger exponent = new BigInteger(reader.readField());
|
||||
BigInteger modulus = new BigInteger(reader.readField());
|
||||
try {
|
||||
@@ -144,6 +158,64 @@ public final class SshPublicKeys {
|
||||
return blob.array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a blob carries a whole public key of the type it declares: an {@code ssh-rsa}
|
||||
* exponent and modulus that make a usable key, a 32-byte ed25519 key, or an uncompressed point
|
||||
* of the size of the curve an ECDSA type names, followed by an application field for the two
|
||||
* security-key types, {@code sk-ssh-ed25519@openssh.com} and
|
||||
* {@code sk-ecdsa-sha2-nistp256@openssh.com}. A type field alone, or a field of the wrong size,
|
||||
* is not a key, and neither is a type other than these, such as {@code ssh-dss} or a
|
||||
* certificate. Unlike {@link #rsaKeyOf}, which reads only the fields it needs, nothing may
|
||||
* follow the key, as OpenSSH requires. The check is of the format alone: it does not ask
|
||||
* whether an RSA modulus is long enough for OpenSSH or whether an EC point lies on its curve.
|
||||
*/
|
||||
public static boolean carriesAKey(byte[] blob) {
|
||||
if (blob == null) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
Reader reader = reader(blob);
|
||||
String type = new String(reader.readField(), StandardCharsets.UTF_8);
|
||||
boolean keyFields = switch (type) {
|
||||
case "ssh-rsa" -> {
|
||||
rsaKeyFrom(reader); // throws when the exponent and modulus make no usable key
|
||||
yield true;
|
||||
}
|
||||
case "ssh-ed25519" -> reader.readField().length == ED25519_KEY_LENGTH;
|
||||
case "sk-ssh-ed25519@openssh.com" -> {
|
||||
boolean key = reader.readField().length == ED25519_KEY_LENGTH;
|
||||
reader.readField(); // the application, which only has to be there
|
||||
yield key;
|
||||
}
|
||||
case "ecdsa-sha2-nistp256" -> carriesAPointOn(reader, "nistp256", 32);
|
||||
case "ecdsa-sha2-nistp384" -> carriesAPointOn(reader, "nistp384", 48);
|
||||
case "ecdsa-sha2-nistp521" -> carriesAPointOn(reader, "nistp521", 66);
|
||||
case "sk-ecdsa-sha2-nistp256@openssh.com" -> {
|
||||
boolean point = carriesAPointOn(reader, "nistp256", 32);
|
||||
reader.readField(); // the application, which only has to be there
|
||||
yield point;
|
||||
}
|
||||
default -> false;
|
||||
};
|
||||
return keyFields && reader.atEnd();
|
||||
} catch (SshPublicKeyException | NumberFormatException ignored) {
|
||||
// A missing or empty field, such as an ssh-rsa type with no exponent: not a key.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the next fields name the curve and hold an uncompressed point of its size:
|
||||
* {@code 0x04} and then both coordinates, each {@code coordinateLength} bytes long.
|
||||
*/
|
||||
private static boolean carriesAPointOn(Reader reader, String curve, int coordinateLength) {
|
||||
if (!curve.equals(new String(reader.readField(), StandardCharsets.UTF_8))) {
|
||||
return false;
|
||||
}
|
||||
byte[] point = reader.readField();
|
||||
return point.length == 1 + 2 * coordinateLength && point[0] == 4;
|
||||
}
|
||||
|
||||
/** The key type an OpenSSH blob declares, such as {@code ssh-rsa}. */
|
||||
public static String keyType(byte[] blob) {
|
||||
return new String(reader(blob).readField(), StandardCharsets.UTF_8);
|
||||
|
||||
@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.core.common.AwsPartition;
|
||||
import io.github.hectorvent.floci.core.common.AwsPartitions;
|
||||
import io.github.hectorvent.floci.core.common.AwsRegionFacts;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.SshPublicKeys;
|
||||
import io.github.hectorvent.floci.core.common.XmlBuilder;
|
||||
import io.github.hectorvent.floci.services.ec2.model.*;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
@@ -3396,6 +3397,7 @@ public class Ec2QueryHandler {
|
||||
}
|
||||
|
||||
private Response handleDescribeKeyPairs(MultivaluedMap<String, String> p, String region) {
|
||||
boolean includePublicKey = Boolean.parseBoolean(p.getFirst("IncludePublicKey"));
|
||||
List<String> keyNames = getList(p, "KeyName");
|
||||
List<String> keyPairIds = getList(p, "KeyPairId");
|
||||
List<KeyPair> kps = service.describeKeyPairs(region, keyNames, keyPairIds);
|
||||
@@ -3407,14 +3409,46 @@ public class Ec2QueryHandler {
|
||||
xml.start("item")
|
||||
.elem("keyPairId", kp.getKeyPairId())
|
||||
.elem("keyName", kp.getKeyName())
|
||||
.elem("keyFingerprint", kp.getKeyFingerprint())
|
||||
.raw(tagSetXml(kp.getTags()))
|
||||
.end("item");
|
||||
.elem("keyFingerprint", kp.getKeyFingerprint());
|
||||
if (includePublicKey) {
|
||||
xml.elem("publicKey", openSshPublicKeyNamedFor(kp));
|
||||
}
|
||||
xml.raw(tagSetXml(kp.getTags())).end("item");
|
||||
}
|
||||
xml.end("keySet").end("DescribeKeyPairsResponse");
|
||||
return xmlResponse(xml.build());
|
||||
}
|
||||
|
||||
/**
|
||||
* The stored public key as an OpenSSH line whose comment is the key-pair name, the form
|
||||
* DescribeKeyPairs reports for created and imported keys alike. ImportKeyPair keeps what it was
|
||||
* given, so this is null unless the material is a single OpenSSH line whose blob is a whole key
|
||||
* of the type the line names: a partial blob, a line labelled with another type and material of
|
||||
* more than one line are not one key to report. PEM, DER and RFC 4716 bodies are not converted,
|
||||
* since ImportKeyPair does not read those formats yet. The line is rebuilt from the blob's type,
|
||||
* the blob and the name rather than copied, so no character of the stored text, such as a NUL
|
||||
* that XML cannot carry, reaches the response.
|
||||
*/
|
||||
private static String openSshPublicKeyNamedFor(KeyPair kp) {
|
||||
String material = kp.getPublicKey();
|
||||
byte[] blob = SshPublicKeys.decodeBlob(material);
|
||||
if (!SshPublicKeys.carriesAKey(blob)) {
|
||||
return null;
|
||||
}
|
||||
String line = material.trim();
|
||||
// decodeBlob took the blob from the second field; the first has to name the same type. More
|
||||
// than one line is not taken apart: authorized_keys reads each line as a key of its own.
|
||||
String type = SshPublicKeys.keyType(blob);
|
||||
if (line.indexOf('\n') >= 0 || !type.equals(line.split("\\s+", 2)[0])) {
|
||||
return null;
|
||||
}
|
||||
// A key pair stored before KeyName was required has no name, and a name holding a control
|
||||
// character, such as a line break that would split this line in two, is no comment either.
|
||||
String name = kp.getKeyName();
|
||||
boolean nameIsAComment = name != null && !name.isBlank() && name.chars().noneMatch(Character::isISOControl);
|
||||
return type + " " + Base64.getEncoder().encodeToString(blob) + (nameIsAComment ? " " + name : "");
|
||||
}
|
||||
|
||||
private Response handleDeleteKeyPair(MultivaluedMap<String, String> p, String region) {
|
||||
String keyName = p.getFirst("KeyName");
|
||||
String keyPairId = p.getFirst("KeyPairId");
|
||||
|
||||
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.core.common;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.interfaces.RSAPublicKey;
|
||||
@@ -188,4 +189,88 @@ class SshPublicKeysTest {
|
||||
assertEquals("ssh-rsa", SshPublicKeys.keyType(
|
||||
SshPublicKeys.decodeBlob(SshPublicKeys.toOpenSsh(KEY))));
|
||||
}
|
||||
|
||||
/**
|
||||
* A blob carries a key only when it has every field its type requires: a type field alone, an
|
||||
* RSA exponent and modulus that make no usable key, or an ed25519 key or ECDSA point of the
|
||||
* wrong size or form, is not a public key, and neither is a type outside RSA, ed25519, the three
|
||||
* ECDSA curves and the two security-key types.
|
||||
*/
|
||||
@Test
|
||||
void aBlobCarriesAKeyOnlyWithEveryFieldItsTypeRequires() {
|
||||
byte[] exponent = {1, 0, 1};
|
||||
assertTrue(SshPublicKeys.carriesAKey(SshPublicKeys.openSshBlob(KEY)));
|
||||
assertFalse(SshPublicKeys.carriesAKey(blob("ssh-rsa")));
|
||||
assertFalse(SshPublicKeys.carriesAKey(blob("ssh-rsa", exponent)));
|
||||
assertFalse(SshPublicKeys.carriesAKey(blob("ssh-rsa", new byte[0], new byte[] {1})));
|
||||
assertFalse(SshPublicKeys.carriesAKey(blob("ssh-rsa", exponent, new byte[] {1})));
|
||||
assertFalse(SshPublicKeys.carriesAKey(
|
||||
blob("ssh-dss", new byte[] {1}, new byte[] {1}, new byte[] {1}, new byte[] {1})));
|
||||
|
||||
assertTrue(SshPublicKeys.carriesAKey(blob("ssh-ed25519", new byte[32])));
|
||||
assertFalse(SshPublicKeys.carriesAKey(blob("ssh-ed25519", new byte[31])));
|
||||
assertFalse(SshPublicKeys.carriesAKey(blob("ssh-ed25519")));
|
||||
assertTrue(SshPublicKeys.carriesAKey(blob("sk-ssh-ed25519@openssh.com", new byte[32], ascii("ssh:"))));
|
||||
assertFalse(SshPublicKeys.carriesAKey(blob("sk-ssh-ed25519@openssh.com", new byte[32])));
|
||||
|
||||
assertTrue(SshPublicKeys.carriesAKey(blob("ecdsa-sha2-nistp256", ascii("nistp256"), point(32))));
|
||||
assertTrue(SshPublicKeys.carriesAKey(blob("ecdsa-sha2-nistp384", ascii("nistp384"), point(48))));
|
||||
assertTrue(SshPublicKeys.carriesAKey(blob("ecdsa-sha2-nistp521", ascii("nistp521"), point(66))));
|
||||
assertFalse(SshPublicKeys.carriesAKey(blob("ecdsa-sha2-nistp256", ascii("nistp384"), point(32))));
|
||||
assertFalse(SshPublicKeys.carriesAKey(blob("ecdsa-sha2-nistp384", ascii("nistp384"), point(32))));
|
||||
assertFalse(SshPublicKeys.carriesAKey(blob("ecdsa-sha2-nistp256", ascii("nistp256"), new byte[64])));
|
||||
assertFalse(SshPublicKeys.carriesAKey(blob("ecdsa-sha2-nistp256", ascii("nistp256"), new byte[65])));
|
||||
assertTrue(SshPublicKeys.carriesAKey(
|
||||
blob("sk-ecdsa-sha2-nistp256@openssh.com", ascii("nistp256"), point(32), ascii("ssh:"))));
|
||||
assertFalse(SshPublicKeys.carriesAKey(
|
||||
blob("sk-ecdsa-sha2-nistp256@openssh.com", ascii("nistp256"), point(32))));
|
||||
|
||||
assertFalse(SshPublicKeys.carriesAKey(blob("ssh-unknown", new byte[32])));
|
||||
assertFalse(SshPublicKeys.carriesAKey(null));
|
||||
}
|
||||
|
||||
/**
|
||||
* Unlike rsaKeyOf, which reads only the fields it needs, a blob carries a key only when nothing
|
||||
* follows the fields of its type: OpenSSH refuses a blob with trailing data, whether that is a
|
||||
* whole extra field or a few stray bytes.
|
||||
*/
|
||||
@Test
|
||||
void aBlobWithAnythingAfterItsKeyCarriesNoKey() {
|
||||
assertFalse(SshPublicKeys.carriesAKey(blobWithTrailingJunk()));
|
||||
assertFalse(SshPublicKeys.carriesAKey(withTrailing(SshPublicKeys.openSshBlob(KEY), new byte[4])));
|
||||
assertFalse(SshPublicKeys.carriesAKey(blob("ssh-ed25519", new byte[32], ascii("extra"))));
|
||||
assertFalse(SshPublicKeys.carriesAKey(withTrailing(blob("ssh-ed25519", new byte[32]), new byte[] {1, 2, 3})));
|
||||
assertFalse(SshPublicKeys.carriesAKey(blob("ecdsa-sha2-nistp256", ascii("nistp256"), point(32), new byte[0])));
|
||||
assertFalse(SshPublicKeys.carriesAKey(
|
||||
blob("sk-ssh-ed25519@openssh.com", new byte[32], ascii("ssh:"), ascii("extra"))));
|
||||
}
|
||||
|
||||
private static byte[] withTrailing(byte[] blob, byte[] trailing) {
|
||||
return ByteBuffer.allocate(blob.length + trailing.length).put(blob).put(trailing).array();
|
||||
}
|
||||
|
||||
/** An uncompressed EC point, {@code 0x04} and then both coordinates of the given size. */
|
||||
private static byte[] point(int coordinateLength) {
|
||||
byte[] point = new byte[1 + 2 * coordinateLength];
|
||||
point[0] = 4;
|
||||
return point;
|
||||
}
|
||||
|
||||
private static byte[] ascii(String value) {
|
||||
return value.getBytes(StandardCharsets.US_ASCII);
|
||||
}
|
||||
|
||||
/** An OpenSSH blob of the given type followed by the given fields, each length-prefixed. */
|
||||
private static byte[] blob(String type, byte[]... fields) {
|
||||
byte[] typeBytes = type.getBytes(StandardCharsets.US_ASCII);
|
||||
int length = Integer.BYTES + typeBytes.length;
|
||||
for (byte[] field : fields) {
|
||||
length += Integer.BYTES + field.length;
|
||||
}
|
||||
ByteBuffer buffer = ByteBuffer.allocate(length).putInt(typeBytes.length).put(typeBytes);
|
||||
for (byte[] field : fields) {
|
||||
buffer.putInt(field.length).put(field);
|
||||
}
|
||||
return buffer.array();
|
||||
}
|
||||
}
|
||||
+215
@@ -0,0 +1,215 @@
|
||||
package io.github.hectorvent.floci.services.ec2;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.SshPublicKeys;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.path.xml.XmlPath;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
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.ValueSource;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringReader;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.interfaces.RSAPublicKey;
|
||||
import java.util.Base64;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.startsWith;
|
||||
|
||||
@QuarkusTest
|
||||
class Ec2KeyPairPublicKeyIntegrationTest {
|
||||
private static final String AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20261009/us-east-1/ec2/aws4_request";
|
||||
|
||||
/** The blob of a throwaway ed25519 public key. */
|
||||
private static final String ED25519_BLOB = "AAAAC3NzaC1lZDI1NTE5AAAAIIj7azlDjVHAsSxgcpCRZ3oWnTm0nAFM64y9jd22ioI/";
|
||||
|
||||
/**
|
||||
* The described key is the public half of the key the caller holds, with the key-pair name as
|
||||
* its comment in place of any the import carried: the line that was imported, or the half of
|
||||
* the private key CreateKeyPair returned. It is there only when IncludePublicKey is true.
|
||||
*/
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void publicKeyIsReturnedOnlyWhenRequested(boolean imported) throws IOException {
|
||||
String name = "public-key-" + UUID.randomUUID();
|
||||
String importedKey = imported ? Ec2KeyMaterial.generateRsa().openSshPublicKey() : null;
|
||||
RequestSpecification create = given().header("Authorization", AUTH)
|
||||
.formParam("Action", imported ? "ImportKeyPair" : "CreateKeyPair")
|
||||
.formParam("KeyName", name);
|
||||
if (imported) {
|
||||
create.formParam("PublicKeyMaterial", Base64.getEncoder().encodeToString(
|
||||
utf8(importedKey + " supplied-comment")));
|
||||
}
|
||||
String responseName = imported ? "ImportKeyPairResponse" : "CreateKeyPairResponse";
|
||||
XmlPath created = create.post("/").then().statusCode(200).extract().xmlPath();
|
||||
String id = created.getString(responseName + ".keyPairId");
|
||||
try {
|
||||
String expected = (imported ? importedKey : publicHalfOf(created.getString(responseName + ".keyMaterial")))
|
||||
+ " " + name;
|
||||
for (String selection : new String[]{"KeyName.1", "KeyPairId.1"}) {
|
||||
String value = selection.startsWith("KeyName") ? name : id;
|
||||
for (String include : new String[]{null, "false", "true"}) {
|
||||
RequestSpecification describe = given().header("Authorization", AUTH)
|
||||
.formParam("Action", "DescribeKeyPairs").formParam(selection, value);
|
||||
if (include != null) {
|
||||
describe.formParam("IncludePublicKey", include);
|
||||
}
|
||||
ValidatableResponse response = describe.post("/").then().statusCode(200)
|
||||
.body("DescribeKeyPairsResponse.keySet.item.size()", equalTo(1))
|
||||
.body("DescribeKeyPairsResponse.keySet.item.keyName", equalTo(name))
|
||||
.body("DescribeKeyPairsResponse.keySet.item.keyPairId", equalTo(id))
|
||||
.body("DescribeKeyPairsResponse.keySet.item.keyMaterial.size()", equalTo(0))
|
||||
.body("DescribeKeyPairsResponse.keySet.item.publicKey.size()",
|
||||
equalTo("true".equals(include) ? 1 : 0));
|
||||
if ("true".equals(include)) {
|
||||
response.body("DescribeKeyPairsResponse.keySet.item.publicKey", equalTo(expected));
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
deleteKeyPair(id);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An OpenSSH line is recognised without a comment and whatever whitespace separates or ends its
|
||||
* fields, and comes back in the canonical single-space form with the key-pair name added.
|
||||
*/
|
||||
@Test
|
||||
void anOpenSshLineWithoutACommentIsDescribedWithTheKeyPairName() {
|
||||
String name = "public-key-" + UUID.randomUUID();
|
||||
describeImported(name, utf8("ssh-ed25519\t" + ED25519_BLOB + "\r\n"), response -> response
|
||||
.body("DescribeKeyPairsResponse.keySet.item.publicKey",
|
||||
equalTo("ssh-ed25519 " + ED25519_BLOB + " " + name)));
|
||||
}
|
||||
|
||||
/**
|
||||
* ImportKeyPair takes a name with a line break, and as a comment that name would turn the one
|
||||
* key into lines an authorized_keys file reads as further keys, so the key is described bare.
|
||||
*/
|
||||
@Test
|
||||
void aNameWithALineBreakIsNotUsedAsTheComment() {
|
||||
String name = "public-key-" + UUID.randomUUID() + "\nssh-ed25519 " + ED25519_BLOB + " another";
|
||||
describeImported(name, utf8("ssh-ed25519 " + ED25519_BLOB), response -> response
|
||||
.body("DescribeKeyPairsResponse.keySet.item.publicKey", equalTo("ssh-ed25519 " + ED25519_BLOB)));
|
||||
}
|
||||
|
||||
/**
|
||||
* ImportKeyPair keeps material it cannot read as it was given, so the key pair is described
|
||||
* without a public key rather than with a rewrite of text that is not an OpenSSH line. A UTF-16
|
||||
* file decodes to text with NUL characters, which XML cannot carry at all.
|
||||
*/
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"rfc4716", "utf16"})
|
||||
void materialThatIsNotAnOpenSshLineIsDescribedWithoutAPublicKey(String format) {
|
||||
String name = "public-key-" + UUID.randomUUID();
|
||||
String openSsh = Ec2KeyMaterial.generateRsa().openSshPublicKey();
|
||||
byte[] material = "rfc4716".equals(format)
|
||||
? utf8("---- BEGIN SSH2 PUBLIC KEY ----\nComment: \"" + name + "\"\n" + openSsh.split(" ")[1]
|
||||
+ "\n---- END SSH2 PUBLIC KEY ----\n")
|
||||
: (openSsh + " " + name).getBytes(StandardCharsets.UTF_16LE);
|
||||
describeImported(name, material, response -> response
|
||||
.body("DescribeKeyPairsResponse.keySet.item.keyName", equalTo(name))
|
||||
.body("DescribeKeyPairsResponse.keySet.item.keyFingerprint", startsWith("00:00"))
|
||||
.body("DescribeKeyPairsResponse.keySet.item.publicKey.size()", equalTo(0)));
|
||||
}
|
||||
|
||||
/**
|
||||
* A blob that declares a key type but lacks a field that type requires, here an ssh-rsa type
|
||||
* with no exponent or modulus and an ed25519 key one byte short, is not a public key.
|
||||
*/
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"AAAAB3NzaC1yc2E=", "AAAAC3NzaC1lZDI1NTE5AAAAHwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="})
|
||||
void aBlobMissingAFieldItsTypeRequiresIsDescribedWithoutAPublicKey(String blob) {
|
||||
String name = "public-key-" + UUID.randomUUID();
|
||||
String type = blob.startsWith("AAAAB3") ? "ssh-rsa" : "ssh-ed25519";
|
||||
describeImported(name, utf8(type + " " + blob + " " + name), response -> response
|
||||
.body("DescribeKeyPairsResponse.keySet.item.publicKey.size()", equalTo(0)));
|
||||
}
|
||||
|
||||
/**
|
||||
* A blob with anything after its key, here a whole extra field or three stray bytes after an
|
||||
* ed25519 key, is one OpenSSH refuses, so it is not described as a key either.
|
||||
*/
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"field", "bytes"})
|
||||
void aBlobWithAnythingAfterItsKeyIsDescribedWithoutAPublicKey(String trailing) {
|
||||
String name = "public-key-" + UUID.randomUUID();
|
||||
byte[] key = Base64.getDecoder().decode(ED25519_BLOB);
|
||||
byte[] extra = "field".equals(trailing) ? new byte[] {0, 0, 0, 5, 'e', 'x', 't', 'r', 'a'} : new byte[] {1, 2, 3};
|
||||
String blob = Base64.getEncoder().encodeToString(
|
||||
ByteBuffer.allocate(key.length + extra.length).put(key).put(extra).array());
|
||||
describeImported(name, utf8("ssh-ed25519 " + blob + " " + name), response -> response
|
||||
.body("DescribeKeyPairsResponse.keySet.item.publicKey.size()", equalTo(0)));
|
||||
}
|
||||
|
||||
/**
|
||||
* A line that names another type than its blob declares, here a whole ssh-rsa blob labelled
|
||||
* ssh-ed25519, is not described as the RSA key its blob holds.
|
||||
*/
|
||||
@Test
|
||||
void aLineLabelledWithAnotherTypeThanItsBlobIsDescribedWithoutAPublicKey() {
|
||||
String name = "public-key-" + UUID.randomUUID();
|
||||
String rsaBlob = Ec2KeyMaterial.generateRsa().openSshPublicKey().split(" ")[1];
|
||||
describeImported(name, utf8("ssh-ed25519 " + rsaBlob + " " + name), response -> response
|
||||
.body("DescribeKeyPairsResponse.keySet.item.publicKey.size()", equalTo(0)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Material holding several key lines is not one key pair's key: an instance launched with it
|
||||
* trusts every line, so describing only the first would hide the others.
|
||||
*/
|
||||
@Test
|
||||
void materialHoldingSeveralKeysIsDescribedWithoutAPublicKey() {
|
||||
String name = "public-key-" + UUID.randomUUID();
|
||||
String second = Ec2KeyMaterial.generateRsa().openSshPublicKey();
|
||||
describeImported(name, utf8("ssh-ed25519 " + ED25519_BLOB + " first\n" + second + " second\n"),
|
||||
response -> response.body("DescribeKeyPairsResponse.keySet.item.publicKey.size()", equalTo(0)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Imports the material under the given name, describes the key pair with IncludePublicKey=true
|
||||
* and hands the response to the check, then deletes the key pair whatever the check found.
|
||||
*/
|
||||
private static void describeImported(String name, byte[] material, Consumer<ValidatableResponse> check) {
|
||||
String id = given().header("Authorization", AUTH)
|
||||
.formParam("Action", "ImportKeyPair").formParam("KeyName", name)
|
||||
.formParam("PublicKeyMaterial", Base64.getEncoder().encodeToString(material))
|
||||
.post("/").then().statusCode(200).extract().path("ImportKeyPairResponse.keyPairId");
|
||||
try {
|
||||
check.accept(given().header("Authorization", AUTH).formParam("Action", "DescribeKeyPairs")
|
||||
.formParam("KeyPairId.1", id).formParam("IncludePublicKey", "true")
|
||||
.post("/").then().statusCode(200)
|
||||
.body("DescribeKeyPairsResponse.keySet.item.keyPairId", equalTo(id)));
|
||||
} finally {
|
||||
deleteKeyPair(id);
|
||||
}
|
||||
}
|
||||
|
||||
private static void deleteKeyPair(String id) {
|
||||
given().header("Authorization", AUTH).formParam("Action", "DeleteKeyPair")
|
||||
.formParam("KeyPairId", id).post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
/** The OpenSSH line, without a comment, of the public half of a PEM private key. */
|
||||
private static String publicHalfOf(String privateKeyPem) throws IOException {
|
||||
try (PEMParser parser = new PEMParser(new StringReader(privateKeyPem))) {
|
||||
PEMKeyPair pair = (PEMKeyPair) parser.readObject();
|
||||
return SshPublicKeys.toOpenSsh((RSAPublicKey) new JcaPEMKeyConverter().getKeyPair(pair).getPublic());
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] utf8(String text) {
|
||||
return text.getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.ec2;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsPartition;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.services.ec2.model.KeyPair;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Subnet;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Tag;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Vpc;
|
||||
@@ -12,6 +13,7 @@ import jakarta.ws.rs.core.Response;
|
||||
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.NullAndEmptySource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
@@ -260,6 +262,34 @@ class Ec2QueryHandlerTest {
|
||||
assertFalse(xml.contains("cn-north-1"), xml);
|
||||
}
|
||||
|
||||
/**
|
||||
* The key-pair name becomes the comment only when it can be one. A key pair stored before
|
||||
* KeyName was required has no name, which would otherwise read {@code null}, and a name with a
|
||||
* line break would split the key into lines an authorized_keys file reads as further keys (XML
|
||||
* turns a carriage return into a line feed on the way), so a name holding any control
|
||||
* character, a tab included, is left off.
|
||||
*/
|
||||
@ParameterizedTest
|
||||
@NullAndEmptySource
|
||||
@ValueSource(strings = {"two\nlines", "carriage\rreturn", "a\ttab"})
|
||||
void describeKeyPairsGivesTheKeyNoCommentWhenTheNameCannotBeOne(String name) {
|
||||
String line = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIIj7azlDjVHAsSxgcpCRZ3oWnTm0nAFM64y9jd22ioI/";
|
||||
KeyPair keyPair = new KeyPair();
|
||||
keyPair.setKeyPairId("key-0123456789abcdef0");
|
||||
keyPair.setKeyName(name);
|
||||
keyPair.setPublicKey(line + " imported-comment");
|
||||
Ec2Service service = mock(Ec2Service.class);
|
||||
when(service.describeKeyPairs(eq("us-east-1"), anyList(), anyList())).thenReturn(List.of(keyPair));
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("IncludePublicKey", "true");
|
||||
|
||||
Response response = handler(service).handle("DescribeKeyPairs", params, "us-east-1");
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
String xml = (String) response.getEntity();
|
||||
assertTrue(xml.contains("<publicKey>" + line + "</publicKey>"), xml);
|
||||
}
|
||||
|
||||
private String describeRegions(RegionResolver regionResolver, String region) {
|
||||
Ec2Service service = mock(Ec2Service.class);
|
||||
when(service.describeRegions(any(AwsPartition.class), anyBoolean())).thenCallRealMethod();
|
||||
|
||||
Reference in new issue
Block a user