fix(ec2): refuse key pairs AWS refuses and describe their type, create time and filters (#6093)

* fix(ec2): refuse key pairs AWS refuses and describe their type, create time and filters

ImportKeyPair stored whatever material it was given. It now reads the key
as AWS documents: RSA or ED25519 as an OpenSSH line, RSA also as RFC 4716
or base64 DER, bare or in PEM armour, and RSA from 1024 to 16384 bits.
DSA, ECDSA, security-key and certificate keys, blobs that are incomplete,
carry trailing bytes or name another type, and material with more than one
key line are refused with InvalidKey.Format. The key is stored as one
OpenSSH line, which is what RunInstances writes to authorized_keys.
CreateKeyPair and ImportKeyPair take a KeyName of up to 255 ASCII
characters with no leading or trailing space, and answer any other with
InvalidParameterValue.

DescribeKeyPairs now returns keyType and createTime, and honours Filter.N
with key-pair-id, key-name, fingerprint, key-type, tag-key and tag:<key>,
refusing any other name. Key pairs persisted before this change load as
they are: they have no createTime, and their keyType is read from the
stored key.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(ec2): describe malformed key pairs from saved records, not imports

ImportKeyPair now refuses material that is not exactly one whole key and
converts RFC 4716, so the IncludePublicKey cases that imported partial
or mislabelled blobs, trailing bytes, two key lines or UTF-16 text could
no longer create their key pairs. Such material is now held only by key
pairs saved by an earlier version, so those cases describe a stored
record through the handler instead, and the RFC 4716 case checks that
the converted key is described as its OpenSSH line.

The handler test stubs the DescribeKeyPairs overload that takes filters,
which the handler now calls. The Key Pairs docs and the javadoc of the
public-key description say what is stored now and what an older record
may still hold.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(ec2): refuse a DER key whose bit string declares pad bits

A SubjectPublicKeyInfo whose key BIT STRING declares unused bits made
Bouncy Castle throw an IllegalStateException, which the key reader did
not catch. ImportKeyPair answered such base64 DER or PEM with a 500
instead of InvalidKey.Format, and a key pair saved earlier with that
material failed every DescribeKeyPairs in its region, since the key type
of an older record is read from its material.

The reader now refuses a key bit string with pad bits, and treats Bouncy
Castle's IllegalStateException like its other parse errors. A new test
sets every byte of each binary form to values that matter to DER and SSH
framing and checks that nothing escapes.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(ec2): refuse an IncludePublicKey that is neither true nor false

DescribeKeyPairs read IncludePublicKey with Boolean.parseBoolean, so a
value such as "invalid" or "yes" was taken as false and the key pairs
were described without their public keys instead of the request being
refused. It now goes through the handler's strict boolean reader, the
one the block device mapping and peering options use: true or false in
any case, and InvalidParameterValue for anything else. TRUE was already
read as true, and still is.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(ec2): send each describe filter once and allow clock skew in the SDK check

The DescribeKeyPairs integration helper always sent a key-name filter of
the test's prefix, so the cases that test key-name itself sent the name
twice and Floci kept only the second. A key-name filter under test is now
sent alone. The SDK compatibility check gives createTime a minute either
side, since Floci may run in a container with another clock.

The Key Pairs docs and the RSA length test now say what AWS lists and
what Floci takes beyond it, citing the 8192-bit key AWS was seen to
import.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(ec2): refuse a DER key with no key in its bit string

An rsaEncryption SubjectPublicKeyInfo whose key bit string holds no bytes
parses to no structure at all, and the reader passed that null on to a
NullPointerException: ImportKeyPair answered such DER or PEM with a 500,
and a key pair saved earlier with it failed DescribeKeyPairs for every
listing that included it. The reader now reads the PKCS#1 sequence
itself and refuses anything that is not two integers.

It reads those integers signed, as an ssh-rsa blob's are, so a modulus
missing its sign byte is refused rather than imported as a different,
positive key. And the key type of an older record no longer depends on
the reader never failing: if it does, the type is left out and the
failure logged, instead of failing the whole description.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* docs(ec2): keep key pair comments and docs true to the new checks

SshPublicKeyException's javadoc said EC2 answers an unreadable imported
key with no fingerprint; ImportKeyPair now refuses it with
InvalidKey.Format. The Key Pairs docs say that an empty IncludePublicKey
reads as false. The RSA length test links the report of an 8192-bit
import in full, and the describe test says that sending one key-name
filter is a Floci limit, not an AWS rule.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(ec2): cover the stored key-type guard on its own

The stored-record test passed even with the reader broken, because the
guard in keyTypeOf turned the reader's exception into the expected
missing type. It now checks that the reader refuses each stored material
by itself, and a new test makes the reader fail, through an inline static
mock as other tests here do, and checks that the record is still
described, with no type, and that a key-type filter passes over it.

The keyTypeOf javadoc and the docs now mention that case, the docs say a
blank IncludePublicKey reads as false and a missing or blank KeyName is
MissingParameter, and a comment no longer says every imported key is
fingerprinted with MD5.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(ec2): make the stored key-type guard test depend on its failing reader

The guard test stored text the real reader already refuses without
throwing, so it passed even if the failing reader was never consulted.
It now stores a valid ed25519 key, whose type would be ed25519 without
the failure, checks that the stubbed reader was called, and describes the
record through the handler too, where each item's type is read. A
comment on the stored-record test no longer says the reader refuses the
records it accepts.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(ec2): AND a repeated DescribeKeyPairs filter name

DescribeKeyPairs read Filter.N into a map keyed by name, so a second
filter of one name replaced the first: key-name=X-prod-* with
key-name=X-*-web returned X-dev-web too. AWS joins every filter with AND.
The handler now passes the filters in request order, as
DescribeAvailabilityZones already does, and a key pair has to match each
of them, with the values of one filter still ORed.

The other EC2 describe actions share the map reader and keep its
behaviour; that is for a separate change. The describe test's helper
goes back to ANDing a second key-name filter with its prefix filter.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(ec2): show the key-type guard covers only key pairs saved without a type

With the key reader made to fail, ImportKeyPair still fails with the
error, and a key pair whose type was recorded is described and filtered
by key-type without the reader being consulted. Only a record saved
before the type was recorded goes through the guard that leaves its type
out and logs the failure.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(ec2): check repeated key pair filters in the service, and route unfiltered calls through them

A service test now passes Filter.N with a repeated name to the ordered
DescribeKeyPairs overload and checks that the two filters are ANDed, and
that a later unknown name is still refused. The unfiltered overload goes
through the ordered one too, leaving the map form as a convenience for
filters of distinct names, and the docs sentence on filters is split in
two.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(ec2): pick repeated key pair filters that each match more alone

The service check of a repeated key-name filter used `*-rsa` then `g*`,
and `g*` alone gives the same answer, so it passed when only the last
filter was kept. Each filter now matches two key pairs alone and one
together, so keeping either one instead fails the test.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(ec2): share one fixture between the key pair tests

The import, describe and public-key integration tests each had their
own CreateKeyPair, ImportKeyPair and DeleteKeyPair calls, and the same
ED25519 key was pasted into five classes. Ec2KeyPairFixtures now holds
those calls and the one key, which the handler, service and persistence
tests use too. SshKeyBlobs builds the OpenSSH blobs and lines that
SshPublicKeysTest, Ec2KeyMaterialTest and Ec2QueryHandlerTest each built
and joined themselves, and the import test reads RSA keys with
SshPublicKeys.rsaKeyOf instead of its own copy.

Test-only: every class runs the same tests as before.
Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(ec2): build key blobs with the SshPublicKeysTest helpers main has

SshPublicKeysTest on main already builds OpenSSH blobs with blob and
joins bytes with withTrailing. The EC2 key pair tests now call those two,
made public for them, instead of the SshKeyBlobs class the previous
commit added, which is removed.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(ec2): keep the shared throwaway keys in Ec2KeyPairFixtures

The pinned RSA key and its fingerprint, the ED25519 fingerprint, the DSA
and ECDSA P-256 keys and the truncated ssh-rsa blob were each written
out in two to four of the key pair test classes. They now live beside
the ED25519 key in Ec2KeyPairFixtures; keys only Ec2KeyMaterialTest
uses stay there. The handler test loses a comment and an import the
earlier move left behind.

The earlier move also switched Ec2KeyPairPublicKeyIntegrationTest and
Ec2QueryHandlerTest from the ED25519 key #6055 added to the shared one;
no assertion in them depends on which valid key it is.

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:
Jackson Price authored and GitHub committed 2026-10-21 09:11:13 -04:00
1 parent f2b62fbbec
commit fbf3bfff84
18 files changed
+1801 -222

No files matched your search

@@ -2,8 +2,8 @@ package io.github.hectorvent.floci.core.common;
/**
* Public key material that could not be read. Thrown by {@link SshPublicKeys} so that each caller
* maps it onto whatever its own API calls the failure, rather than the parser deciding: EC2
* answers an unreadable imported key with no fingerprint at all.
* maps it onto whatever its own API calls the failure, rather than the parser deciding: EC2's
* ImportKeyPair answers an unreadable key with InvalidKey.Format, IAM with InvalidPublicKey.
*/
public class SshPublicKeyException extends RuntimeException {
@@ -1,17 +1,27 @@
package io.github.hectorvent.floci.services.ec2;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.PublicKeys;
import io.github.hectorvent.floci.core.common.SshPublicKeyException;
import io.github.hectorvent.floci.core.common.SshPublicKeys;
import org.bouncycastle.asn1.ASN1Integer;
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.openssl.jcajce.JcaPEMWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPublicKey;
import java.util.Base64;
import java.util.HexFormat;
import java.util.List;
/**
* Real key material for EC2 key pairs.
@@ -32,6 +42,15 @@ public final class Ec2KeyMaterial {
/** An ed25519 public key is a fixed 32-byte value, so any other length is not one. */
private static final int ED25519_KEY_LENGTH = 32;
/** The shortest RSA key ImportKeyPair takes, the shortest of the lengths AWS lists as supported. */
private static final int MIN_IMPORTED_RSA_BITS = 1024;
/** The longest RSA key ImportKeyPair takes, which is also the longest OpenSSH reads. */
private static final int MAX_IMPORTED_RSA_BITS = 16384;
private static final String RFC_4716_BEGIN = "---- BEGIN SSH2 PUBLIC KEY ----";
private static final String RFC_4716_END = "---- END SSH2 PUBLIC KEY ----";
private Ec2KeyMaterial() {}
/**
@@ -41,6 +60,16 @@ public final class Ec2KeyMaterial {
*/
public record Generated(String privateKeyPem, String openSshPublicKey, String fingerprint) {}
/**
* A public key ImportKeyPair accepted.
*
* @param keyType {@code rsa} or {@code ed25519}, as DescribeKeyPairs reports it
* @param fingerprint the fingerprint AWS reports for an imported key of that type
* @param openSshPublicKey the key as one {@code "ssh-rsa AAAA..."} line without a comment,
* whatever format it was imported in, for authorized_keys
*/
public record Imported(String keyType, String fingerprint, String openSshPublicKey) {}
public static Generated generateRsa() {
try {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
@@ -56,7 +85,7 @@ public final class Ec2KeyMaterial {
}
// "The SHA-1 digest of the DER encoded private key" for a key pair AWS created.
// (Imported keys use the MD5 of the public key instead -- see fingerprintOf.)
// (Imported keys are fingerprinted another way, by key type -- see readImportedKey.)
String fingerprint = colonHex(Digests.sha1(pair.getPrivate().getEncoded()));
return new Generated(
@@ -69,51 +98,63 @@ public final class Ec2KeyMaterial {
}
/**
* Fingerprint for an imported public key, in the scheme AWS uses for that key type.
* Reads the public key given to ImportKeyPair, accepting the key types and formats AWS
* documents: an RSA or ED25519 key as an OpenSSH line, and an RSA key also as an RFC 4716
* file or as base64 DER, bare or in PEM armour. An RSA key must be 1024 to 16384 bits. EC2
* does not accept DSA keys, and ECDSA and security-key types are not among those it supports.
*
* <p>ImportKeyPair does not fingerprint every key the same way, and it does not agree
* with CreateKeyPair either:
* <p>An OpenSSH line holds one key, whose blob has to be exactly the key of the type the line
* names, as OpenSSH requires: no field missing, nothing after the key, no other type. Material
* with a second line is refused rather than read as its first key, since an instance launched
* with the key pair would trust every line of it.
*
* <p>The fingerprint is the one AWS reports for an imported key, which is not the scheme
* CreateKeyPair uses:
*
* <ul>
* <li><b>ssh-rsa</b>: "the MD5 public key fingerprint", taken over the DER
* SubjectPublicKeyInfo rather than over the SSH wire blob. AWS documents the check
* as {@code openssl rsa -in key -pubout -outform DER | openssl md5 -c}, and
* {@link java.security.Key#getEncoded()} produces exactly that DER, so the blob is
* decoded back to a public key first. Colon-separated hex, as AWS reports it.</li>
* <li><b>ssh-ed25519</b>: the base64-encoded SHA-256 digest of the wire blob, "which is
* the default for OpenSSH". This is the {@code ssh-keygen -l} value without its
* {@code SHA256:} prefix, and padded: AWS keeps the trailing {@code =} that
* ssh-keygen drops.</li>
* <li><b>rsa</b>: "the MD5 public key fingerprint", taken over the DER SubjectPublicKeyInfo
* rather than over the SSH wire blob. AWS documents the check as
* {@code openssl rsa -in key -pubout -outform DER | openssl md5 -c}, and
* {@link java.security.Key#getEncoded()} produces exactly that DER. Colon-separated
* hex, as AWS reports it.</li>
* <li><b>ed25519</b>: the base64-encoded SHA-256 digest of the wire blob, "which is the
* default for OpenSSH". This is the {@code ssh-keygen -l} value without its
* {@code SHA256:} prefix, and padded: AWS keeps the trailing {@code =} that ssh-keygen
* drops.</li>
* </ul>
*
* <p>Any other key type keeps the MD5 of the wire blob: stable and distinct per key,
* which is what callers depend on, but not a value AWS would report. AWS accepts only
* RSA and ed25519 material for import, so nothing else has a documented answer to match.
*
* <p>Returns null for material that does not parse, so the caller can decide rather than
* getting a fingerprint of garbage.
*
* @return the key, or null when AWS would refuse the material
* @see <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/create-key-pairs.html#how-to-generate-your-own-key-and-import-it-to-aws">Requirements for key pairs</a>
* @see <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/verify-keys.html">Verify the fingerprint of your key pair</a>
*/
public static String fingerprintOf(String openSshPublicKey) {
byte[] blob = SshPublicKeys.decodeBlob(openSshPublicKey);
if (blob == null) {
public static Imported readImportedKey(String material) {
if (material == null) {
return null;
}
List<String> lines = material.trim().lines().map(String::strip).toList();
if (lines.isEmpty()) {
return null;
}
String first = lines.getFirst();
try {
SshPublicKeys.Reader reader = SshPublicKeys.reader(blob);
String type = new String(reader.readField(), StandardCharsets.UTF_8);
if ("ssh-ed25519".equals(type)) {
if (reader.readField().length != ED25519_KEY_LENGTH) {
return null;
}
return Base64.getEncoder().encodeToString(Digests.sha256(blob));
if (first.equals(RFC_4716_BEGIN)) {
byte[] blob = rfc4716Blob(lines);
return importedRsa(rsaKeyOfWholeBlob(blob), "ssh-rsa " + base64(blob));
}
// EC2 documents its ssh-rsa fingerprint as the MD5 of the DER, which is not the
// OpenSSH fingerprint of the same key. SshPublicKeys keeps the two apart on purpose.
byte[] der = "ssh-rsa".equals(type) ? SshPublicKeys.rsaKeyOf(blob).getEncoded() : blob;
return SshPublicKeys.md5ColonHex(der);
} catch (Exception e) { // malformed material is the caller's problem, not a crash
if (first.startsWith("-----BEGIN ")) {
RSAPublicKey key = rsaKeyOfDer(pemBody(lines));
return importedRsa(key, SshPublicKeys.toOpenSsh(key));
}
String[] fields = first.split("\\s+", 3);
if (fields.length > 1) {
return lines.size() == 1 ? openSshLine(fields[0], Base64.getDecoder().decode(fields[1])) : null;
}
RSAPublicKey key = rsaKeyOfDer(Base64.getDecoder().decode(String.join("", lines)));
return importedRsa(key, SshPublicKeys.toOpenSsh(key));
} catch (SshPublicKeyException | IllegalArgumentException | IllegalStateException
| GeneralSecurityException | IOException expected) {
// Material AWS refuses, which the caller answers with InvalidKey.Format. Bouncy Castle
// reports some malformed DER with an IllegalStateException rather than an IOException.
return null;
}
}
@@ -122,6 +163,133 @@ public final class Ec2KeyMaterial {
return SshPublicKeys.toOpenSsh(key);
}
/** The key of an OpenSSH line whose type field is {@code type} and whose blob is {@code blob}. */
private static Imported openSshLine(String type, byte[] blob) throws GeneralSecurityException {
return switch (type) {
case "ssh-rsa" -> importedRsa(rsaKeyOfWholeBlob(blob), "ssh-rsa " + base64(blob));
case "ssh-ed25519" -> importedEd25519(blob);
default -> null;
};
}
/**
* The RSA key of an {@code ssh-rsa} blob that holds its type, exponent and modulus and nothing
* else. {@link SshPublicKeys#rsaKeyOf} stops once it has the key; an import must not.
*/
private static RSAPublicKey rsaKeyOfWholeBlob(byte[] blob) throws GeneralSecurityException {
SshPublicKeys.Reader reader = SshPublicKeys.reader(blob);
byte[] type = reader.readField();
byte[] exponent = reader.readField();
byte[] modulus = reader.readField();
BigInteger e = new BigInteger(exponent);
BigInteger n = new BigInteger(modulus);
if (!"ssh-rsa".equals(new String(type, StandardCharsets.UTF_8)) || !fillsTheBlob(blob, type, exponent, modulus)
|| e.signum() <= 0 || n.signum() <= 0) {
throw new SshPublicKeyException("not exactly one ssh-rsa public key");
}
return PublicKeys.rsa(n, e);
}
private static Imported importedEd25519(byte[] blob) {
SshPublicKeys.Reader reader = SshPublicKeys.reader(blob);
byte[] type = reader.readField();
byte[] key = reader.readField();
if (!"ssh-ed25519".equals(new String(type, StandardCharsets.UTF_8)) || key.length != ED25519_KEY_LENGTH
|| !fillsTheBlob(blob, type, key)) {
return null;
}
return new Imported("ed25519", Base64.getEncoder().encodeToString(Digests.sha256(blob)),
"ssh-ed25519 " + base64(blob));
}
private static Imported importedRsa(RSAPublicKey key, String openSshPublicKey) {
int bits = key.getModulus().bitLength();
if (bits < MIN_IMPORTED_RSA_BITS || bits > MAX_IMPORTED_RSA_BITS) {
return null;
}
return new Imported("rsa", SshPublicKeys.md5ColonHex(key.getEncoded()), openSshPublicKey);
}
/** Whether the length-prefixed fields read so far are the whole blob, with nothing after them. */
private static boolean fillsTheBlob(byte[] blob, byte[]... fields) {
int length = 0;
for (byte[] field : fields) {
length += Integer.BYTES + field.length;
}
return length == blob.length;
}
/**
* The key blob of an RFC 4716 file: the base64 body between the begin and end markers, after
* its header lines, each a {@code Tag: value} that a trailing backslash continues onto the next.
*/
private static byte[] rfc4716Blob(List<String> lines) {
if (lines.size() < 3 || !RFC_4716_END.equals(lines.getLast())) {
throw new SshPublicKeyException("not an RFC 4716 public key");
}
StringBuilder body = new StringBuilder();
boolean continued = false;
for (String line : lines.subList(1, lines.size() - 1)) {
if (body.isEmpty() && (continued || line.contains(":"))) {
continued = line.endsWith("\\");
continue;
}
body.append(line);
}
return Base64.getDecoder().decode(body.toString());
}
/**
* The DER in PEM armour labelled as a public key: {@code PUBLIC KEY}, a SubjectPublicKeyInfo,
* or {@code RSA PUBLIC KEY}, the bare PKCS#1 key that {@code ssh-keygen -e -m PEM} writes. Any
* other label, such as a private key pasted by mistake, is not a public key.
*/
private static byte[] pemBody(List<String> lines) {
String label = lines.getFirst().substring("-----BEGIN ".length());
if (!("PUBLIC KEY-----".equals(label) || "RSA PUBLIC KEY-----".equals(label))
|| lines.size() < 3 || !lines.getLast().equals("-----END " + label)) {
throw new SshPublicKeyException("not a PEM public key");
}
return Base64.getDecoder().decode(String.join("", lines.subList(1, lines.size() - 1)));
}
/**
* The RSA key a DER SubjectPublicKeyInfo or PKCS#1 RSAPublicKey encodes. Another algorithm,
* such as an EC key, is refused, as are bytes after the structure.
*/
private static RSAPublicKey rsaKeyOfDer(byte[] der) throws IOException, GeneralSecurityException {
if (!(ASN1Primitive.fromByteArray(der) instanceof ASN1Sequence structure) || structure.size() == 0) {
throw new SshPublicKeyException("not a DER public key");
}
// A SubjectPublicKeyInfo opens with its algorithm, itself a sequence; PKCS#1 with the modulus.
ASN1Primitive rsaKey = structure;
if (structure.getObjectAt(0) instanceof ASN1Sequence) {
SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(structure);
// The key is a whole number of bytes, so a bit string declaring unused bits holds none.
if (!PKCSObjectIdentifiers.rsaEncryption.equals(info.getAlgorithm().getAlgorithm())
|| info.getPublicKeyData().getPadBits() != 0) {
throw new SshPublicKeyException("not an RSA public key");
}
rsaKey = info.parsePublicKey();
}
// PKCS#1 RSAPublicKey: SEQUENCE { modulus INTEGER, publicExponent INTEGER }. An empty bit string
// parses to nothing at all. The integers are read signed, as an ssh-rsa blob's are, so a
// modulus missing its sign byte is refused rather than read as another, positive key.
if (!(rsaKey instanceof ASN1Sequence fields) || fields.size() != 2) {
throw new SshPublicKeyException("not an RSA public key");
}
BigInteger modulus = ASN1Integer.getInstance(fields.getObjectAt(0)).getValue();
BigInteger exponent = ASN1Integer.getInstance(fields.getObjectAt(1)).getValue();
if (modulus.signum() <= 0 || exponent.signum() <= 0) {
throw new SshPublicKeyException("not an RSA public key");
}
return PublicKeys.rsa(modulus, exponent);
}
private static String base64(byte[] bytes) {
return Base64.getEncoder().encodeToString(bytes);
}
private static String colonHex(byte[] digest) {
return HexFormat.of().withDelimiter(":").formatHex(digest);
}
@@ -3433,10 +3433,10 @@ public class Ec2QueryHandler {
}
private Response handleDescribeKeyPairs(MultivaluedMap<String, String> p, String region) {
boolean includePublicKey = Boolean.parseBoolean(p.getFirst("IncludePublicKey"));
boolean includePublicKey = Boolean.TRUE.equals(parseOptionalBoolean(p.getFirst("IncludePublicKey"), "IncludePublicKey"));
List<String> keyNames = getList(p, "KeyName");
List<String> keyPairIds = getList(p, "KeyPairId");
List<KeyPair> kps = service.describeKeyPairs(region, keyNames, keyPairIds);
List<KeyPair> kps = service.describeKeyPairs(region, keyNames, keyPairIds, getFiltersList(p));
XmlBuilder xml = new XmlBuilder()
.start("DescribeKeyPairsResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
@@ -3444,6 +3444,8 @@ public class Ec2QueryHandler {
for (KeyPair kp : kps) {
xml.start("item")
.elem("keyPairId", kp.getKeyPairId())
.elem("keyType", Ec2Service.keyTypeOf(kp))
.elem("createTime", kp.getCreateTime() != null ? ISO_FMT.format(kp.getCreateTime()) : null)
.elem("keyName", kp.getKeyName())
.elem("keyFingerprint", kp.getKeyFingerprint());
if (includePublicKey) {
@@ -3457,13 +3459,14 @@ public class Ec2QueryHandler {
/**
* 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.
* DescribeKeyPairs reports for created and imported keys alike. ImportKeyPair stores one OpenSSH
* line, but a key pair saved by an earlier version kept the material 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, and PEM, DER and RFC 4716 bodies saved that way are not
* converted here. 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();
@@ -236,6 +236,14 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
private static final Set<String> EGRESS_ONLY_INTERNET_GATEWAY_FILTERS = Set.of(
"attachment.state", "attachment.vpc-id",
"egress-only-internet-gateway-id", "tag-key", "tag-value");
/**
* The filter names DescribeKeyPairs documents, with tag:&lt;key&gt; admitted through tag-key,
* plus key-type, which the documentation omits but which every key pair carries.
*/
private static final Set<String> KEY_PAIR_FILTERS = Set.of(
"fingerprint", "key-name", "key-pair-id", "key-type", "tag-key");
/** The longest key-pair name CreateKeyPair and ImportKeyPair take. */
private static final int MAX_KEY_NAME_LENGTH = 255;
private static final Set<String> AVAILABILITY_ZONE_FILTERS = Set.of(
"group-long-name", "group-name", "message", "opt-in-status",
"parent-zone-id", "parent-zone-name", "region-name", "state",
@@ -7416,13 +7424,33 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
// 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.setCreateTime(Instant.now());
kp.setRegion(region);
keyPairs.put(key(region, keyPairId), kp);
return kp;
}
public List<KeyPair> describeKeyPairs(String region, List<String> keyNames, List<String> keyPairIds) {
return describeKeyPairs(region, keyNames, keyPairIds, List.of());
}
/** A convenience for filters of distinct names; a request's Filter.N goes through the ordered overload. */
public List<KeyPair> describeKeyPairs(String region, List<String> keyNames, List<String> keyPairIds,
Map<String, List<String>> filters) {
return describeKeyPairs(region, keyNames, keyPairIds, List.copyOf(filters.entrySet()));
}
/**
* Filter.N in request order, each a name and its values: AWS ANDs the filters, a repeated name
* included, and ORs the values within one.
*/
public List<KeyPair> describeKeyPairs(String region, List<String> keyNames, List<String> keyPairIds,
List<Map.Entry<String, List<String>>> filters) {
ensureDefaultResources(region);
// matchesFilter answers true for a name it does not know, so an unknown name would match
// every key pair rather than fail as it does in AWS.
requireSupportedFilters(filters.stream().map(Map.Entry::getKey).toList(), KEY_PAIR_FILTERS);
List<KeyPair> regionKeyPairs = keyPairs.scan(k -> true).stream()
.filter(k -> k.getRegion().equals(region))
.collect(Collectors.toList());
@@ -7446,9 +7474,34 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
return regionKeyPairs.stream()
.filter(k -> keyNames.isEmpty() || keyNames.contains(k.getKeyName()))
.filter(k -> keyPairIds.isEmpty() || keyPairIds.contains(k.getKeyPairId()))
.filter(k -> filters.stream().allMatch(f -> matchesFilter(k, f.getKey(), f.getValue(), region)))
.collect(Collectors.toList());
}
/**
* 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.
*/
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;
} 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;
}
}
/**
* Deletes by id when one is given, otherwise by name, and returns the deleted key pair so
* the response can carry its id. Null when nothing matched: AWS answers a delete of an
@@ -7472,19 +7525,23 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
public KeyPair importKeyPair(String region, String keyName, String publicKeyMaterial) {
ensureDefaultResources(region);
requireKeyName(keyName);
Ec2KeyMaterial.Imported imported = Ec2KeyMaterial.readImportedKey(publicKeyMaterial);
if (imported == null) {
throw new AwsException("InvalidKey.Format", "Key is not in valid OpenSSH public key format", 400);
}
rejectDuplicateKeyName(region, keyName);
String keyPairId = "key-" + randomHex(17);
KeyPair kp = new KeyPair();
kp.setKeyPairId(keyPairId);
kp.setKeyName(keyName);
// A per-key fingerprint, not a constant: callers compare it to detect that the key
// under a given name has been replaced. Falls back to the old placeholder only when
// the material does not parse, rather than reporting a digest of garbage.
String fingerprint = Ec2KeyMaterial.fingerprintOf(publicKeyMaterial);
kp.setKeyFingerprint(fingerprint != null
? fingerprint
: "00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00");
kp.setPublicKey(publicKeyMaterial);
// under a given name has been replaced.
kp.setKeyFingerprint(imported.fingerprint());
kp.setKeyType(imported.keyType());
// The key as one OpenSSH line, whatever format it came in: RunInstances writes it to the
// guest's authorized_keys, which reads neither RFC 4716 nor DER.
kp.setPublicKey(imported.openSshPublicKey());
kp.setCreateTime(Instant.now());
kp.setRegion(region);
keyPairs.put(key(region, keyPairId), kp);
return kp;
@@ -7542,10 +7599,26 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
return containerManager.isContainerRunning(instance.getDockerContainerId());
}
/**
* A key-pair name as AWS documents it for CreateKeyPair and ImportKeyPair alike: up to 255
* ASCII characters, with no leading or trailing space.
*/
private static void requireKeyName(String keyName) {
if (keyName == null || keyName.isBlank()) {
throw new AwsException("MissingParameter", "The request must contain the parameter KeyName", 400);
}
String reason = null;
if (keyName.length() > MAX_KEY_NAME_LENGTH) {
reason = "Length exceeds maximum of " + MAX_KEY_NAME_LENGTH + " characters.";
} else if (keyName.chars().anyMatch(c -> c > 0x7F)) {
reason = "Character sets beyond ASCII are not supported.";
} else if (keyName.startsWith(" ") || keyName.endsWith(" ")) {
reason = "Leading and trailing spaces are not allowed.";
}
if (reason != null) {
throw new AwsException("InvalidParameterValue",
"Value (" + keyName + ") for parameter KeyName is invalid. " + reason, 400);
}
}
// Compared name-first so a nameless record can never throw here. One such record, stored
@@ -11872,6 +11945,15 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
default -> true;
};
}
if (resource instanceof KeyPair keyPair) {
return switch (filterName) {
case "key-pair-id" -> matchesValue(values, keyPair.getKeyPairId());
case "key-name" -> matchesValue(values, keyPair.getKeyName());
case "fingerprint" -> matchesValue(values, keyPair.getKeyFingerprint());
case "key-type" -> matchesValue(values, keyTypeOf(keyPair));
default -> true;
};
}
return true;
}
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.ec2.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
@@ -15,6 +16,8 @@ public class KeyPair {
private String keyFingerprint;
private String keyMaterial;
private String publicKey;
private String keyType;
private Instant createTime;
private String region;
private List<Tag> tags = new ArrayList<>();
@@ -35,6 +38,14 @@ public class KeyPair {
public String getPublicKey() { return publicKey; }
public void setPublicKey(String publicKey) { this.publicKey = publicKey; }
/** {@code rsa} or {@code ed25519}; null for a key pair stored before the type was recorded. */
public String getKeyType() { return keyType; }
public void setKeyType(String keyType) { this.keyType = keyType; }
/** When the key pair was created or imported; null for one stored before this was recorded. */
public Instant getCreateTime() { return createTime; }
public void setCreateTime(Instant createTime) { this.createTime = createTime; }
public String getRegion() { return region; }
public void setRegion(String region) { this.region = region; }