diff --git a/docs/services/ec2.md b/docs/services/ec2.md index 7692ebcc73..d54e3d412a 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -319,6 +319,7 @@ naming different VPCs find nothing. | StopInstances | Stops running instances and updates their stored lifecycle state. | | RebootInstances | Reboots instances through the local EC2 service model. | | DescribeInstanceStatus | Returns status records for stored instances. | +| GetConsoleOutput | Returns a console log carrying the guest's SSH host keys between the `-----BEGIN SSH HOST KEY KEYS-----` and `-----END SSH HOST KEY KEYS-----` markers cloud-init prints, read from the running instance container. An instance that is not running, or whose container cannot be read, returns an empty log, as a just-launched one does on AWS. An instance in another region is `InvalidInstanceID.NotFound`. `DryRun=true` returns `DryRunOperation` before the instance is looked up, as on AWS. | | DescribeInstanceCreditSpecifications | Returns the CPU credit option of burstable performance instances. A named instance id reports the option the instance acquired at launch, either the explicit `CreditSpecification.CpuCredits` or the family default, `standard` for t2 and `unlimited` for t3, t3a and t4g. An id that is not a burstable performance instance reports `standard`, and only an unknown id is an error. Naming no id returns the instances on the unlimited option, including one that kept `unlimited` after a resize onto a non-burstable type. `Filter.N` supports the modeled `instance-id` and narrows whichever set the request selected. `MaxResults` accepts 5 through 1000 and cannot be combined with instance ids. `DryRun=true` returns `DryRunOperation`. | | DescribeInstanceAttribute | Returns a supported attribute for an instance. `ebsOptimized` reports what `RunInstances` (or its launch template) set; instances launched by CloudFormation, Auto Scaling or Fleet report `false`. | | ModifyInstanceAttribute | Updates supported mutable attributes for an instance. `UserData.Value` (base64) needs the instance stopped, as on AWS, and answers `IncorrectInstanceState` otherwise. | diff --git a/docs/services/index.md b/docs/services/index.md index 7d6cdf96f1..107cdb74fb 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -86,7 +86,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [Data Firehose](firehose.md) | `POST /` + `X-Amz-Target: Firehose_20150804.*` | JSON 1.1 | 12 | | [ECS](ecs.md) | `POST /` + `X-Amz-Target: AmazonEC2ContainerServiceV20141113.*` | JSON 1.1 | 59 | | [EFS](efs.md) | `/2015-02-01/...` | REST JSON | 26 | -| [EC2](ec2.md) | `POST /` with `Action=` param | EC2 Query | 223 | +| [EC2](ec2.md) | `POST /` with `Action=` param | EC2 Query | 224 | | [Lightsail](lightsail.md) | `POST /` + `X-Amz-Target: Lightsail_20161128.*` | JSON 1.1 | 79 local responses; 161 recognized actions | | [ACM](acm.md) | `POST /` + `X-Amz-Target: CertificateManager.*` | JSON 1.1 | 16 | | [ECR](ecr.md) | `POST /` + `X-Amz-Target: AmazonEC2ContainerRegistry_V20150921.*` (control plane) and `/v2/...` (data plane proxied to `registry:2`) | JSON 1.1 + OCI Distribution | 34 | diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java index 255d0b6b03..895b332817 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java @@ -91,6 +91,9 @@ public class Ec2ContainerManager { private static final int LAUNCH_QUEUE_CAPACITY = 64; // ponytail: a fixed cap on concurrent post-start IMDS setups; a start beyond it skips the setup. private static final int METADATA_SETUP_CONCURRENCY = 16; + /** Real host public keys, one line per type, come to well under a kilobyte together. */ + static final int SSH_HOST_KEYS_MAX_BYTES = 16 * 1024; + private static final int SSH_HOST_KEYS_STDERR_BYTES = 1024; private static final long USER_DATA_EXECUTION_TIMEOUT_MINUTES = 30; // Wait for capacity so accepted launches are not dropped, but never run launch work on callers. static final RejectedExecutionHandler BLOCKING_BACKPRESSURE = (runnable, executor) -> { @@ -1975,4 +1978,27 @@ public class Ec2ContainerManager { static Optional preferredMetadataSourceIp(Map networks) { return Ec2MetadataProxy.preferredMetadataSourceIp(networks); } + + /** + * The instance's SSH host public keys, read from its running container. AWS prints these to + * the console log at first boot (cloud-init's "SSH HOST KEY KEYS" block), which is how a + * client verifies the host it connects to. + */ + public String readSshHostKeys(String containerId) { + String[] cmd = {"sh", "-c", "for f in /etc/ssh/ssh_host_*_key.pub; do [ -f \"$f\" ] && cat \"$f\"; done"}; + // The files are the guest's to write, so capture no more than real host keys can take. + UserDataPipeline.BoundedOutput stdout = new UserDataPipeline.BoundedOutput(SSH_HOST_KEYS_MAX_BYTES); + UserDataPipeline.BoundedOutput stderr = new UserDataPipeline.BoundedOutput(SSH_HOST_KEYS_STDERR_BYTES); + ContainerExec.Result result = ContainerExec.run(dockerClient, containerId, cmd, 15, stdout, stderr); + if (result.exitCode() != 0) { + return ""; + } + if (stdout.truncated()) { + LOG.warnv("Ignoring SSH host keys of container {0}: {1} bytes exceed the {2}-byte limit", + containerId, stdout.totalBytes(), SSH_HOST_KEYS_MAX_BYTES); + return ""; + } + return new String(stdout.toByteArray(), StandardCharsets.UTF_8); + } + } diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java index 75248c76f7..48d547e8f8 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java @@ -108,6 +108,7 @@ public class Ec2QueryHandler { case "StartInstances" -> handleStartInstances(params, region); case "StopInstances" -> handleStopInstances(params, region); case "RebootInstances" -> handleRebootInstances(params, region); + case "GetConsoleOutput" -> handleGetConsoleOutput(params, region); case "MonitorInstances" -> handleMonitoring(params, region, "MonitorInstances", true); case "UnmonitorInstances" -> handleMonitoring(params, region, "UnmonitorInstances", false); case "DescribeInstanceStatus" -> handleDescribeInstanceStatus(params, region); @@ -1558,6 +1559,26 @@ public class Ec2QueryHandler { return xmlResponse(buildInstanceStateChangeXml("StopInstancesResponse", changes)); } + private Response handleGetConsoleOutput(MultivaluedMap p, String region) { + // AWS answers a dry run before it looks at the instance, even for an empty or malformed id. + checkDryRun(p); + String instanceId = p.getFirst("InstanceId"); + if (instanceId == null || instanceId.isBlank()) { + throw new AwsException("MissingParameter", "The request must contain the parameter InstanceId", 400); + } + String output = service.getConsoleOutput(region, instanceId); + String encoded = Base64.getEncoder().encodeToString( + output.getBytes(StandardCharsets.UTF_8)); + XmlBuilder xml = new XmlBuilder() + .start("GetConsoleOutputResponse", AwsNamespaces.EC2) + .elem("requestId", UUID.randomUUID().toString()) + .elem("instanceId", instanceId) + .elem("timestamp", Instant.now().toString()) + .elem("output", encoded) + .end("GetConsoleOutputResponse"); + return xmlResponse(xml.build()); + } + private Response handleRebootInstances(MultivaluedMap p, String region) { List ids = getList(p, "InstanceId"); service.rebootInstances(region, ids); diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java index 1893dfefc3..bcd5d63cfc 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java @@ -16007,4 +16007,32 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab } return converted; } + + /** + * GetConsoleOutput: a console log carrying the instance's SSH host keys between the markers + * cloud-init prints, the part clients read from it. An instance that is not running, or whose + * container cannot be read, has an empty log, as a just-launched one does on AWS. + */ + public String getConsoleOutput(String region, String instanceId) { + Instance instance = getRequiredInstance(region, instanceId); + String containerId = instance.getDockerContainerId(); + if (containerId == null || containerId.isBlank() || instance.getState() == null + || !"running".equals(instance.getState().getName())) { + return ""; + } + String keys; + try { + keys = containerManager.readSshHostKeys(containerId); + } catch (RuntimeException e) { + // The container stopped or went away between the state check and the read. + LOG.debugv("No console output for {0}: {1}", instanceId, e.getMessage()); + return ""; + } + if (keys == null || keys.isBlank()) { + return ""; + } + return "Cloud-init finished for " + instanceId + "\n" + + "-----BEGIN SSH HOST KEY KEYS-----\n" + keys.strip() + "\n-----END SSH HOST KEY KEYS-----\n"; + } + } diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.java index a4834a338d..579bd9f746 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.java @@ -28,6 +28,7 @@ import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer; import io.github.hectorvent.floci.core.common.docker.ContainerBuilder; import io.github.hectorvent.floci.core.common.docker.ContainerDetector; +import io.github.hectorvent.floci.core.common.docker.ContainerExecStubs; import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager; import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer; import io.github.hectorvent.floci.core.common.docker.ContainerReachableEndpoint; @@ -1349,6 +1350,30 @@ class Ec2ContainerManagerTest { Duration.ofSeconds(5)); } + @Test + void readSshHostKeysReturnsTheGuestsHostKeys() { + DockerClient docker = mock(DockerClient.class); + String keys = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAII0fBPBUZHaEOBc2mySfmI5btu4mkvFfNRujmF7RH2fj root@guest\n"; + ContainerExecStubs.completeEveryExec(docker, TEST_CONTAINER_ID, 0L, keys, ""); + + Ec2ContainerManager manager = managerWith(mock(ContainerLifecycleManager.class), docker, + mock(Ec2MetadataServer.class)); + + assertEquals(keys, manager.readSshHostKeys(TEST_CONTAINER_ID)); + } + + @Test + void readSshHostKeysIgnoresOutputBeyondWhatHostKeysCanTake() { + DockerClient docker = mock(DockerClient.class); + String planted = "x".repeat(Ec2ContainerManager.SSH_HOST_KEYS_MAX_BYTES + 1); + ContainerExecStubs.completeEveryExec(docker, TEST_CONTAINER_ID, 0L, planted, ""); + + Ec2ContainerManager manager = managerWith(mock(ContainerLifecycleManager.class), docker, + mock(Ec2MetadataServer.class)); + + assertEquals("", manager.readSshHostKeys(TEST_CONTAINER_ID)); + } + private static Ec2ContainerManager managerWithReachability(ContainerNetworkReachability reachability) { return new Ec2ContainerManager( mock(ContainerBuilder.class), diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2GetConsoleOutputIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2GetConsoleOutputIntegrationTest.java new file mode 100644 index 0000000000..3e341b2c78 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2GetConsoleOutputIntegrationTest.java @@ -0,0 +1,189 @@ +package io.github.hectorvent.floci.services.ec2; + +import io.github.hectorvent.floci.services.ec2.model.Instance; +import io.github.hectorvent.floci.services.ec2.model.InstanceState; +import io.github.hectorvent.floci.testing.AwsTestClients; +import io.github.hectorvent.floci.testing.Ec2Requests; +import io.quarkus.test.InjectMock; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.path.xml.XmlPath; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.ec2.Ec2Client; +import software.amazon.awssdk.services.ec2.model.Ec2Exception; +import software.amazon.awssdk.services.ec2.model.GetConsoleOutputResponse; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.List; +import java.util.UUID; + +import static io.github.hectorvent.floci.services.ec2.Ec2KeyPairFixtures.REGION; +import static io.github.hectorvent.floci.services.ec2.Ec2KeyPairFixtures.ec2; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * GetConsoleOutput returns the guest's SSH host keys between the markers cloud-init prints, the part + * clients read from the console log to verify the host they connect to. + * + *

It shares the application of {@link Ec2CapturedImageReclaimIntegrationTest}, which turns EC2's + * mock mode off, with the container manager mocked as there. + */ +@QuarkusTest +@TestProfile(Ec2CapturedImageReclaimIntegrationTest.ContainerBackedEc2.class) +class Ec2GetConsoleOutputIntegrationTest { + + private static final String HOST_KEY = + "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAII0fBPBUZHaEOBc2mySfmI5btu4mkvFfNRujmF7RH2fj root@guest"; + private static final String HOST_KEY_BLOCK = "-----BEGIN SSH HOST KEY KEYS-----\n" + HOST_KEY + + "\n-----END SSH HOST KEY KEYS-----\n"; + + @Inject + Ec2Service service; + + @InjectMock + Ec2ContainerManager containerManager; + + @Test + void consoleOutputCarriesTheGuestsSshHostKeys() { + String containerId = "console-" + UUID.randomUUID(); + Instance instance = storedInstance(containerId, InstanceState.running()); + when(containerManager.readSshHostKeys(containerId)).thenReturn(HOST_KEY + "\n"); + try { + XmlPath response = ec2("GetConsoleOutput").formParam("InstanceId", instance.getInstanceId()) + .when().post("/") + .then().statusCode(200) + .body("GetConsoleOutputResponse.instanceId", equalTo(instance.getInstanceId())) + .extract().xmlPath(); + + String output = decode(response.getString("GetConsoleOutputResponse.output")); + assertTrue(output.contains(HOST_KEY_BLOCK), output); + } finally { + service.terminateInstances(REGION, List.of(instance.getInstanceId())); + } + } + + @Test + void theSdkReadsTheInstanceIdTimestampAndOutput() { + String containerId = "console-" + UUID.randomUUID(); + Instance instance = storedInstance(containerId, InstanceState.running()); + when(containerManager.readSshHostKeys(containerId)).thenReturn(HOST_KEY + "\n"); + try (Ec2Client client = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1)) { + GetConsoleOutputResponse response = client.getConsoleOutput(r -> r.instanceId(instance.getInstanceId())); + + assertEquals(instance.getInstanceId(), response.instanceId()); + assertNotNull(response.timestamp()); + assertTrue(decode(response.output()).contains(HOST_KEY_BLOCK), response.output()); + } finally { + service.terminateInstances(REGION, List.of(instance.getInstanceId())); + } + } + + @Test + void anInstanceWithoutAContainerHasAnEmptyConsoleOutput() { + Instance instance = storedInstance(null, InstanceState.running()); + try { + assertEquals("", consoleOutput(instance)); + } finally { + service.terminateInstances(REGION, List.of(instance.getInstanceId())); + } + } + + @Test + void aStoppedInstanceHasAnEmptyConsoleOutputWithoutTouchingItsContainer() { + Instance instance = storedInstance("console-" + UUID.randomUUID(), InstanceState.stopped()); + try { + assertEquals("", consoleOutput(instance)); + verify(containerManager, never()).readSshHostKeys(anyString()); + } finally { + service.terminateInstances(REGION, List.of(instance.getInstanceId())); + } + } + + @Test + void aContainerThatCannotBeReadGivesAnEmptyConsoleOutput() { + String containerId = "console-" + UUID.randomUUID(); + Instance instance = storedInstance(containerId, InstanceState.running()); + when(containerManager.readSshHostKeys(containerId)).thenThrow(new IllegalStateException("container is not running")); + try { + assertEquals("", consoleOutput(instance)); + } finally { + service.terminateInstances(REGION, List.of(instance.getInstanceId())); + } + } + + @Test + void anInstanceInAnotherRegionIsNotFound() { + Instance instance = storedInstance(null, InstanceState.running()); + try { + Ec2Requests.ec2("GetConsoleOutput", "test", "us-west-2") + .formParam("InstanceId", instance.getInstanceId()) + .when().post("/") + .then().statusCode(400) + .body("Response.Errors.Error.Code", equalTo("InvalidInstanceID.NotFound")); + } finally { + service.terminateInstances(REGION, List.of(instance.getInstanceId())); + } + } + + @ParameterizedTest + @ValueSource(strings = {"", "not-an-instance-id", "i-0123456789abcdef0"}) + void aDryRunIsAnsweredBeforeTheInstanceIsLookedUp(String instanceId) { + try (Ec2Client client = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1)) { + Ec2Exception error = assertThrows(Ec2Exception.class, + () -> client.getConsoleOutput(r -> r.instanceId(instanceId).dryRun(true))); + + assertEquals("DryRunOperation", error.awsErrorDetails().errorCode()); + } + verify(containerManager, never()).readSshHostKeys(anyString()); + } + + @Test + void anUnknownInstanceIsNotFound() { + ec2("GetConsoleOutput").formParam("InstanceId", "i-0123456789abcdef0") + .when().post("/") + .then().statusCode(400) + .body("Response.Errors.Error.Code", equalTo("InvalidInstanceID.NotFound")); + } + + @Test + void aRequestWithoutAnInstanceIdIsRejected() { + ec2("GetConsoleOutput") + .when().post("/") + .then().statusCode(400) + .body("Response.Errors.Error.Code", equalTo("MissingParameter")); + } + + private static String consoleOutput(Instance instance) { + return ec2("GetConsoleOutput").formParam("InstanceId", instance.getInstanceId()) + .when().post("/") + .then().statusCode(200) + .extract().xmlPath().getString("GetConsoleOutputResponse.output"); + } + + private static String decode(String output) { + return new String(Base64.getDecoder().decode(output), StandardCharsets.UTF_8); + } + + private Instance storedInstance(String containerId, InstanceState state) { + Instance instance = new Instance(); + instance.setInstanceId("i-" + UUID.randomUUID().toString().replace("-", "").substring(0, 17)); + instance.setRegion(REGION); + instance.setDockerContainerId(containerId); + instance.setState(state); + service.putInstanceForTest(instance); + return instance; + } +}