mirror of
https://github.com/floci-io/floci.git
synced 2026-12-02 09:47:56 -05:00
feat(ec2-instance-connect): SendSSHPublicKey, verified by the unmodified AWS agent (#7473)
This commit is contained in:
1 parent
0de5566d22
commit
3701d4d041
28 files changed
+1295
-11
No files matched your search
@@ -0,0 +1,34 @@
|
||||
package io.floci.aws.core.common;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.QuarkusTestProfile;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/** EC2 Instance Connect has its own enabled flag; turning it off leaves EC2 on. */
|
||||
@QuarkusTest
|
||||
@TestProfile(InstanceConnectEnablementIntegrationTest.InstanceConnectDisabledProfile.class)
|
||||
class InstanceConnectEnablementIntegrationTest {
|
||||
|
||||
@Inject
|
||||
ServiceRegistry serviceRegistry;
|
||||
|
||||
@Test
|
||||
void ownFlagDisablesOnlyInstanceConnect() {
|
||||
assertFalse(serviceRegistry.isServiceEnabled("ec2-instance-connect"));
|
||||
assertTrue(serviceRegistry.isServiceEnabled("ec2"));
|
||||
}
|
||||
|
||||
public static final class InstanceConnectDisabledProfile implements QuarkusTestProfile {
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
return Map.of("floci.services.ec2instanceconnect.enabled", "false");
|
||||
}
|
||||
}
|
||||
}
|
||||
+48
-1
@@ -2,10 +2,12 @@ package io.floci.aws.core.common;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
|
||||
import io.floci.aws.services.ec2instanceconnect.InstanceConnectKeys;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.floci.aws.testing.PartitionMatrix;
|
||||
import io.floci.aws.testing.PartitionMatrix.PartitionCase;
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.arc.Arc;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.path.json.config.JsonPathConfig;
|
||||
import io.restassured.response.Response;
|
||||
@@ -45,7 +47,7 @@ class PartitionCrossServiceSmokeIntegrationTest {
|
||||
"aps", "autoscaling", "backup", "batch", "bcmdataexports", "bedrock", "bedrockagentcorecontrol", "ce",
|
||||
"cloudfront", "cloudmap", "cloudwatch", "codebuild", "codedeploy", "codepipeline", "cognito",
|
||||
"configservice", "connect", "controlcatalog", "controltower", "datasync", "dlm", "dms", "dsql", "dynamodb", "ec2",
|
||||
"ecr", "ecs", "efs", "eks", "elasticache", "elasticbeanstalk", "elb", "elbv2", "emr", "emrserverless",
|
||||
"ec2instanceconnect", "ecr", "ecs", "efs", "eks", "elasticache", "elasticbeanstalk", "elb", "elbv2", "emr", "emrserverless",
|
||||
"eventbridge", "eventbridgev2", "firehose", "fis", "glue", "guardduty", "iot", "kinesis", "kinesisanalytics", "lambda",
|
||||
"lambdamicrovms", "lambdaweb", "memorydb", "msk", "mwaa", "networkfirewall", "oam", "opensearch", "organizations",
|
||||
"paymentcryptography", "pipes", "quicksight", "ram", "rds", "redshift", "redshiftserverless",
|
||||
@@ -534,6 +536,51 @@ class PartitionCrossServiceSmokeIntegrationTest {
|
||||
PartitionMatrix.assertGlobalArnIn(partitionCase, created.xmlPath().getString("CreateIpamResponse.ipam.ipamArn"));
|
||||
}
|
||||
|
||||
/**
|
||||
* SendSSHPublicKey answers only RequestId and Success; the caller ARN it mints is read back
|
||||
* from the signed active-keys document IMDS would serve the instance, and the signer host from
|
||||
* the name its certificate is issued under.
|
||||
*/
|
||||
@ParameterizedTest
|
||||
@MethodSource(PartitionMatrix.NON_COMMERCIAL_CASES)
|
||||
void instanceConnectCallerArnAndSignerHost(PartitionCase partitionCase) {
|
||||
String region = offered(partitionCase, "ec2-instance-connect");
|
||||
String instanceId = signed(region, "ec2")
|
||||
.formParam("Action", "RunInstances")
|
||||
.formParam("Version", "2016-11-15")
|
||||
.formParam("ImageId", "ami-0123456789abcdef0")
|
||||
.formParam("InstanceType", "t3.micro")
|
||||
.formParam("MinCount", "1")
|
||||
.formParam("MaxCount", "1")
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().xmlPath().getString("RunInstancesResponse.instancesSet.item.instanceId");
|
||||
cleanup.register(() -> signed(region, "ec2")
|
||||
.formParam("Action", "TerminateInstances")
|
||||
.formParam("Version", "2016-11-15")
|
||||
.formParam("InstanceId.1", instanceId)
|
||||
.when().post("/"));
|
||||
// A mock launch settles on the next describe, as it does for any other caller.
|
||||
String state = signed(region, "ec2")
|
||||
.formParam("Action", "DescribeInstances")
|
||||
.formParam("Version", "2016-11-15")
|
||||
.formParam("InstanceId.1", instanceId)
|
||||
.when().post("/").then().statusCode(200).extract().xmlPath()
|
||||
.getString("DescribeInstancesResponse.reservationSet.item.instancesSet.item.instanceState.name");
|
||||
assertEquals("running", state);
|
||||
|
||||
json11(region, "ec2-instance-connect", "AWSEC2InstanceConnectService.SendSSHPublicKey",
|
||||
"{\"InstanceId\":\"" + instanceId + "\",\"InstanceOSUser\":\"admin\",\"SSHPublicKey\":\""
|
||||
+ "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl smoke\"}")
|
||||
.when().post("/").then().statusCode(200);
|
||||
|
||||
String document = Arc.container().instance(InstanceConnectKeys.class).get()
|
||||
.activeKeysDocument(region, instanceId, "admin").orElseThrow();
|
||||
String caller = document.lines().filter(line -> line.startsWith("#Caller="))
|
||||
.findFirst().orElseThrow().substring("#Caller=".length());
|
||||
PartitionMatrix.assertGlobalArnIn(partitionCase, caller);
|
||||
assertRegionalHostIn(partitionCase, InstanceConnectKeys.signerCommonName(region));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource(PartitionMatrix.NON_COMMERCIAL_CASES)
|
||||
void apiGatewayDomainNameArn(PartitionCase partitionCase) {
|
||||
|
||||
@@ -43,6 +43,7 @@ import io.floci.aws.services.ec2.model.InstanceNetworkInterface;
|
||||
import io.floci.aws.services.ec2.model.InstanceState;
|
||||
import io.floci.aws.services.ec2.net.VpcNetworkManager;
|
||||
import io.floci.aws.services.ec2.portforward.Ec2PortForwardManager;
|
||||
import io.floci.aws.services.ec2instanceconnect.InstanceConnectKeys;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
@@ -300,7 +301,7 @@ class Ec2ContainerManagerTest {
|
||||
networks.put(second, new ContainerNetwork().withIpv4Address(sharedFirst ? "10.0.1.10" : "192.0.2.10"));
|
||||
when(settings.getNetworks()).thenReturn(networks);
|
||||
when(command.exec()).thenReturn(response);
|
||||
Ec2MetadataServer server = new Ec2MetadataServer(null, null, null);
|
||||
Ec2MetadataServer server = new Ec2MetadataServer(null, null, null, (InstanceConnectKeys) null);
|
||||
Ec2ContainerManager manager = managerWith(lifecycle, docker, server);
|
||||
Instance guest = instance("i-multinetwork");
|
||||
guest.setDockerContainerId(TEST_CONTAINER_ID);
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
package io.floci.aws.services.ec2;
|
||||
|
||||
import io.floci.aws.services.ec2instanceconnect.InstanceConnectKeys;
|
||||
import io.vertx.core.Context;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* The IMDS paths the unmodified EC2 Instance Connect agent reads, in the shape it reads them:
|
||||
* with a trailing slash, and {@code active-keys} probed with HEAD before it is fetched.
|
||||
*/
|
||||
class Ec2MetadataInstanceConnectTest {
|
||||
|
||||
@Test
|
||||
void servesTheAgentsPathsWithTrailingSlashesAndHead() throws Exception {
|
||||
InstanceConnectKeys keys = mock(InstanceConnectKeys.class);
|
||||
when(keys.activeKeysDocument(anyString(), eq("i-0123456789abcdef0"), anyString())).thenReturn(Optional.empty());
|
||||
when(keys.activeKeysDocument(anyString(), eq("i-0123456789abcdef0"), eq("admin")))
|
||||
.thenReturn(Optional.of("#Timestamp=1\nssh-ed25519 AAAA\nc2ln\n\n"));
|
||||
when(keys.signerCertificateChain(anyString())).thenReturn("CHAIN");
|
||||
Map<String, String> staples = new LinkedHashMap<>();
|
||||
staples.put("AA11", "c3RhcGxlMQ==");
|
||||
staples.put("BB22", "c3RhcGxlMg==");
|
||||
when(keys.ocspStaples(anyString())).thenReturn(staples);
|
||||
|
||||
try (Ec2MetadataTestFixture imds = new Ec2MetadataTestFixture().withInstanceConnect(keys)) {
|
||||
imds.instance().setRegion("us-east-1");
|
||||
imds.start();
|
||||
String token = imds.putToken("60").body();
|
||||
String keysPath = "/latest/meta-data/managed-ssh-keys/";
|
||||
|
||||
assertEquals("i-0123456789abcdef0", imds.get("/latest/meta-data/instance-id/", token).body());
|
||||
assertEquals("amazonaws.com", imds.get("/latest/meta-data/services/domain/", token).body());
|
||||
assertEquals(200, imds.head(keysPath + "active-keys/admin/", token).statusCode());
|
||||
assertEquals(404, imds.head(keysPath + "active-keys/root/", token).statusCode());
|
||||
assertEquals("#Timestamp=1\nssh-ed25519 AAAA\nc2ln\n\n",
|
||||
imds.get(keysPath + "active-keys/admin/", token).body());
|
||||
assertEquals("CHAIN", imds.get(keysPath + "signer-cert/", token).body());
|
||||
assertEquals("AA11\nBB22", imds.get(keysPath + "signer-ocsp/", token).body());
|
||||
assertEquals("c3RhcGxlMg==", imds.get(keysPath + "signer-ocsp/BB22", token).body());
|
||||
assertEquals(404, imds.get(keysPath + "signer-ocsp/CC33", token).statusCode());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void keyGenerationAndSigningRunOffTheEventLoop() throws Exception {
|
||||
AtomicBoolean onEventLoop = new AtomicBoolean();
|
||||
InstanceConnectKeys keys = mock(InstanceConnectKeys.class);
|
||||
when(keys.signerCertificateChain(anyString())).thenAnswer(inv -> {
|
||||
onEventLoop.set(Context.isOnEventLoopThread());
|
||||
return "CHAIN";
|
||||
});
|
||||
try (Ec2MetadataTestFixture imds = new Ec2MetadataTestFixture().withInstanceConnect(keys)) {
|
||||
imds.instance().setRegion("us-east-1");
|
||||
imds.start();
|
||||
String token = imds.putToken("60").body();
|
||||
assertEquals("CHAIN", imds.get("/latest/meta-data/managed-ssh-keys/signer-cert", token).body());
|
||||
assertFalse(onEventLoop.get(), "signing must not run on the Vert.x event loop");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void servicesDomainIsTheInstanceRegionsPartitionDomain() throws Exception {
|
||||
try (Ec2MetadataTestFixture imds = new Ec2MetadataTestFixture()) {
|
||||
imds.instance().setRegion("cn-north-1");
|
||||
imds.start();
|
||||
String token = imds.putToken("60").body();
|
||||
assertEquals("amazonaws.com.cn", imds.get("/latest/meta-data/services/domain", token).body());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void managedSshKeysAreAbsentWithoutInstanceConnect() throws Exception {
|
||||
try (Ec2MetadataTestFixture imds = new Ec2MetadataTestFixture()) {
|
||||
imds.start();
|
||||
String token = imds.putToken("60").body();
|
||||
assertEquals(404, imds.get("/latest/meta-data/managed-ssh-keys/signer-cert/", token).statusCode());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package io.floci.aws.services.ec2;
|
||||
import io.floci.aws.services.ec2.model.Instance;
|
||||
import io.floci.aws.services.ec2.model.Placement;
|
||||
import io.floci.aws.services.ec2.model.Tag;
|
||||
import io.floci.aws.services.ec2instanceconnect.InstanceConnectKeys;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
@@ -15,7 +16,7 @@ class Ec2MetadataServerTest {
|
||||
|
||||
@Test
|
||||
void reconciliationAndTerminationPreserveOtherInstances() {
|
||||
Ec2MetadataServer server = new Ec2MetadataServer(null, null, null);
|
||||
Ec2MetadataServer server = new Ec2MetadataServer(null, null, null, (InstanceConnectKeys) null);
|
||||
Instance first = new Instance();
|
||||
first.setInstanceId("i-first");
|
||||
Instance second = new Instance();
|
||||
@@ -100,7 +101,7 @@ class Ec2MetadataServerTest {
|
||||
|
||||
@Test
|
||||
void staleContainerUnregisterDoesNotRemoveCurrentRegistration() {
|
||||
Ec2MetadataServer server = new Ec2MetadataServer(null, null, null);
|
||||
Ec2MetadataServer server = new Ec2MetadataServer(null, null, null, (InstanceConnectKeys) null);
|
||||
Instance oldInstance = new Instance();
|
||||
oldInstance.setInstanceId("i-old");
|
||||
Instance currentInstance = new Instance();
|
||||
|
||||
@@ -2,6 +2,7 @@ package io.floci.aws.services.ec2;
|
||||
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.services.ec2.model.Instance;
|
||||
import io.floci.aws.services.ec2instanceconnect.InstanceConnectKeys;
|
||||
import io.floci.aws.services.iam.IamService;
|
||||
import io.floci.aws.testing.MutableClock;
|
||||
import io.floci.aws.testutil.FreePorts;
|
||||
@@ -34,6 +35,7 @@ final class Ec2MetadataTestFixture implements AutoCloseable {
|
||||
private final Instance instance = instance("i-0123456789abcdef0");
|
||||
private Vertx vertx;
|
||||
private Ec2MetadataServer server;
|
||||
private InstanceConnectKeys instanceConnect;
|
||||
private String endpoint;
|
||||
|
||||
void start() throws Exception {
|
||||
@@ -53,7 +55,7 @@ final class Ec2MetadataTestFixture implements AutoCloseable {
|
||||
int port = FreePorts.anyInterfacePort();
|
||||
when(config.services().ec2().imdsPort()).thenReturn(port);
|
||||
vertx = Vertx.vertx();
|
||||
server = new Ec2MetadataServer(vertx, config, iam, serverClock);
|
||||
server = new Ec2MetadataServer(vertx, config, iam, serverClock, instanceConnect);
|
||||
server.start().get(10, TimeUnit.SECONDS);
|
||||
endpoint = "http://127.0.0.1:" + port;
|
||||
if (registeredInstance != null) {
|
||||
@@ -76,6 +78,18 @@ final class Ec2MetadataTestFixture implements AutoCloseable {
|
||||
}
|
||||
}
|
||||
|
||||
/** Serves EC2 Instance Connect from {@code keys}; call before {@link #start()}. */
|
||||
Ec2MetadataTestFixture withInstanceConnect(InstanceConnectKeys keys) {
|
||||
this.instanceConnect = keys;
|
||||
return this;
|
||||
}
|
||||
|
||||
HttpResponse<String> head(String path, String token) throws Exception {
|
||||
return client.send(HttpRequest.newBuilder(URI.create(endpoint + path)).timeout(Duration.ofSeconds(5))
|
||||
.header(TOKEN_HEADER, token).method("HEAD", HttpRequest.BodyPublishers.noBody()).build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
}
|
||||
|
||||
MutableClock clock() {
|
||||
return clock;
|
||||
}
|
||||
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
package io.floci.aws.services.ec2instanceconnect;
|
||||
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.floci.aws.testing.Ec2Requests.ec2;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.emptyString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
|
||||
@QuarkusTest
|
||||
class InstanceConnectIntegrationTest {
|
||||
|
||||
private static final String JSON_1_1 = "application/x-amz-json-1.1";
|
||||
private static final String ED25519 =
|
||||
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl user@host";
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
private static Response send(String instanceId, String key) {
|
||||
return given()
|
||||
.header("X-Amz-Target", "AWSEC2InstanceConnectService.SendSSHPublicKey")
|
||||
.contentType(JSON_1_1)
|
||||
.body("{\"InstanceId\":\"" + instanceId + "\",\"InstanceOSUser\":\"ec2-user\",\"SSHPublicKey\":\""
|
||||
+ key + "\"}")
|
||||
.post("/");
|
||||
}
|
||||
|
||||
@Test
|
||||
void sendsAKeyToARunningInstanceAndRejectsWhatAwsRejects() {
|
||||
String instanceId = ec2("RunInstances", "000000000000", "us-east-1")
|
||||
.formParam("ImageId", "ami-0abcdef1234567890")
|
||||
.formParam("InstanceType", "t3.micro")
|
||||
.formParam("MinCount", "1").formParam("MaxCount", "1")
|
||||
.post("/").then().statusCode(200)
|
||||
.extract().path("RunInstancesResponse.instancesSet.item.instanceId");
|
||||
try {
|
||||
// Mock mode settles a launch on the first DescribeInstances; the key needs a running instance.
|
||||
ec2("DescribeInstances", "000000000000", "us-east-1").formParam("InstanceId.1", instanceId)
|
||||
.post("/").then().statusCode(200)
|
||||
.body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.instanceState.name",
|
||||
equalTo("running"));
|
||||
send(instanceId, ED25519).then().statusCode(200)
|
||||
.body("Success", equalTo(true))
|
||||
.body("RequestId", not(emptyString()));
|
||||
send(instanceId, "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5 " + "c".repeat(80)).then().statusCode(400)
|
||||
.body("__type", equalTo("InvalidArgsException"));
|
||||
} finally {
|
||||
ec2("TerminateInstances", "000000000000", "us-east-1").formParam("InstanceId.1", instanceId)
|
||||
.post("/").then().statusCode(200);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownInstanceIsAModeledError() {
|
||||
send("i-0000000000000000f", ED25519).then().statusCode(400)
|
||||
.body("__type", equalTo("EC2InstanceNotFoundException"));
|
||||
}
|
||||
}
|
||||
+189
@@ -0,0 +1,189 @@
|
||||
package io.floci.aws.services.ec2instanceconnect;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.services.ec2.Ec2Service;
|
||||
import io.floci.aws.services.ec2.model.Instance;
|
||||
import io.floci.aws.services.ec2.model.InstanceState;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.Base64;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class InstanceConnectJsonHandlerTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String INSTANCE = "i-0123456789abcdef0";
|
||||
private static final Instant NOW = Instant.parse("2026-10-16T12:00:00Z");
|
||||
private static final String ED25519 =
|
||||
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl user@host";
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private Ec2Service ec2;
|
||||
private InstanceConnectKeys keys;
|
||||
private InstanceConnectJsonHandler handler;
|
||||
private Instance instance;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
ec2 = mock(Ec2Service.class);
|
||||
keys = mock(InstanceConnectKeys.class);
|
||||
handler = handlerIn("us-east-1");
|
||||
instance = new Instance();
|
||||
instance.setInstanceId(INSTANCE);
|
||||
instance.setState(InstanceState.running());
|
||||
when(ec2.getInstance(REGION, INSTANCE)).thenReturn(Optional.of(instance));
|
||||
}
|
||||
|
||||
@Test
|
||||
void storesTheKeyForSixtySecondsAndReportsSuccess() {
|
||||
Response response = handler.handle("SendSSHPublicKey", request(INSTANCE, "admin", ED25519), REGION);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals(true, ((ObjectNode) response.getEntity()).get("Success").asBoolean());
|
||||
ArgumentCaptor<InstanceConnectKeys.ActiveKey> stored = ArgumentCaptor.forClass(InstanceConnectKeys.ActiveKey.class);
|
||||
verify(keys).add(stored.capture());
|
||||
assertEquals("admin", stored.getValue().osUser());
|
||||
assertEquals(NOW.plusSeconds(60), stored.getValue().expiresAt());
|
||||
assertEquals(((ObjectNode) response.getEntity()).get("RequestId").asText(), stored.getValue().requestId());
|
||||
assertEquals("arn:aws:iam::000000000000:root", stored.getValue().caller());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theCallerArnIsInTheDeploymentsPartition() {
|
||||
handlerIn("us-gov-west-1").handle("SendSSHPublicKey", request(INSTANCE, "admin", ED25519), REGION);
|
||||
|
||||
ArgumentCaptor<InstanceConnectKeys.ActiveKey> stored = ArgumentCaptor.forClass(InstanceConnectKeys.ActiveKey.class);
|
||||
verify(keys).add(stored.capture());
|
||||
assertEquals("arn:aws-us-gov:iam::000000000000:root", stored.getValue().caller());
|
||||
}
|
||||
|
||||
private InstanceConnectJsonHandler handlerIn(String defaultRegion) {
|
||||
return new InstanceConnectJsonHandler(ec2, keys, new RegionResolver(defaultRegion, "000000000000"), mapper,
|
||||
Clock.fixed(NOW, ZoneOffset.UTC));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsWhatTheServiceModelAndAwsReject() {
|
||||
Map<ObjectNode, String> cases = new LinkedHashMap<>();
|
||||
cases.put(request("instance-1", "admin", ED25519), "InvalidArgsException");
|
||||
cases.put(request(INSTANCE, "bad user", ED25519), "InvalidArgsException");
|
||||
cases.put(request(INSTANCE, "admin", "ssh-ed25519 AAAA"), "InvalidArgsException");
|
||||
cases.put(request(INSTANCE, "admin", "ssh-dss " + "A".repeat(100)), "InvalidArgsException");
|
||||
cases.put(request(INSTANCE, "admin", rsaKey(1024)), "InvalidArgsException");
|
||||
// Right type, no key material: SSH could not use these, so they must not report Success.
|
||||
cases.put(request(INSTANCE, "admin", "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5 " + "c".repeat(80)), "InvalidArgsException");
|
||||
cases.put(request(INSTANCE, "admin", sshKey("ssh-ed25519", new byte[31])), "InvalidArgsException");
|
||||
cases.put(request(INSTANCE, "admin", ecdsaKey("nistp256", "nistp384", 65, (byte) 4)), "InvalidArgsException");
|
||||
cases.put(request(INSTANCE, "admin", ecdsaKey("nistp256", "nistp256", 64, (byte) 4)), "InvalidArgsException");
|
||||
cases.put(request(INSTANCE, "admin", ecdsaKey("nistp256", "nistp256", 65, (byte) 2)), "InvalidArgsException");
|
||||
// An ssh-rsa blob with an empty exponent and a zero modulus, and a type label that disagrees with the blob.
|
||||
cases.put(request(INSTANCE, "admin", "ssh-rsa " + blob("ssh-rsa", new byte[0], new byte[256]) + " test"), "InvalidArgsException");
|
||||
cases.put(request(INSTANCE, "admin", "ssh-rsa " + blob("ssh-ed25519", new byte[32]) + " test"), "InvalidArgsException");
|
||||
// RFC 4251 s5: a 2048-bit modulus with its top bit set and no leading 0x00 is a negative mpint.
|
||||
byte[] unsignedModulus = new byte[256];
|
||||
unsignedModulus[0] = (byte) 0x80;
|
||||
cases.put(request(INSTANCE, "admin", "ssh-rsa " + blob("ssh-rsa", new byte[] {1, 0, 1}, unsignedModulus) + " test"), "InvalidArgsException");
|
||||
cases.put(request(INSTANCE, "admin", ED25519 + "\n#Timestamp=9999999999\n" + ED25519), "InvalidArgsException");
|
||||
cases.put(request(INSTANCE, "admin", ED25519.replace("user@host", "us\u0007er@host")), "InvalidArgsException");
|
||||
cases.put(request("i-0000000000000000f", "admin", ED25519), "EC2InstanceNotFoundException");
|
||||
cases.forEach((request, code) -> assertEquals(code, assertThrows(AwsException.class,
|
||||
() -> handler.handle("SendSSHPublicKey", request, REGION)).getErrorCode(), request.toString()));
|
||||
|
||||
instance.setState(InstanceState.stopped());
|
||||
assertEquals("EC2InstanceStateInvalidException", assertThrows(AwsException.class,
|
||||
() -> handler.handle("SendSSHPublicKey", request(INSTANCE, "admin", ED25519), REGION)).getErrorCode());
|
||||
verify(keys, never()).add(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void serialConsoleIsUnsupportedOnceTheInstanceIsFound() {
|
||||
ObjectNode request = request(INSTANCE, "admin", ED25519);
|
||||
assertEquals("SerialConsoleSessionUnsupportedException", assertThrows(AwsException.class,
|
||||
() -> handler.handle("SendSerialConsoleSSHPublicKey", request, REGION)).getErrorCode());
|
||||
ObjectNode missing = request("i-0000000000000000f", "admin", ED25519);
|
||||
assertEquals("EC2InstanceNotFoundException", assertThrows(AwsException.class,
|
||||
() -> handler.handle("SendSerialConsoleSSHPublicKey", missing, REGION)).getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void acceptsAnRsaKeyOf2048Bits() {
|
||||
handler.handle("SendSSHPublicKey", request(INSTANCE, "admin", rsaKey(2048)), REGION);
|
||||
verify(keys).add(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void acceptsWellFormedEd25519AndEcdsaKeys() {
|
||||
// ECDSA lines are real ssh-keygen -t ecdsa output (throwaway keys, public half only).
|
||||
handler.handle("SendSSHPublicKey", request(INSTANCE, "admin", sshKey("ssh-ed25519", new byte[32])), REGION);
|
||||
handler.handle("SendSSHPublicKey", request(INSTANCE, "admin", "ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBKhKXIBq6uSFm4w/wDQuFN9HzZFxgqLbSpaTJB+J6aAHWXBU7rpF1xa7s4dpFzLTSb+xn8JbKWbLozKoeIWV8hw= test"), REGION);
|
||||
handler.handle("SendSSHPublicKey", request(INSTANCE, "admin", "ecdsa-sha2-nistp384 AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBJFY0hkoTsJID0TIS1BgpJVWTDguQ7sTojV4dfGqMEKjMSAoOnXUdGV1Y+AIhF4rZE9IKsHsjtxg4JYesYz7FR+9CTxHjog7BGzYmVcsVSnRL3t68fT7S3cXhoVkV/3WZA== test"), REGION);
|
||||
handler.handle("SendSSHPublicKey", request(INSTANCE, "admin", "ecdsa-sha2-nistp521 AAAAE2VjZHNhLXNoYTItbmlzdHA1MjEAAAAIbmlzdHA1MjEAAACFBABCp6D79VfVN1Td7nP/lhUWST6qIkN28rgBp1FhyKO2UCTwxObXTOEL7WvfyQ+/J60K21J1ovjtlcC61YhWx0F7eAC/glgVeIBd0leLmmv3YGJkmE7POLgg4nfVXNLJayW3Q8rgyNAROCIC++3Avdn9GZIPrrFnyo1M0aNeW03/dLE2Xg== test"), REGION);
|
||||
verify(keys, times(4)).add(any());
|
||||
}
|
||||
|
||||
/** An ssh-ed25519 line carrying {@code material} as its key. */
|
||||
private static String sshKey(String type, byte[] material) {
|
||||
return type + " " + blob(type, material) + " test";
|
||||
}
|
||||
|
||||
private static String ecdsaKey(String typeCurve, String blobCurve, int pointLength, byte first) {
|
||||
byte[] point = new byte[pointLength];
|
||||
point[0] = first;
|
||||
return "ecdsa-sha2-" + typeCurve + " " + blob("ecdsa-sha2-" + typeCurve, blobCurve.getBytes(StandardCharsets.US_ASCII), point)
|
||||
+ " test";
|
||||
}
|
||||
|
||||
private static String blob(String type, byte[]... fields) {
|
||||
byte[] t = type.getBytes(StandardCharsets.US_ASCII);
|
||||
int size = 4 + t.length;
|
||||
for (byte[] f : fields) {
|
||||
size += 4 + f.length;
|
||||
}
|
||||
ByteBuffer b = ByteBuffer.allocate(size).putInt(t.length).put(t);
|
||||
for (byte[] f : fields) {
|
||||
b.putInt(f.length).put(f);
|
||||
}
|
||||
return Base64.getEncoder().encodeToString(b.array());
|
||||
}
|
||||
|
||||
private ObjectNode request(String instanceId, String user, String key) {
|
||||
ObjectNode node = mapper.createObjectNode();
|
||||
node.put("InstanceId", instanceId);
|
||||
node.put("InstanceOSUser", user);
|
||||
node.put("SSHPublicKey", key);
|
||||
return node;
|
||||
}
|
||||
|
||||
/** An ssh-rsa line whose modulus has exactly {@code bits} bits; only its size is ever checked. */
|
||||
private static String rsaKey(int bits) {
|
||||
byte[] type = "ssh-rsa".getBytes(StandardCharsets.US_ASCII);
|
||||
byte[] exponent = BigInteger.valueOf(65537).toByteArray();
|
||||
byte[] modulus = BigInteger.ONE.shiftLeft(bits - 1).toByteArray();
|
||||
ByteBuffer blob = ByteBuffer.allocate(12 + type.length + exponent.length + modulus.length);
|
||||
blob.putInt(type.length).put(type).putInt(exponent.length).put(exponent).putInt(modulus.length).put(modulus);
|
||||
return "ssh-rsa " + Base64.getEncoder().encodeToString(blob.array()) + " test";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
package io.floci.aws.services.ec2instanceconnect;
|
||||
|
||||
import io.floci.aws.config.FlociCertificateAuthority;
|
||||
import io.floci.aws.services.acm.CertificateGenerator;
|
||||
import io.floci.aws.testing.ManualClock;
|
||||
import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder;
|
||||
import org.bouncycastle.cert.ocsp.BasicOCSPResp;
|
||||
import org.bouncycastle.cert.ocsp.CertificateID;
|
||||
import org.bouncycastle.cert.ocsp.OCSPResp;
|
||||
import org.bouncycastle.cert.ocsp.SingleResp;
|
||||
import org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder;
|
||||
import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
import java.security.Signature;
|
||||
import java.security.cert.CertificateFactory;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.security.spec.MGF1ParameterSpec;
|
||||
import java.security.spec.PSSParameterSpec;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class InstanceConnectKeysTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final Instant NOW = Instant.parse("2026-10-16T12:00:00Z");
|
||||
private static final String KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl test";
|
||||
|
||||
@TempDir
|
||||
Path tlsDir;
|
||||
|
||||
private FlociCertificateAuthority root;
|
||||
private ManualClock clock;
|
||||
private InstanceConnectKeys keys;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
root = FlociCertificateAuthority.loadOrCreate(tlsDir);
|
||||
clock = new ManualClock(NOW);
|
||||
keys = new InstanceConnectKeys(() -> root, new CertificateGenerator(), clock);
|
||||
}
|
||||
|
||||
@Test
|
||||
void chainIsSignerThenIntermediateThenRootWithTheAgentsExpectedSignerName() throws Exception {
|
||||
List<X509Certificate> chain = parseChain(keys.signerCertificateChain(REGION));
|
||||
|
||||
assertEquals(3, chain.size());
|
||||
assertEquals("CN=managed-ssh-signer.us-east-1.amazonaws.com", chain.get(0).getSubjectX500Principal().getName());
|
||||
assertEquals("CN=" + InstanceConnectKeys.INTERMEDIATE_CN, chain.get(1).getSubjectX500Principal().getName());
|
||||
assertEquals(root.certificate(), chain.get(2));
|
||||
chain.get(0).verify(chain.get(1).getPublicKey());
|
||||
chain.get(1).verify(root.certificate().getPublicKey());
|
||||
assertTrue(chain.get(1).getBasicConstraints() >= 0, "the intermediate is a CA");
|
||||
assertEquals(-1, chain.get(0).getBasicConstraints(), "the signer is not");
|
||||
assertEquals("Floci_Local_CA", keys.trustAnchorFileStem());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSignerNameUsesTheRegionsPartitionDomain() throws Exception {
|
||||
assertEquals("CN=managed-ssh-signer.cn-north-1.amazonaws.com.cn",
|
||||
parseChain(keys.signerCertificateChain("cn-north-1")).get(0).getSubjectX500Principal().getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void eachNonRootCertificateHasAGoodStapleSignedByItsIssuer() throws Exception {
|
||||
List<X509Certificate> chain = parseChain(keys.signerCertificateChain(REGION));
|
||||
Map<String, String> staples = keys.ocspStaples(REGION);
|
||||
|
||||
assertEquals(2, staples.size());
|
||||
for (int i = 0; i < 2; i++) {
|
||||
X509Certificate cert = chain.get(i);
|
||||
X509Certificate issuer = chain.get(i + 1);
|
||||
String staple = staples.get(InstanceConnectKeys.sha1Fingerprint(cert));
|
||||
BasicOCSPResp basic = (BasicOCSPResp) new OCSPResp(Base64.getDecoder().decode(staple)).getResponseObject();
|
||||
assertTrue(basic.isSignatureValid(new JcaContentVerifierProviderBuilder().build(issuer.getPublicKey())));
|
||||
SingleResp single = basic.getResponses()[0];
|
||||
assertNull(single.getCertStatus(), "null is OCSP 'good'");
|
||||
CertificateID expected = new CertificateID(new JcaDigestCalculatorProviderBuilder().build()
|
||||
.get(CertificateID.HASH_SHA1), new JcaX509CertificateHolder(issuer), cert.getSerialNumber());
|
||||
assertEquals(expected, single.getCertID());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void activeKeysAreSignedWithRsaPssOverTheHeaderAndKeyLines() throws Exception {
|
||||
keys.add(new InstanceConnectKeys.ActiveKey("i-0123456789abcdef0", "admin", KEY,
|
||||
NOW.plus(InstanceConnectKeys.KEY_LIFETIME), "arn:aws:iam::000000000000:root", "req-1"));
|
||||
|
||||
String document = keys.activeKeysDocument(REGION, "i-0123456789abcdef0", "admin").orElseThrow();
|
||||
String[] lines = document.split("\n", -1);
|
||||
assertEquals("#Timestamp=" + NOW.plusSeconds(60).getEpochSecond(), lines[0]);
|
||||
assertEquals("#Instance=i-0123456789abcdef0", lines[1]);
|
||||
assertEquals(KEY, lines[4]);
|
||||
assertEquals("", lines[6], "a blank line ends each entry");
|
||||
|
||||
String signed = String.join("\n", List.of(lines).subList(0, 5)) + "\n";
|
||||
X509Certificate signer = parseChain(keys.signerCertificateChain(REGION)).getFirst();
|
||||
Signature verifier = Signature.getInstance("RSASSA-PSS");
|
||||
verifier.setParameter(new PSSParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, 32, 1));
|
||||
verifier.initVerify(signer.getPublicKey());
|
||||
verifier.update(signed.getBytes(StandardCharsets.UTF_8));
|
||||
assertTrue(verifier.verify(Base64.getDecoder().decode(lines[5])));
|
||||
}
|
||||
|
||||
@Test
|
||||
void keysAreScopedToTheirUserAndExpireAfterSixtySeconds() {
|
||||
keys.add(new InstanceConnectKeys.ActiveKey("i-0123456789abcdef0", "admin", KEY,
|
||||
NOW.plus(InstanceConnectKeys.KEY_LIFETIME), "caller", "req-1"));
|
||||
|
||||
assertTrue(keys.activeKeysDocument(REGION, "i-0123456789abcdef0", "root").isEmpty());
|
||||
assertTrue(keys.activeKeysDocument(REGION, "i-0000000000000000f", "admin").isEmpty());
|
||||
clock.advance(Duration.ofSeconds(60));
|
||||
assertTrue(keys.activeKeysDocument(REGION, "i-0123456789abcdef0", "admin").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void expiredKeysAreDroppedWhenTheNextKeyArrives() {
|
||||
keys.add(new InstanceConnectKeys.ActiveKey("i-0123456789abcdef0", "admin", KEY,
|
||||
NOW.plus(InstanceConnectKeys.KEY_LIFETIME), "caller", "req-1"));
|
||||
clock.advance(Duration.ofSeconds(61));
|
||||
keys.add(new InstanceConnectKeys.ActiveKey("i-0000000000000000f", "admin", KEY,
|
||||
clock.instant().plus(InstanceConnectKeys.KEY_LIFETIME), "caller", "req-2"));
|
||||
|
||||
assertEquals(1, keys.trackedInstanceCount(), "the first instance's expired key is not kept");
|
||||
}
|
||||
|
||||
private static List<X509Certificate> parseChain(String pem) throws Exception {
|
||||
CertificateFactory factory = CertificateFactory.getInstance("X.509");
|
||||
List<X509Certificate> chain = new ArrayList<>();
|
||||
factory.generateCertificates(new ByteArrayInputStream(pem.getBytes(StandardCharsets.US_ASCII)))
|
||||
.forEach(cert -> chain.add((X509Certificate) cert));
|
||||
return chain;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user