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:
Jackson Price authored and GitHub committed 2026-10-20 09:54:54 -04:00
1 parent cbdeb0c8dc
commit 9f9c16a181
7 files changed
+506 -4

No files matched your search

@@ -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");