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
@@ -882,6 +882,7 @@ public interface EmulatorConfig {
|
||||
|
||||
LakeFormationServiceConfig lakeformation();
|
||||
EfsServiceConfig efs();
|
||||
Ec2InstanceConnectServiceConfig ec2instanceconnect();
|
||||
CodeGuruReviewerServiceConfig codegurureviewer();
|
||||
CodeArtifactServiceConfig codeartifact();
|
||||
QuickSightServiceConfig quicksight();
|
||||
@@ -1207,6 +1208,11 @@ public interface EmulatorConfig {
|
||||
boolean enabled();
|
||||
}
|
||||
|
||||
interface Ec2InstanceConnectServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
}
|
||||
|
||||
interface EfsServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
|
||||
@@ -27,6 +27,7 @@ import io.floci.aws.services.configservice.ConfigServiceJsonHandler;
|
||||
import io.floci.aws.services.cur.CurJsonHandler;
|
||||
import io.floci.aws.services.datasync.DataSyncJsonHandler;
|
||||
import io.floci.aws.services.dms.DmsJsonHandler;
|
||||
import io.floci.aws.services.ec2instanceconnect.InstanceConnectJsonHandler;
|
||||
import io.floci.aws.services.ecr.EcrJsonHandler;
|
||||
import io.floci.aws.services.ecs.EcsJsonHandler;
|
||||
import io.floci.aws.services.emr.EmrHandler;
|
||||
@@ -115,6 +116,7 @@ public class AwsJson11Controller {
|
||||
private final CodeDeployJsonHandler codeDeployJsonHandler;
|
||||
private final CodePipelineJsonHandler codePipelineJsonHandler;
|
||||
private final Ec2MessagesJsonHandler ec2MessagesJsonHandler;
|
||||
private final InstanceConnectJsonHandler instanceConnectJsonHandler;
|
||||
private final TransferHandler transferHandler;
|
||||
private final TextractJsonHandler textractJsonHandler;
|
||||
private final ComprehendJsonHandler comprehendJsonHandler;
|
||||
@@ -172,6 +174,7 @@ public class AwsJson11Controller {
|
||||
CodeDeployJsonHandler codeDeployJsonHandler,
|
||||
CodePipelineJsonHandler codePipelineJsonHandler,
|
||||
Ec2MessagesJsonHandler ec2MessagesJsonHandler,
|
||||
InstanceConnectJsonHandler instanceConnectJsonHandler,
|
||||
TransferHandler transferHandler,
|
||||
TextractJsonHandler textractJsonHandler,
|
||||
ComprehendJsonHandler comprehendJsonHandler,
|
||||
@@ -233,6 +236,7 @@ public class AwsJson11Controller {
|
||||
this.codeDeployJsonHandler = codeDeployJsonHandler;
|
||||
this.codePipelineJsonHandler = codePipelineJsonHandler;
|
||||
this.ec2MessagesJsonHandler = ec2MessagesJsonHandler;
|
||||
this.instanceConnectJsonHandler = instanceConnectJsonHandler;
|
||||
this.transferHandler = transferHandler;
|
||||
this.textractJsonHandler = textractJsonHandler;
|
||||
this.comprehendJsonHandler = comprehendJsonHandler;
|
||||
@@ -340,6 +344,7 @@ public class AwsJson11Controller {
|
||||
case "codepipeline" -> codePipelineJsonHandler.handle(
|
||||
action, request, region, regionResolver.getAccountId());
|
||||
case "ec2messages" -> ec2MessagesJsonHandler.handle(action, request, region);
|
||||
case "ec2-instance-connect" -> instanceConnectJsonHandler.handle(action, request, region);
|
||||
case "transfer" -> transferHandler.handle(action, request, region);
|
||||
case "textract" -> textractJsonHandler.handle(action, request, region);
|
||||
case "comprehend" -> comprehendJsonHandler.handle(action, request, region);
|
||||
|
||||
@@ -641,6 +641,10 @@ public class ResolvedServiceCatalog {
|
||||
null, null, 5000L, null, ServiceProtocol.JSON,
|
||||
protocols(ServiceProtocol.JSON),
|
||||
Set.of("AmazonSSMMessageDeliveryService."), Set.of("ec2messages"), Set.of(), Set.of()),
|
||||
descriptor("ec2-instance-connect", "ec2-instance-connect", config.services().ec2instanceconnect().enabled(), false,
|
||||
null, null, 5000L, null, ServiceProtocol.JSON,
|
||||
protocols(ServiceProtocol.JSON),
|
||||
Set.of("AWSEC2InstanceConnectService."), Set.of("ec2-instance-connect"), Set.of(), Set.of()),
|
||||
descriptor("transfer", "transfer", config.services().transfer().enabled(), true,
|
||||
"transfer", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,
|
||||
protocols(ServiceProtocol.JSON),
|
||||
|
||||
@@ -583,6 +583,8 @@ public class Ec2ContainerManager {
|
||||
configureLinkLocalMetadataEndpoint(started.namespace() == null
|
||||
? containerId : started.namespace().helperId(), instanceId, flociHost, imdsPort);
|
||||
|
||||
installInstanceConnectTrustAnchor(containerId, instanceId);
|
||||
|
||||
// Publish security-group TCP ingress ports on the host via socat sidecars.
|
||||
if (appPorts != null && !appPorts.isEmpty()) {
|
||||
portForwardManager.reconcile(instance, appPorts);
|
||||
@@ -1738,6 +1740,40 @@ public class Ec2ContainerManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds Floci's local CA to the guest's system trust store, so the unmodified EC2 Instance
|
||||
* Connect agent can verify the signer chain Floci serves through IMDS. On EC2 that chain ends
|
||||
* at a public root the AMI already trusts. The agent finds the root by its common name, as
|
||||
* {@code /etc/ssl/certs/<CN with underscores>.pem}, which is the name
|
||||
* {@code update-ca-certificates} gives a {@code <stem>.crt} it installs. Best effort: images
|
||||
* without a Debian-family trust store are left alone.
|
||||
*/
|
||||
private void installInstanceConnectTrustAnchor(String containerId, String instanceId) {
|
||||
metadataServer.instanceConnect().ifPresent(keys -> {
|
||||
try {
|
||||
String dir = "/usr/local/share/ca-certificates";
|
||||
ContainerExec.Result probe = execInContainerForResult(containerId, new String[]{"sh", "-c",
|
||||
"[ -d " + dir + " ] && command -v update-ca-certificates >/dev/null"}, 5);
|
||||
if (probe.exitCode() != 0) {
|
||||
LOG.debugv("EC2 instance {0} has no update-ca-certificates trust store; EC2 Instance Connect "
|
||||
+ "keys cannot be verified there", instanceId);
|
||||
return;
|
||||
}
|
||||
RetryingTarCopier.copyBytes(dockerClient, containerId, dir, keys.trustAnchorFileStem() + ".crt",
|
||||
keys.trustAnchorPem().getBytes(StandardCharsets.UTF_8), 0644);
|
||||
ContainerExec.Result update = execInContainerForResult(containerId,
|
||||
new String[]{"update-ca-certificates"}, 60);
|
||||
if (update.exitCode() != 0) {
|
||||
LOG.warnv("Could not refresh the trust store of EC2 instance {0}: {1}", instanceId,
|
||||
update.summary());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Could not install the EC2 Instance Connect trust anchor in EC2 instance {0}: {1}",
|
||||
instanceId, e.getMessage());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void injectSshKey(String containerId, String publicKey) {
|
||||
try {
|
||||
// Ensure .ssh directory exists with correct permissions
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
package io.floci.aws.services.ec2;
|
||||
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.AwsRegions;
|
||||
import io.floci.aws.services.ec2.model.GroupIdentifier;
|
||||
import io.floci.aws.services.ec2.model.Instance;
|
||||
import io.floci.aws.services.ec2.model.Tag;
|
||||
import io.floci.aws.services.ec2instanceconnect.InstanceConnectKeys;
|
||||
import io.floci.aws.services.iam.IamService;
|
||||
import io.floci.aws.services.iam.model.IamRole;
|
||||
import io.floci.aws.services.iam.model.InstanceProfile;
|
||||
@@ -34,6 +36,7 @@ import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.BiFunction;
|
||||
|
||||
/**
|
||||
* IMDS-compatible HTTP server bound to port 9169 on the Floci host.
|
||||
@@ -67,17 +70,30 @@ public class Ec2MetadataServer {
|
||||
private final Set<Instance> synthesizedProfiles = ConcurrentHashMap.newKeySet();
|
||||
|
||||
private volatile HttpServer httpServer;
|
||||
private final InstanceConnectKeys instanceConnect;
|
||||
|
||||
@Inject
|
||||
public Ec2MetadataServer(Vertx vertx, EmulatorConfig config, IamService iamService) {
|
||||
this(vertx, config, iamService, Clock.systemUTC());
|
||||
public Ec2MetadataServer(Vertx vertx, EmulatorConfig config, IamService iamService,
|
||||
InstanceConnectKeys instanceConnect) {
|
||||
this(vertx, config, iamService, Clock.systemUTC(), instanceConnect);
|
||||
}
|
||||
|
||||
Ec2MetadataServer(Vertx vertx, EmulatorConfig config, IamService iamService, Clock clock) {
|
||||
this(vertx, config, iamService, clock, null);
|
||||
}
|
||||
|
||||
Ec2MetadataServer(Vertx vertx, EmulatorConfig config, IamService iamService, Clock clock,
|
||||
InstanceConnectKeys instanceConnect) {
|
||||
this.vertx = vertx;
|
||||
this.config = config;
|
||||
this.credentials = new Ec2InstanceCredentials(iamService);
|
||||
this.clock = clock;
|
||||
this.instanceConnect = instanceConnect;
|
||||
}
|
||||
|
||||
/** EC2 Instance Connect's signing material, for installing its trust anchor in guests; empty in tests. */
|
||||
public Optional<InstanceConnectKeys> instanceConnect() {
|
||||
return Optional.ofNullable(instanceConnect);
|
||||
}
|
||||
|
||||
/** Called by Ec2ContainerManager after a container starts to register its IP. */
|
||||
@@ -178,6 +194,17 @@ public class Ec2MetadataServer {
|
||||
router.get("/latest/meta-data/tags/instance").handler(ctx -> handleInstanceTagKeys(ctx));
|
||||
router.get("/latest/meta-data/tags/instance/").handler(ctx -> handleInstanceTagKeys(ctx));
|
||||
router.getWithRegex("/latest/meta-data/tags/instance/.+").handler(ctx -> handleInstanceTagValue(ctx));
|
||||
router.get("/latest/meta-data/services/domain").handler(ctx -> handleText(ctx, inst -> AwsRegions.dnsSuffixFor(inst.getRegion())));
|
||||
// EC2 Instance Connect. The agent probes active-keys with HEAD before fetching it. Blocking
|
||||
// handlers: the first call generates RSA key pairs and every one signs, which must not stall the event loop.
|
||||
router.route("/latest/meta-data/managed-ssh-keys/active-keys/:user").method(HttpMethod.GET)
|
||||
.method(HttpMethod.HEAD).blockingHandler(this::handleManagedSshKeys);
|
||||
router.get("/latest/meta-data/managed-ssh-keys/signer-cert").blockingHandler(ctx -> handleInstanceConnect(ctx,
|
||||
(keys, inst) -> keys.signerCertificateChain(inst.getRegion())));
|
||||
router.get("/latest/meta-data/managed-ssh-keys/signer-ocsp").blockingHandler(ctx -> handleInstanceConnect(ctx,
|
||||
(keys, inst) -> String.join("\n", keys.ocspStaples(inst.getRegion()).keySet())));
|
||||
router.get("/latest/meta-data/managed-ssh-keys/signer-ocsp/:fingerprint").blockingHandler(ctx -> handleInstanceConnect(ctx,
|
||||
(keys, inst) -> keys.ocspStaples(inst.getRegion()).get(ctx.pathParam("fingerprint"))));
|
||||
router.get("/latest/user-data").handler(ctx -> handleUserData(ctx));
|
||||
router.get("/latest/dynamic/instance-identity/document").handler(ctx -> handleIdentityDocument(ctx));
|
||||
|
||||
@@ -275,6 +302,31 @@ public class Ec2MetadataServer {
|
||||
.end(value);
|
||||
}
|
||||
|
||||
private void handleManagedSshKeys(RoutingContext ctx) {
|
||||
handleInstanceConnect(ctx, (keys, inst) -> keys.activeKeysDocument(inst.getRegion(),
|
||||
inst.getInstanceId(), ctx.pathParam("user")).orElse(null));
|
||||
}
|
||||
|
||||
private void handleInstanceConnect(RoutingContext ctx,
|
||||
BiFunction<InstanceConnectKeys, Instance, String> body) {
|
||||
Instance inst = resolveInstance(ctx);
|
||||
if (inst == null) {
|
||||
return;
|
||||
}
|
||||
String value = instanceConnect == null ? null : body.apply(instanceConnect, inst);
|
||||
if (value == null) {
|
||||
ctx.response().setStatusCode(404).end("not-available");
|
||||
return;
|
||||
}
|
||||
ctx.response().setStatusCode(200).putHeader("content-type", "text/plain");
|
||||
if (ctx.request().method() == HttpMethod.HEAD) {
|
||||
ctx.response().putHeader("content-length", String.valueOf(value.getBytes(StandardCharsets.UTF_8).length))
|
||||
.end();
|
||||
} else {
|
||||
ctx.response().end(value);
|
||||
}
|
||||
}
|
||||
|
||||
private void handleMac(RoutingContext ctx) {
|
||||
Instance inst = resolveInstance(ctx);
|
||||
if (inst == null) {
|
||||
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
package io.floci.aws.services.ec2instanceconnect;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
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.core.common.SshPublicKeys;
|
||||
import io.floci.aws.services.ec2.Ec2Service;
|
||||
import io.floci.aws.services.ec2.model.Instance;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* EC2 Instance Connect ({@code X-Amz-Target: AWSEC2InstanceConnectService.*}).
|
||||
*
|
||||
* <p>{@code SendSSHPublicKey} validates the request against the service model and the instance's
|
||||
* state, then hands the key to {@link InstanceConnectKeys}, which serves it signed to the
|
||||
* instance's agent through IMDS for {@link InstanceConnectKeys#KEY_LIFETIME}. The serial console
|
||||
* operation is answered with {@code SerialConsoleSessionUnsupportedException} once the instance is
|
||||
* found: Docker-backed instances have no serial console.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class InstanceConnectJsonHandler {
|
||||
|
||||
// Patterns and bounds from the service model (ec2-instance-connect 2018-04-02).
|
||||
private static final Pattern INSTANCE_ID = Pattern.compile("^i-[a-f0-9]+$");
|
||||
private static final Pattern OS_USER = Pattern.compile(
|
||||
"(^[A-Za-z_][A-Za-z0-9@._-]{0,30}[A-Za-z0-9$_-]?$)"
|
||||
+ "|(^(?=.{2,32}$)[0-9]{1,32}[A-Za-z@._-][A-Za-z0-9@._-]*[A-Za-z0-9$_-]?$)");
|
||||
private static final Pattern AVAILABILITY_ZONE = Pattern.compile("^(\\w+-){2,3}\\d+\\w+$");
|
||||
/** The key types AWS documents for EC2 Instance Connect: RSA (2048 bits or more), ED25519 and ECDSA. */
|
||||
private static final Set<String> KEY_TYPES = Set.of("ssh-rsa", "ssh-ed25519",
|
||||
"ecdsa-sha2-nistp256", "ecdsa-sha2-nistp384", "ecdsa-sha2-nistp521");
|
||||
private static final int MIN_RSA_BITS = 2048;
|
||||
|
||||
private final Ec2Service ec2Service;
|
||||
private final InstanceConnectKeys keys;
|
||||
private final RegionResolver regionResolver;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final Clock clock;
|
||||
|
||||
@Inject
|
||||
public InstanceConnectJsonHandler(Ec2Service ec2Service, InstanceConnectKeys keys,
|
||||
RegionResolver regionResolver, ObjectMapper objectMapper) {
|
||||
this(ec2Service, keys, regionResolver, objectMapper, Clock.systemUTC());
|
||||
}
|
||||
|
||||
InstanceConnectJsonHandler(Ec2Service ec2Service, InstanceConnectKeys keys, RegionResolver regionResolver,
|
||||
ObjectMapper objectMapper, Clock clock) {
|
||||
this.ec2Service = ec2Service;
|
||||
this.keys = keys;
|
||||
this.regionResolver = regionResolver;
|
||||
this.objectMapper = objectMapper;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
public Response handle(String action, JsonNode request, String region) {
|
||||
return switch (action) {
|
||||
case "SendSSHPublicKey" -> sendSshPublicKey(request, region);
|
||||
case "SendSerialConsoleSSHPublicKey" -> sendSerialConsoleSshPublicKey(request, region);
|
||||
default -> throw new AwsException("UnknownOperationException",
|
||||
"Operation " + action + " is not supported.", 400);
|
||||
};
|
||||
}
|
||||
|
||||
private Response sendSshPublicKey(JsonNode request, String region) {
|
||||
String instanceId = required(request, "InstanceId");
|
||||
String osUser = required(request, "InstanceOSUser");
|
||||
String publicKey = required(request, "SSHPublicKey");
|
||||
String zone = request.path("AvailabilityZone").asText(null);
|
||||
|
||||
if (instanceId.length() < 10 || instanceId.length() > 32 || !INSTANCE_ID.matcher(instanceId).matches()) {
|
||||
throw invalid("Invalid instance ID: " + instanceId);
|
||||
}
|
||||
if (osUser.length() > 32 || !OS_USER.matcher(osUser).matches()) {
|
||||
throw invalid("Invalid InstanceOSUser: " + osUser);
|
||||
}
|
||||
if (publicKey.length() < 80 || publicKey.length() > 4096) {
|
||||
throw invalid("SSHPublicKey must be between 80 and 4096 characters long.");
|
||||
}
|
||||
if (publicKey.trim().chars().anyMatch(Character::isISOControl)) {
|
||||
// The key is copied verbatim into the signed active-keys document, whose framing is
|
||||
// line-based: an embedded newline would let one key forge lines for another.
|
||||
throw invalid("SSHPublicKey must be a single line without control characters.");
|
||||
}
|
||||
validatePublicKey(publicKey.trim());
|
||||
if (zone != null && (zone.length() < 6 || zone.length() > 32 || !AVAILABILITY_ZONE.matcher(zone).matches())) {
|
||||
throw invalid("Invalid AvailabilityZone: " + zone);
|
||||
}
|
||||
|
||||
Instance instance = ec2Service.getInstance(region, instanceId)
|
||||
.orElseThrow(() -> new AwsException("EC2InstanceNotFoundException",
|
||||
"Instance not found: " + instanceId, 400));
|
||||
String instanceZone = instance.getPlacement() != null ? instance.getPlacement().getAvailabilityZone() : null;
|
||||
if (zone != null && instanceZone != null && !zone.equals(instanceZone)) {
|
||||
throw new AwsException("EC2InstanceNotFoundException",
|
||||
"Instance not found in availability zone " + zone + ": " + instanceId, 400);
|
||||
}
|
||||
String state = instance.getState() != null ? instance.getState().getName() : null;
|
||||
if (!"running".equals(state)) {
|
||||
throw new AwsException("EC2InstanceStateInvalidException",
|
||||
"Instance " + instanceId + " is not in a valid state for this operation: " + state, 400);
|
||||
}
|
||||
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
String caller = regionResolver.buildGlobalArn("iam", "root");
|
||||
keys.add(new InstanceConnectKeys.ActiveKey(instanceId, osUser, publicKey.trim(),
|
||||
clock.instant().plus(InstanceConnectKeys.KEY_LIFETIME), caller, requestId));
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("RequestId", requestId);
|
||||
response.put("Success", true);
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
/** Docker-backed instances have no serial console; AWS checks the instance exists before saying so. */
|
||||
private Response sendSerialConsoleSshPublicKey(JsonNode request, String region) {
|
||||
String instanceId = required(request, "InstanceId");
|
||||
ec2Service.getInstance(region, instanceId)
|
||||
.orElseThrow(() -> new AwsException("EC2InstanceNotFoundException",
|
||||
"Instance not found: " + instanceId, 400));
|
||||
throw new AwsException("SerialConsoleSessionUnsupportedException",
|
||||
"The EC2 serial console is not supported for instance " + instanceId + ".", 400);
|
||||
}
|
||||
|
||||
private static String required(JsonNode request, String field) {
|
||||
JsonNode value = request.get(field);
|
||||
if (value == null || value.isNull() || value.asText().isEmpty()) {
|
||||
throw invalid(field + " is required.");
|
||||
}
|
||||
return value.asText();
|
||||
}
|
||||
|
||||
/** One OpenSSH public key line: a supported type, its base64 blob carrying the same type, RSA of 2048 bits or more. */
|
||||
static void validatePublicKey(String line) {
|
||||
String[] parts = line.split("\\s+");
|
||||
if (parts.length < 2 || !KEY_TYPES.contains(parts[0])) {
|
||||
throw invalid("Unsupported or malformed SSH public key. Supported types: RSA, ED25519 and ECDSA.");
|
||||
}
|
||||
byte[] blob = SshPublicKeys.decodeBlob(line);
|
||||
if (!SshPublicKeys.carriesAKey(blob)) {
|
||||
throw invalid("Malformed SSH public key.");
|
||||
}
|
||||
if (!SshPublicKeys.keyType(blob).equals(parts[0])) {
|
||||
throw invalid("The SSH public key's type does not match its encoded data.");
|
||||
}
|
||||
if ("ssh-rsa".equals(parts[0]) && SshPublicKeys.rsaKeyOf(blob).getModulus().bitLength() < MIN_RSA_BITS) {
|
||||
throw invalid("RSA keys must be at least " + MIN_RSA_BITS + " bits long.");
|
||||
}
|
||||
}
|
||||
|
||||
private static AwsException invalid(String message) {
|
||||
return new AwsException("InvalidArgsException", message, 400);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
package io.floci.aws.services.ec2instanceconnect;
|
||||
|
||||
import io.floci.aws.config.FlociCertificateAuthority;
|
||||
import io.floci.aws.core.common.AwsRegions;
|
||||
import io.floci.aws.core.common.Resettable;
|
||||
import io.floci.aws.services.acm.CertificateGenerator;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.inject.Inject;
|
||||
import org.bouncycastle.asn1.x500.X500Name;
|
||||
import org.bouncycastle.cert.X509CertificateHolder;
|
||||
import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder;
|
||||
import org.bouncycastle.cert.ocsp.BasicOCSPResp;
|
||||
import org.bouncycastle.cert.ocsp.BasicOCSPRespBuilder;
|
||||
import org.bouncycastle.cert.ocsp.CertificateID;
|
||||
import org.bouncycastle.cert.ocsp.CertificateStatus;
|
||||
import org.bouncycastle.cert.ocsp.OCSPResp;
|
||||
import org.bouncycastle.cert.ocsp.OCSPRespBuilder;
|
||||
import org.bouncycastle.cert.ocsp.jcajce.JcaBasicOCSPRespBuilder;
|
||||
import org.bouncycastle.operator.DigestCalculatorProvider;
|
||||
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
|
||||
import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.KeyPair;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.Signature;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.security.interfaces.ECKey;
|
||||
import java.security.spec.MGF1ParameterSpec;
|
||||
import java.security.spec.PSSParameterSpec;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.Date;
|
||||
import java.util.HexFormat;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* The instance side of EC2 Instance Connect: the keys {@code SendSSHPublicKey} pushed, and the
|
||||
* signing material the unmodified AWS agent ({@code aws-ec2-instance-connect-config}) verifies
|
||||
* them with, served through IMDS under {@code managed-ssh-keys/}.
|
||||
*
|
||||
* <p>The agent's contract, which this class exists to satisfy:
|
||||
* <ul>
|
||||
* <li>{@code signer-cert/} is a PEM chain: the signer first, then each issuer. The signer's CN
|
||||
* must be {@code managed-ssh-signer.<region>.<domain>}, and the last certificate's CN must
|
||||
* name a trusted file {@code /etc/ssl/certs/<CN with spaces as underscores>.pem}.</li>
|
||||
* <li>Every certificate below that trusted one needs an OCSP staple at
|
||||
* {@code signer-ocsp/<upper-case SHA-1 fingerprint>} (base64 DER), signed by its issuer,
|
||||
* reporting {@code good}.</li>
|
||||
* <li>{@code active-keys/<user>/} holds one entry per key: {@code #Timestamp=} (expiry, epoch
|
||||
* seconds), {@code #Instance=}, {@code #Caller=} and {@code #Request=} lines, the key line,
|
||||
* then a base64 RSA-PSS (SHA-256, MGF1-SHA-256, salt 32) signature over those lines, and a
|
||||
* blank line.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>The chain is signer, a Floci intermediate, and Floci's local CA, which Floci installs into
|
||||
* each guest's trust store. On AWS the chain ends at a public root the AMI already trusts.
|
||||
* Signing material lives in memory: a restart issues a new intermediate and signers under the
|
||||
* same persistent root, so guests keep verifying.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class InstanceConnectKeys implements Resettable {
|
||||
|
||||
/** AWS keeps a pushed key for 60 seconds. */
|
||||
public static final Duration KEY_LIFETIME = Duration.ofSeconds(60);
|
||||
static final String INTERMEDIATE_CN = "Floci EC2 Instance Connect Intermediate CA";
|
||||
private static final Duration INTERMEDIATE_VALIDITY = Duration.ofDays(365);
|
||||
private static final Duration SIGNER_VALIDITY = Duration.ofDays(30);
|
||||
/** Material is reissued once it is this close to expiry, so a verification never races it. */
|
||||
private static final Duration RENEW_BEFORE = Duration.ofDays(1);
|
||||
private static final Duration STAPLE_VALIDITY = Duration.ofDays(7);
|
||||
|
||||
public record ActiveKey(String instanceId, String osUser, String publicKey, Instant expiresAt,
|
||||
String caller, String requestId) {}
|
||||
|
||||
private record Issued(X509Certificate certificate, PrivateKey key) {}
|
||||
|
||||
private final Supplier<FlociCertificateAuthority> rootCa;
|
||||
private final CertificateGenerator generator;
|
||||
private final Clock clock;
|
||||
private final Map<String, List<ActiveKey>> keysByInstance = new ConcurrentHashMap<>();
|
||||
private final Map<String, Issued> signers = new ConcurrentHashMap<>();
|
||||
private Issued intermediate;
|
||||
|
||||
@Inject
|
||||
public InstanceConnectKeys(Instance<FlociCertificateAuthority> rootCa,
|
||||
CertificateGenerator generator) {
|
||||
this(rootCa::get, generator, Clock.systemUTC());
|
||||
}
|
||||
|
||||
InstanceConnectKeys(Supplier<FlociCertificateAuthority> rootCa, CertificateGenerator generator, Clock clock) {
|
||||
this.rootCa = rootCa;
|
||||
this.generator = generator;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
// ── Keys ──────────────────────────────────────────────────────────────────
|
||||
|
||||
public void add(ActiveKey key) {
|
||||
// Expired keys go here rather than on terminate: a key lives 60 seconds, so this bounds the
|
||||
// map to instances that received one within the last minute.
|
||||
keysByInstance.entrySet().removeIf(entry -> live(entry.getValue()).isEmpty());
|
||||
keysByInstance.compute(key.instanceId(), (id, existing) -> {
|
||||
List<ActiveKey> live = live(existing);
|
||||
live.add(key);
|
||||
return live;
|
||||
});
|
||||
}
|
||||
|
||||
/** The signed authorized-keys document for {@code osUser}, or empty when no key is live. */
|
||||
public Optional<String> activeKeysDocument(String region, String instanceId, String osUser) {
|
||||
List<ActiveKey> forUser = live(keysByInstance.get(instanceId)).stream()
|
||||
.filter(key -> key.osUser().equals(osUser))
|
||||
.toList();
|
||||
if (forUser.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
PrivateKey signingKey = signer(region).key();
|
||||
StringBuilder document = new StringBuilder();
|
||||
for (ActiveKey key : forUser) {
|
||||
String signed = "#Timestamp=" + key.expiresAt().getEpochSecond() + "\n"
|
||||
+ "#Instance=" + key.instanceId() + "\n"
|
||||
+ "#Caller=" + key.caller() + "\n"
|
||||
+ "#Request=" + key.requestId() + "\n"
|
||||
+ key.publicKey().trim() + "\n";
|
||||
document.append(signed).append(sign(signingKey, signed)).append("\n\n");
|
||||
}
|
||||
return Optional.of(document.toString());
|
||||
}
|
||||
|
||||
int trackedInstanceCount() {
|
||||
return keysByInstance.size();
|
||||
}
|
||||
|
||||
private List<ActiveKey> live(List<ActiveKey> keys) {
|
||||
Instant now = clock.instant();
|
||||
List<ActiveKey> live = new ArrayList<>();
|
||||
if (keys != null) {
|
||||
keys.stream().filter(key -> key.expiresAt().isAfter(now)).forEach(live::add);
|
||||
}
|
||||
return live;
|
||||
}
|
||||
|
||||
private static String sign(PrivateKey key, String data) {
|
||||
try {
|
||||
Signature signature = Signature.getInstance("RSASSA-PSS");
|
||||
signature.setParameter(new PSSParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, 32, 1));
|
||||
signature.initSign(key);
|
||||
signature.update(data.getBytes(StandardCharsets.UTF_8));
|
||||
return Base64.getEncoder().encodeToString(signature.sign());
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Failed to sign an EC2 Instance Connect key", e);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Signing material ──────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* The signer certificate, then the intermediate, then the root: what {@code signer-cert/} serves.
|
||||
* Synchronized with {@link #signer} and {@link #intermediate} so a rotation between the two reads
|
||||
* cannot mix generations.
|
||||
*/
|
||||
public synchronized String signerCertificateChain(String region) {
|
||||
try {
|
||||
return generator.toPem(signer(region).certificate())
|
||||
+ generator.toPem(intermediate().certificate())
|
||||
+ rootCa.get().caPem();
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Failed to encode the EC2 Instance Connect signer chain", e);
|
||||
}
|
||||
}
|
||||
|
||||
/** OCSP staples by upper-case SHA-1 fingerprint, each base64 DER: the signer's and the intermediate's. */
|
||||
public synchronized Map<String, String> ocspStaples(String region) {
|
||||
Issued signer = signer(region);
|
||||
Issued intermediate = intermediate();
|
||||
FlociCertificateAuthority root = rootCa.get();
|
||||
Map<String, String> staples = new LinkedHashMap<>();
|
||||
staples.put(sha1Fingerprint(signer.certificate()),
|
||||
staple(signer.certificate(), intermediate.certificate(), intermediate.key()));
|
||||
staples.put(sha1Fingerprint(intermediate.certificate()),
|
||||
staple(intermediate.certificate(), root.certificate(), root.key()));
|
||||
return staples;
|
||||
}
|
||||
|
||||
/** The root guests must trust, and the file name the agent looks it up by. */
|
||||
public String trustAnchorPem() {
|
||||
return rootCa.get().caPem();
|
||||
}
|
||||
|
||||
public String trustAnchorFileStem() {
|
||||
String dn = rootCa.get().certificate().getSubjectX500Principal().getName();
|
||||
String cn = dn.replaceFirst("(?s).*CN=([^,]+).*", "$1");
|
||||
return cn.trim().replaceAll(" +", "_");
|
||||
}
|
||||
|
||||
public static String signerCommonName(String region) {
|
||||
return "managed-ssh-signer." + region + "." + AwsRegions.dnsSuffixFor(region);
|
||||
}
|
||||
|
||||
private synchronized Issued intermediate() {
|
||||
if (intermediate == null || expiresSoon(intermediate.certificate())) {
|
||||
FlociCertificateAuthority root = rootCa.get();
|
||||
intermediate = issue(INTERMEDIATE_CN, true,
|
||||
X500Name.getInstance(root.certificate().getSubjectX500Principal().getEncoded()),
|
||||
root.certificate(), root.key(), INTERMEDIATE_VALIDITY);
|
||||
signers.clear();
|
||||
}
|
||||
return intermediate;
|
||||
}
|
||||
|
||||
private synchronized Issued signer(String region) {
|
||||
Issued issuer = intermediate();
|
||||
Issued current = signers.get(region);
|
||||
if (current == null || expiresSoon(current.certificate())) {
|
||||
current = issue(signerCommonName(region), false,
|
||||
X500Name.getInstance(issuer.certificate().getSubjectX500Principal().getEncoded()),
|
||||
issuer.certificate(), issuer.key(), SIGNER_VALIDITY);
|
||||
signers.put(region, current);
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
private boolean expiresSoon(X509Certificate certificate) {
|
||||
return certificate.getNotAfter().toInstant().isBefore(clock.instant().plus(RENEW_BEFORE));
|
||||
}
|
||||
|
||||
private Issued issue(String commonName, boolean asCa, X500Name issuerDn, X509Certificate issuerCert,
|
||||
PrivateKey issuerKey, Duration validity) {
|
||||
try {
|
||||
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
|
||||
keyGen.initialize(2048);
|
||||
KeyPair pair = keyGen.generateKeyPair();
|
||||
Instant now = clock.instant();
|
||||
X509Certificate cert = generator.signCertificate(new X500Name("CN=" + commonName), pair.getPublic(),
|
||||
issuerDn, issuerKey, List.of(), asCa, null, now.minus(5, ChronoUnit.MINUTES),
|
||||
now.plus(validity), issuerCert.getPublicKey());
|
||||
return new Issued(cert, pair.getPrivate());
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Failed to issue " + commonName, e);
|
||||
}
|
||||
}
|
||||
|
||||
private String staple(X509Certificate certificate, X509Certificate issuer, PrivateKey issuerKey) {
|
||||
try {
|
||||
DigestCalculatorProvider digests = new JcaDigestCalculatorProviderBuilder().build();
|
||||
CertificateID id = new CertificateID(digests.get(CertificateID.HASH_SHA1),
|
||||
new JcaX509CertificateHolder(issuer), certificate.getSerialNumber());
|
||||
BasicOCSPRespBuilder builder = new JcaBasicOCSPRespBuilder(issuer.getPublicKey(),
|
||||
digests.get(CertificateID.HASH_SHA1));
|
||||
Instant now = clock.instant();
|
||||
builder.addResponse(id, CertificateStatus.GOOD, Date.from(now.minus(5, ChronoUnit.MINUTES)),
|
||||
Date.from(now.plus(STAPLE_VALIDITY)), null);
|
||||
String algorithm = issuerKey instanceof ECKey ? "SHA256withECDSA" : "SHA256withRSA";
|
||||
BasicOCSPResp basic = builder.build(new JcaContentSignerBuilder(algorithm).build(issuerKey),
|
||||
new X509CertificateHolder[0], Date.from(now));
|
||||
OCSPResp response = new OCSPRespBuilder().build(OCSPRespBuilder.SUCCESSFUL, basic);
|
||||
return Base64.getEncoder().encodeToString(response.getEncoded());
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Failed to staple " + certificate.getSubjectX500Principal(), e);
|
||||
}
|
||||
}
|
||||
|
||||
static String sha1Fingerprint(X509Certificate certificate) {
|
||||
try {
|
||||
return HexFormat.of().withUpperCase()
|
||||
.formatHex(MessageDigest.getInstance("SHA-1").digest(certificate.getEncoded()));
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Cannot fingerprint " + certificate.getSubjectX500Principal(), e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void clear() {
|
||||
keysByInstance.clear();
|
||||
signers.clear();
|
||||
intermediate = null;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user