fix(ec2): start sshd even when run-instances omits a key pair (#2245)

* fix(ec2): start sshd even when run-instances omits a key pair

Reported in #2184: run-instances without --key-name left every
container with no SSH daemon listening at all, "connection refused"
regardless of image (alpine, Amazon Linux 2023, Ubuntu all affected).

The cause: startSshd() only ran inside the same conditional as
injectSshKey(), so no key pair meant sshd never started. Real AWS AMIs
run sshd as part of normal boot regardless of whether a key pair is
attached - the daemon is always there, it just has nothing to
authenticate an unattached client with. Floci's behavior diverged by
not running the daemon at all in that case, rather than running it and
correctly having no way in.

Splits the two: injectSshKey still only runs when a key was actually
provided (nothing to inject otherwise), but startSshd now always runs.
It's fully self-contained already (installs openssh-server if absent,
generates host keys, starts the daemon) and never depended on anything
injectSshKey sets up, so making it unconditional needed no other
changes.

Verified: new test launches an instance with no public key and asserts
sshd still starts (and confirms nothing gets written to
authorized_keys, since there's no key to inject). Confirmed it fails
with the fix reverted (no /usr/sbin/sshd invocation happens without a
key) and passes with it restored. Full ec2 package regression is green
(268 tests) - including the several existing tests that already
launched with no key pair and needed no changes to keep passing.

* fix(ec2): stop silently claiming sshd started when it never actually did

Follow-up on a comment from duytanisme on #2245: sshd not starting even
when an SSH key IS provided, requiring a manual exec-in or a custom
user-data script to work around it.

Root cause: startSshd() ran every step through execInContainer(),
which discards the exec's exit code entirely and only throws if the
Docker API call itself fails. The install step's shell script is an
if/elif chain with no matching branch, or whose install command itself
failed (no network yet, apt lock held, etc.) - and a bash if/elif with
no matching branch and no else clause exits 0 by convention. So a
container without a package manager, or one where the install call
failed for any reason, still reported success, ssh-keygen and sshd
then both ran anyway against a daemon that was never installed, and
"Started sshd in EC2 instance" got logged regardless.

Switches every step to execInContainerForResult and checks its exit
code explicitly, following the exact pattern already used by
configureLinkLocalMetadataEndpoint for the same class of problem:
bail out and log a specific warning with the actual command output at
whichever step actually failed, instead of silently proceeding.

Also adds an explicit "command -v sshd" as the last statement of the
install script, so its own exit code is the real source of truth for
whether sshd is actually available afterward, and switches the start
command from a hardcoded /usr/sbin/sshd to a bare "sshd" resolved via
PATH (matching how ssh-keygen is already invoked two lines above),
since not every image installs it to that exact path.

Verified: new test forces the install probe to fail and asserts
ssh-keygen and the start command are never even attempted. Confirmed
it fails (proceeds anyway) with the exit-code check disabled and
passes with it restored. Updated the existing no-key-pair test for the
new bare "sshd" command. Full ec2 package regression is green (269
tests).
This commit is contained in:
Olamide Kosile authored and GitHub committed 2026-08-13 18:58:55 -04:00
1 parent a0adea9073
commit da5ff910b4
2 files changed
+132 -8

No files matched your search

@@ -217,11 +217,16 @@ public class Ec2ContainerManager {
portForwardManager.reconcile(instance, appPorts);
}
// Inject SSH public key
// Inject SSH public key, if one was provided
if (publicKey != null && !publicKey.isBlank()) {
injectSshKey(containerId, publicKey);
startSshd(containerId, instanceId);
}
// sshd runs on every instance regardless of whether a key pair was supplied,
// matching real AWS AMIs (which start it as part of normal boot, independent of
// key-pair association) - starting it only when a key was present meant
// run-instances without --key-name produced a "connection refused" instead of AWS's
// actual behavior: a running daemon with simply nothing to authenticate against.
startSshd(containerId, instanceId);
// Execute UserData
String userData = instance.getUserData();
@@ -454,18 +459,40 @@ public class Ec2ContainerManager {
private void startSshd(String containerId, String instanceId) {
try {
// Install openssh-server if absent
execInContainer(containerId, new String[]{"sh", "-c",
// Install openssh-server if absent. The trailing "command -v sshd" makes the script's
// own exit code the source of truth for whether sshd is actually available afterward -
// without it, a shell if/elif chain with no matching branch (no dnf/apt-get/apk found) or
// whose install command itself failed (e.g. no network yet, apt lock held) still exits 0
// by bash convention, so every later step here would silently no-op against a daemon that
// was never installed while still logging success.
ContainerExecResult install = execInContainerForResult(containerId, new String[]{"sh", "-c",
"if ! command -v sshd >/dev/null 2>&1; then" +
" if command -v dnf >/dev/null 2>&1; then dnf install -y openssh-server >/dev/null 2>&1;" +
" elif command -v apt-get >/dev/null 2>&1; then DEBIAN_FRONTEND=noninteractive apt-get install -y openssh-server >/dev/null 2>&1;" +
" elif command -v apk >/dev/null 2>&1; then apk add --no-cache openssh >/dev/null 2>&1;" +
" fi;" +
"fi"}, 120);
"fi;" +
"command -v sshd >/dev/null 2>&1"}, 120);
if (install.exitCode() != 0) {
LOG.warnv("Could not install openssh-server for EC2 instance {0}: {1}",
instanceId, install.summary());
return;
}
// Generate host keys
execInContainer(containerId, new String[]{"ssh-keygen", "-A"}, 10);
// Start sshd without -D so it daemonizes itself and survives this exec session
execInContainer(containerId, new String[]{"/usr/sbin/sshd"}, 5);
ContainerExecResult keygen = execInContainerForResult(containerId, new String[]{"ssh-keygen", "-A"}, 10);
if (keygen.exitCode() != 0) {
LOG.warnv("Could not generate SSH host keys for EC2 instance {0}: {1}",
instanceId, keygen.summary());
return;
}
// Start sshd without -D so it daemonizes itself and survives this exec session. Resolved
// via PATH (like ssh-keygen above) rather than hardcoded to /usr/sbin/sshd, since not
// every image installs it to that exact path.
ContainerExecResult start = execInContainerForResult(containerId, new String[]{"sshd"}, 5);
if (start.exitCode() != 0) {
LOG.warnv("Could not start sshd for EC2 instance {0}: {1}", instanceId, start.summary());
return;
}
LOG.infov("Started sshd in EC2 instance {0}", instanceId);
} catch (Exception e) {
LOG.warnv("Could not start sshd in EC2 instance {0}: {1}", instanceId, e.getMessage());
@@ -370,6 +370,103 @@ class Ec2ContainerManagerTest {
awaitUntil(() -> "running".equals(instance.getState().getName()), Duration.ofSeconds(2));
}
@Test
void launchWithoutKeyPairStillStartsSshd() throws Exception {
// Regression for #2184: sshd previously only started when a key pair was supplied, so
// run-instances without --key-name left no daemon listening at all ("connection refused")
// instead of matching real AWS AMIs, which run sshd as part of normal boot regardless of
// whether a key pair is attached to the instance.
LaunchHarness harness = launchHarness();
InspectContainerCmd inspect = mock(InspectContainerCmd.class);
InspectContainerResponse withIp = inspectResponse("172.18.0.20");
when(harness.dockerClient.inspectContainerCmd(TEST_CONTAINER_ID)).thenReturn(inspect);
when(inspect.exec()).thenReturn(withIp);
harness.stubSuccessfulExecs(new CountDownLatch(0), new CountDownLatch(0));
Instance instance = instance("i-nokeypair");
harness.manager.launch(instance, "ubuntu:24.04", null, "us-west-2");
awaitUntil(() -> "running".equals(instance.getState().getName()), Duration.ofSeconds(2));
ExecCreateCmd execCreate = harness.dockerClient.execCreateCmd(TEST_CONTAINER_ID);
verify(execCreate, timeout(2000)).withCmd(eq(new String[]{"sshd"}));
// No key pair was supplied, so nothing should have been written to authorized_keys.
verify(harness.dockerClient, never()).copyArchiveToContainerCmd(TEST_CONTAINER_ID);
}
private static final String[] SSHD_INSTALL_PROBE_CMD = {"sh", "-c",
"if ! command -v sshd >/dev/null 2>&1; then"
+ " if command -v dnf >/dev/null 2>&1; then dnf install -y openssh-server >/dev/null 2>&1;"
+ " elif command -v apt-get >/dev/null 2>&1; then DEBIAN_FRONTEND=noninteractive apt-get install -y openssh-server >/dev/null 2>&1;"
+ " elif command -v apk >/dev/null 2>&1; then apk add --no-cache openssh >/dev/null 2>&1;"
+ " fi;"
+ "fi;"
+ "command -v sshd >/dev/null 2>&1"};
@Test
void launchWhenSshdInstallFails_doesNotAttemptKeygenOrStart() throws Exception {
// Regression reported as a follow-up on #2245 (duytanisme): sshd not starting even when a
// key pair IS provided. Root cause: execInContainer() discards exit codes entirely, so a
// shell if/elif chain with no matching package manager - or whose install command itself
// failed (no network yet, apt lock held, etc.) - still exits 0 by bash convention with no
// final check, meaning startSshd() proceeded to ssh-keygen and sshd regardless and still
// logged success. This forces the install probe to report failure and asserts the later
// steps are never even attempted, rather than running against a daemon that was never
// installed.
LaunchHarness harness = launchHarness();
InspectContainerCmd inspect = mock(InspectContainerCmd.class);
InspectContainerResponse withIp = inspectResponse("172.18.0.21");
when(harness.dockerClient.inspectContainerCmd(TEST_CONTAINER_ID)).thenReturn(inspect);
when(inspect.exec()).thenReturn(withIp);
ExecCreateCmd execCreate = mock(ExecCreateCmd.class, withSettings().defaultAnswer(RETURNS_SELF));
when(harness.dockerClient.execCreateCmd(TEST_CONTAINER_ID)).thenReturn(execCreate);
AtomicReference<String[]> currentCommand = new AtomicReference<>();
when(execCreate.withCmd(any(String[].class))).thenAnswer(invocation -> {
Object[] args = invocation.getArguments();
currentCommand.set(args.length == 1 && args[0] instanceof String[] cmd
? cmd : Arrays.copyOf(args, args.length, String[].class));
return execCreate;
});
ExecCreateCmdResponse execResponse = mock(ExecCreateCmdResponse.class);
when(execResponse.getId()).thenReturn("exec-1");
when(execCreate.exec()).thenReturn(execResponse);
when(harness.dockerClient.execStartCmd(anyString())).thenAnswer(invocation -> {
ExecStartCmd execStart = mock(ExecStartCmd.class);
when(execStart.exec(any())).thenAnswer(startInvocation -> {
@SuppressWarnings("unchecked")
ResultCallback<Frame> callback = startInvocation.getArgument(0);
callback.onComplete();
return callback;
});
return execStart;
});
// Every exec succeeds except the sshd-install probe script, simulating an image with none
// of dnf/apt-get/apk, or whose install command itself failed.
InspectExecCmd inspectExec = mock(InspectExecCmd.class);
when(harness.dockerClient.inspectExecCmd(anyString())).thenReturn(inspectExec);
when(inspectExec.exec()).thenAnswer(invocation -> {
InspectExecResponse response = mock(InspectExecResponse.class);
boolean isSshdInstallProbe = Arrays.equals(currentCommand.get(), SSHD_INSTALL_PROBE_CMD);
when(response.getExitCodeLong()).thenReturn(isSshdInstallProbe ? 1L : 0L);
return response;
});
CopyArchiveToContainerCmd copy = mock(CopyArchiveToContainerCmd.class, withSettings().defaultAnswer(RETURNS_SELF));
when(harness.dockerClient.copyArchiveToContainerCmd(TEST_CONTAINER_ID)).thenReturn(copy);
when(copy.withTarInputStream(any(InputStream.class))).thenReturn(copy);
Instance instance = instance("i-sshdinstallfail");
harness.manager.launch(instance, "ubuntu:24.04", "ssh-ed25519 AAAAtest", "us-west-2");
awaitUntil(() -> "running".equals(instance.getState().getName()), Duration.ofSeconds(2));
verify(execCreate, timeout(2000)).withCmd(eq(SSHD_INSTALL_PROBE_CMD));
verify(execCreate, never()).withCmd(eq(new String[]{"ssh-keygen", "-A"}));
verify(execCreate, never()).withCmd(eq(new String[]{"sshd"}));
}
private static LaunchHarness launchHarness() {
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, withSettings().defaultAnswer(RETURNS_SELF));