mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -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
@@ -9,15 +9,20 @@ import org.bouncycastle.asn1.ASN1Primitive;
|
||||
import org.bouncycastle.asn1.ASN1Sequence;
|
||||
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
|
||||
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
|
||||
import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters;
|
||||
import org.bouncycastle.crypto.util.OpenSSHPrivateKeyUtil;
|
||||
import org.bouncycastle.crypto.util.OpenSSHPublicKeyUtil;
|
||||
import org.bouncycastle.openssl.jcajce.JcaPEMWriter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringWriter;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.math.BigInteger;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.SecureRandom;
|
||||
import java.security.interfaces.RSAPublicKey;
|
||||
import java.util.Base64;
|
||||
import java.util.HexFormat;
|
||||
@@ -51,12 +56,18 @@ public final class Ec2KeyMaterial {
|
||||
private static final String RFC_4716_BEGIN = "---- BEGIN SSH2 PUBLIC KEY ----";
|
||||
private static final String RFC_4716_END = "---- END SSH2 PUBLIC KEY ----";
|
||||
|
||||
/** The base64 line length of ssh-keygen's private key files; readers take any. */
|
||||
private static final int OPENSSH_LINE_LENGTH = 70;
|
||||
|
||||
private Ec2KeyMaterial() {}
|
||||
|
||||
/**
|
||||
* @param privateKeyPem PKCS#1 PEM, the "BEGIN RSA PRIVATE KEY" form AWS returns
|
||||
* @param openSshPublicKey the matching "ssh-rsa AAAA..." line, for authorized_keys
|
||||
* @param fingerprint SHA-1 of the DER private key, colon-separated hex
|
||||
* @param privateKeyPem the private key as KeyMaterial returns it: for an RSA key as PEM, the PKCS#1
|
||||
* "BEGIN RSA PRIVATE KEY" form AWS returns, for an ED25519 key as an OpenSSH
|
||||
* private key, and for KeyFormat ppk as a PuTTY key file
|
||||
* @param openSshPublicKey the matching "ssh-rsa AAAA..." or "ssh-ed25519 AAAA..." line, for authorized_keys
|
||||
* @param fingerprint for an RSA key the SHA-1 of the DER private key, colon-separated hex; for an
|
||||
* ED25519 key the base64 SHA-256 of the public key blob
|
||||
*/
|
||||
public record Generated(String privateKeyPem, String openSshPublicKey, String fingerprint) {}
|
||||
|
||||
@@ -198,8 +209,7 @@ public final class Ec2KeyMaterial {
|
||||
|| !fillsTheBlob(blob, type, key)) {
|
||||
return null;
|
||||
}
|
||||
return new Imported("ed25519", Base64.getEncoder().encodeToString(Digests.sha256(blob)),
|
||||
"ssh-ed25519 " + base64(blob));
|
||||
return new Imported("ed25519", ed25519Fingerprint(blob), "ssh-ed25519 " + base64(blob));
|
||||
}
|
||||
|
||||
private static Imported importedRsa(RSAPublicKey key, String openSshPublicKey) {
|
||||
@@ -290,7 +300,64 @@ public final class Ec2KeyMaterial {
|
||||
return Base64.getEncoder().encodeToString(bytes);
|
||||
}
|
||||
|
||||
private static String colonHex(byte[] digest) {
|
||||
static String colonHex(byte[] digest) {
|
||||
return HexFormat.of().withDelimiter(":").formatHex(digest);
|
||||
}
|
||||
|
||||
/**
|
||||
* The fingerprint EC2 gives an ED25519 key, created or imported: the base64-encoded SHA-256 of the
|
||||
* public key blob, the value {@code ssh-keygen -l} prints after {@code SHA256:}, with the {@code =}
|
||||
* padding AWS keeps and ssh-keygen drops.
|
||||
*/
|
||||
private static String ed25519Fingerprint(byte[] blob) {
|
||||
return base64(Digests.sha256(blob));
|
||||
}
|
||||
|
||||
/** A new ED25519 key pair for CreateKeyPair's {@code KeyType=ed25519}. */
|
||||
static Generated generateEd25519() {
|
||||
return ed25519(new Ed25519PrivateKeyParameters(new SecureRandom()));
|
||||
}
|
||||
|
||||
/**
|
||||
* The material CreateKeyPair returns for an ED25519 private key: the key in OpenSSH's own private
|
||||
* key format, the {@code BEGIN OPENSSH PRIVATE KEY} block AWS returns for one, since PKCS#1, the
|
||||
* RSA form, has no ED25519 encoding.
|
||||
*/
|
||||
static Generated ed25519(Ed25519PrivateKeyParameters privateKey) {
|
||||
byte[] blob;
|
||||
byte[] encoded;
|
||||
try {
|
||||
blob = OpenSSHPublicKeyUtil.encodePublicKey(privateKey.generatePublicKey());
|
||||
encoded = OpenSSHPrivateKeyUtil.encodePrivateKey(privateKey);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException("Could not encode an ED25519 key pair", e);
|
||||
}
|
||||
String body = base64(encoded);
|
||||
StringBuilder pem = new StringBuilder("-----BEGIN OPENSSH PRIVATE KEY-----\n");
|
||||
for (int i = 0; i < body.length(); i += OPENSSH_LINE_LENGTH) {
|
||||
pem.append(body, i, Math.min(i + OPENSSH_LINE_LENGTH, body.length())).append('\n');
|
||||
}
|
||||
pem.append("-----END OPENSSH PRIVATE KEY-----\n");
|
||||
return new Generated(pem.toString(), "ssh-ed25519 " + base64(blob), ed25519Fingerprint(blob));
|
||||
}
|
||||
|
||||
/**
|
||||
* The key pair CreateKeyPair returns for a KeyType, {@code rsa} or {@code ed25519}, and a
|
||||
* KeyFormat, {@code pem} or {@code ppk}: a new key of that type, its private half in that format.
|
||||
* The request has already been refused for any other value.
|
||||
*
|
||||
* @param keyName the key pair's name, which a PuTTY key file carries as its comment
|
||||
*/
|
||||
public static Generated generate(String keyType, String keyFormat, String keyName) {
|
||||
Generated pem = switch (keyType) {
|
||||
case "rsa" -> generateRsa();
|
||||
case "ed25519" -> generateEd25519();
|
||||
default -> throw new IllegalArgumentException("Unsupported key type: " + keyType);
|
||||
};
|
||||
return switch (keyFormat) {
|
||||
case "pem" -> pem;
|
||||
case "ppk" -> Ec2PuttyKeys.of(pem, keyName);
|
||||
default -> throw new IllegalArgumentException("Unsupported key format: " + keyFormat);
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package io.github.hectorvent.floci.services.ec2;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.Digests;
|
||||
import io.github.hectorvent.floci.core.common.Pem;
|
||||
import io.github.hectorvent.floci.core.common.SshPublicKeys;
|
||||
import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters;
|
||||
import org.bouncycastle.crypto.util.OpenSSHPrivateKeyUtil;
|
||||
import org.bouncycastle.util.io.pem.PemReader;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.StringReader;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.math.BigInteger;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.interfaces.RSAPrivateCrtKey;
|
||||
import java.security.spec.RSAPrivateCrtKeySpec;
|
||||
import java.util.Base64;
|
||||
import java.util.HexFormat;
|
||||
|
||||
/**
|
||||
* The key pair CreateKeyPair returns for {@code KeyFormat=ppk}: the key it creates for PEM, written
|
||||
* as a PuTTY private key file instead.
|
||||
*
|
||||
* <p>The file is version 2 of PuTTY's format, unencrypted, with the key pair's name as its comment,
|
||||
* which is what AWS returns for an RSA and an ED25519 key alike; every PuTTY release since 0.52 reads
|
||||
* version 2, and since 0.68 for an ED25519 key. It is laid out as PuTTY's sshpubk.c writes it: a line
|
||||
* naming the key's algorithm, {@code Encryption: none}, the comment, the public key blob and the
|
||||
* private fields as counted lines of base64, 64 characters to a line, and a {@code Private-MAC}, the
|
||||
* HMAC-SHA1 of the algorithm, the encryption, the comment and both blobs, each as an SSH string, keyed
|
||||
* with the SHA-1 of {@code putty-private-key-file-mac-key} followed by the passphrase, empty here.
|
||||
*
|
||||
* <p>The public key and the fingerprint are the PEM key's, but for the order of an RSA key's primes:
|
||||
* PuTTY keeps the larger first, which Java's key generator does not ensure, so the key is written in
|
||||
* that order and fingerprinted, by the SHA-1 of its DER private key, as written. That is the key
|
||||
* PuTTYgen exports from the file.
|
||||
*
|
||||
* @see <a href="https://the.earth.li/~sgtatham/putty/0.83/htmldoc/AppendixC.html">PuTTY's key file format</a>
|
||||
*/
|
||||
final class Ec2PuttyKeys {
|
||||
|
||||
private static final int LINE_LENGTH = 64;
|
||||
|
||||
private Ec2PuttyKeys() {}
|
||||
|
||||
/**
|
||||
* {@code pem} as a PuTTY key file whose comment is {@code keyName}, or empty for a name holding a
|
||||
* control character, such as a line break, since the comment is a line of the file.
|
||||
*/
|
||||
static Ec2KeyMaterial.Generated of(Ec2KeyMaterial.Generated pem, String keyName) {
|
||||
byte[] publicBlob = SshPublicKeys.decodeBlob(pem.openSshPublicKey());
|
||||
String algorithm = SshPublicKeys.keyType(publicBlob);
|
||||
String comment = keyName == null || keyName.chars().anyMatch(Character::isISOControl) ? "" : keyName;
|
||||
return switch (algorithm) {
|
||||
case "ssh-rsa" -> {
|
||||
RSAPrivateCrtKey key = largerPrimeFirst((RSAPrivateCrtKey) Pem.parsePrivateKey(pem.privateKeyPem()));
|
||||
// PuTTY's ssh-rsa private fields: the private exponent, the primes and the inverse of the
|
||||
// second prime modulo the first.
|
||||
byte[] privateBlob = strings(key.getPrivateExponent().toByteArray(), key.getPrimeP().toByteArray(),
|
||||
key.getPrimeQ().toByteArray(), key.getCrtCoefficient().toByteArray());
|
||||
yield new Ec2KeyMaterial.Generated(file(algorithm, comment, publicBlob, privateBlob),
|
||||
pem.openSshPublicKey(), Ec2KeyMaterial.colonHex(Digests.sha1(key.getEncoded())));
|
||||
}
|
||||
// PuTTY's ssh-ed25519 private field: the 32-byte private key, without OpenSSH's copy of the public key.
|
||||
case "ssh-ed25519" -> new Ec2KeyMaterial.Generated(
|
||||
file(algorithm, comment, publicBlob, strings(ed25519PrivateKey(pem.privateKeyPem()))),
|
||||
pem.openSshPublicKey(), pem.fingerprint());
|
||||
default -> throw new IllegalArgumentException("No PuTTY key file for a " + algorithm + " key");
|
||||
};
|
||||
}
|
||||
|
||||
private static String file(String algorithm, String comment, byte[] publicBlob, byte[] privateBlob) {
|
||||
StringBuilder file = new StringBuilder()
|
||||
.append("PuTTY-User-Key-File-2: ").append(algorithm).append('\n')
|
||||
.append("Encryption: none\n")
|
||||
.append("Comment: ").append(comment).append('\n');
|
||||
appendLines(file, "Public-Lines", publicBlob);
|
||||
appendLines(file, "Private-Lines", privateBlob);
|
||||
byte[] mac = mac(strings(ascii(algorithm), ascii("none"), comment.getBytes(StandardCharsets.UTF_8),
|
||||
publicBlob, privateBlob));
|
||||
return file.append("Private-MAC: ").append(HexFormat.of().formatHex(mac)).append('\n').toString();
|
||||
}
|
||||
|
||||
private static void appendLines(StringBuilder file, String header, byte[] blob) {
|
||||
String base64 = Base64.getEncoder().encodeToString(blob);
|
||||
file.append(header).append(": ").append((base64.length() + LINE_LENGTH - 1) / LINE_LENGTH).append('\n');
|
||||
for (int i = 0; i < base64.length(); i += LINE_LENGTH) {
|
||||
file.append(base64, i, Math.min(i + LINE_LENGTH, base64.length())).append('\n');
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] mac(byte[] data) {
|
||||
try {
|
||||
Mac hmac = Mac.getInstance("HmacSHA1");
|
||||
hmac.init(new SecretKeySpec(Digests.sha1(ascii("putty-private-key-file-mac-key")), "HmacSHA1"));
|
||||
return hmac.doFinal(data);
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new IllegalStateException("HMAC-SHA1 is unavailable", e);
|
||||
}
|
||||
}
|
||||
|
||||
/** The key with its larger prime first, the order PuTTY stores, and its CRT values for that order. */
|
||||
private static RSAPrivateCrtKey largerPrimeFirst(RSAPrivateCrtKey key) {
|
||||
if (key.getPrimeP().compareTo(key.getPrimeQ()) > 0) {
|
||||
return key;
|
||||
}
|
||||
BigInteger p = key.getPrimeQ();
|
||||
BigInteger q = key.getPrimeP();
|
||||
BigInteger d = key.getPrivateExponent();
|
||||
try {
|
||||
return (RSAPrivateCrtKey) KeyFactory.getInstance("RSA").generatePrivate(new RSAPrivateCrtKeySpec(
|
||||
key.getModulus(), key.getPublicExponent(), d, p, q, d.mod(p.subtract(BigInteger.ONE)),
|
||||
d.mod(q.subtract(BigInteger.ONE)), q.modInverse(p)));
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new IllegalStateException("Could not reorder the RSA key's primes", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] ed25519PrivateKey(String openSshPem) {
|
||||
try (PemReader reader = new PemReader(new StringReader(openSshPem))) {
|
||||
return ((Ed25519PrivateKeyParameters) OpenSSHPrivateKeyUtil.parsePrivateKeyBlob(
|
||||
reader.readPemObject().getContent())).getEncoded();
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException("Could not read the ED25519 key", e);
|
||||
}
|
||||
}
|
||||
|
||||
/** SSH strings: each field as a four-byte length and then its bytes. */
|
||||
private static byte[] strings(byte[]... fields) {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
for (byte[] field : fields) {
|
||||
out.writeBytes(ByteBuffer.allocate(Integer.BYTES).putInt(field.length).array());
|
||||
out.writeBytes(field);
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
private static byte[] ascii(String text) {
|
||||
return text.getBytes(StandardCharsets.US_ASCII);
|
||||
}
|
||||
}
|
||||
@@ -3419,8 +3419,10 @@ public class Ec2QueryHandler {
|
||||
}
|
||||
|
||||
private Response handleCreateKeyPair(MultivaluedMap<String, String> p, String region) {
|
||||
// AWS answers DryRun before it checks the name or the key type.
|
||||
checkDryRun(p);
|
||||
String keyName = requireKeyName(p);
|
||||
KeyPair kp = service.createKeyPair(region, keyName);
|
||||
KeyPair kp = service.createKeyPair(region, keyName, p.getFirst("KeyType"), p.getFirst("KeyFormat"));
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("CreateKeyPairResponse", AwsNamespaces.EC2)
|
||||
.elem("requestId", UUID.randomUUID().toString())
|
||||
|
||||
@@ -14,6 +14,7 @@ import io.github.hectorvent.floci.core.common.PaginatedResult;
|
||||
import io.github.hectorvent.floci.core.common.RequestContext;
|
||||
import io.github.hectorvent.floci.core.common.RequestScopes;
|
||||
import io.github.hectorvent.floci.core.common.Resettable;
|
||||
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
|
||||
import io.github.hectorvent.floci.core.resource.ExplorerResource;
|
||||
import io.github.hectorvent.floci.core.resource.ResourceProvider;
|
||||
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
|
||||
@@ -7411,20 +7412,33 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
// ─── Key Pairs ─────────────────────────────────────────────────────────────
|
||||
|
||||
public KeyPair createKeyPair(String region, String keyName) {
|
||||
return createKeyPair(region, keyName, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a key pair of {@code keyType}, {@code rsa} when null, and returns its private key in
|
||||
* {@code keyFormat}, {@code pem} when null. A value outside either enum is refused with the message
|
||||
* AWS's request validation gives; Floci checks the values after the name is found present and
|
||||
* valid and before it is found taken.
|
||||
*/
|
||||
public KeyPair createKeyPair(String region, String keyName, String keyType, String keyFormat) {
|
||||
ensureDefaultResources(region);
|
||||
requireKeyName(keyName);
|
||||
String type = keyType != null ? keyType : "rsa";
|
||||
String format = keyFormat != null ? keyFormat : "pem";
|
||||
requireKeyTypeAndFormat(type, format);
|
||||
rejectDuplicateKeyName(region, keyName);
|
||||
String keyPairId = "key-" + randomHex(17);
|
||||
KeyPair kp = new KeyPair();
|
||||
kp.setKeyPairId(keyPairId);
|
||||
kp.setKeyName(keyName);
|
||||
Ec2KeyMaterial.Generated generated = Ec2KeyMaterial.generateRsa();
|
||||
Ec2KeyMaterial.Generated generated = Ec2KeyMaterial.generate(type, format, keyName);
|
||||
kp.setKeyFingerprint(generated.fingerprint());
|
||||
kp.setKeyMaterial(generated.privateKeyPem());
|
||||
// The public half is what RunInstances injects into the guest's authorized_keys.
|
||||
// Without storing it, a key pair created here could never authenticate anything.
|
||||
kp.setPublicKey(generated.openSshPublicKey());
|
||||
kp.setKeyType("rsa");
|
||||
kp.setKeyType(type);
|
||||
kp.setCreateTime(Instant.now());
|
||||
kp.setRegion(region);
|
||||
keyPairs.put(key(region, keyPairId), kp);
|
||||
@@ -7480,26 +7494,27 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
|
||||
/**
|
||||
* The key type DescribeKeyPairs reports. A key pair stored before the type was recorded has it
|
||||
* read from what it holds: rsa when CreateKeyPair made it, since that has only ever generated
|
||||
* RSA keys, and otherwise the type of its imported key, or none when ImportKeyPair would now
|
||||
* refuse that material or reading it fails, which is logged.
|
||||
* read from the public key it holds, whether CreateKeyPair made it or ImportKeyPair took it. A
|
||||
* created key pair saved before created key pairs kept their public key is rsa, the only type
|
||||
* CreateKeyPair made then. Otherwise it has none, when ImportKeyPair would now refuse the
|
||||
* material or reading it fails, which is logged.
|
||||
*/
|
||||
static String keyTypeOf(KeyPair keyPair) {
|
||||
if (keyPair.getKeyType() != null) {
|
||||
return keyPair.getKeyType();
|
||||
}
|
||||
if (keyPair.getKeyMaterial() != null) {
|
||||
return "rsa";
|
||||
}
|
||||
try {
|
||||
Ec2KeyMaterial.Imported imported = Ec2KeyMaterial.readImportedKey(keyPair.getPublicKey());
|
||||
return imported != null ? imported.keyType() : null;
|
||||
Ec2KeyMaterial.Imported key = Ec2KeyMaterial.readImportedKey(keyPair.getPublicKey());
|
||||
if (key != null) {
|
||||
return key.keyType();
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
// The record may hold any text an earlier ImportKeyPair stored. Text the reader cannot
|
||||
// handle leaves the type out instead of failing every description in the region.
|
||||
LOG.warnv(e, "Could not read the key type of stored key pair {0}", keyPair.getKeyPairId());
|
||||
return null;
|
||||
}
|
||||
return keyPair.getKeyMaterial() != null ? "rsa" : null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -7631,6 +7646,22 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|
||||
}
|
||||
}
|
||||
|
||||
/** KeyType and KeyFormat take only the values AWS's model lists; each other value is reported. */
|
||||
private static void requireKeyTypeAndFormat(String keyType, String keyFormat) {
|
||||
List<String> violations = new ArrayList<>();
|
||||
if (!List.of("rsa", "ed25519").contains(keyType)) {
|
||||
violations.add("Value '" + keyType + "' at 'keyType' failed to satisfy constraint: "
|
||||
+ "Member must satisfy enum value set: [rsa, ed25519]");
|
||||
}
|
||||
if (!List.of("ppk", "pem").contains(keyFormat)) {
|
||||
violations.add("Value '" + keyFormat + "' at 'keyFormat' failed to satisfy constraint: "
|
||||
+ "Member must satisfy enum value set: [ppk, pem]");
|
||||
}
|
||||
if (!violations.isEmpty()) {
|
||||
throw SmithyValidationErrors.exception("InvalidParameterValue", violations);
|
||||
}
|
||||
}
|
||||
|
||||
public KeyPair findKeyPair(String region, String keyName) {
|
||||
if (keyName == null) {
|
||||
return null;
|
||||
|
||||
Reference in new issue
Block a user