mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 22:11:36 -05:00
fix(ec2): issue instance-profile role credentials through IMDS (#3742)
* fix(ec2): issue instance-profile role credentials through IMDS * test(ec2): cover null IMDS unregister and shutdown revocation
This commit is contained in:
1 parent
ef03c59864
commit
d4a96913df
13 files changed
+504
-74
No files matched your search
@@ -193,6 +193,10 @@ public class EmulatorLifecycle {
|
||||
if (sweptSessions > 0) {
|
||||
LOG.infov("Removed {0} orphaned Lambda execution-role session(s)", sweptSessions);
|
||||
}
|
||||
int sweptEc2Sessions = iamService.sweepOrphanedEc2InstanceSessions();
|
||||
if (sweptEc2Sessions > 0) {
|
||||
LOG.infov("Removed {0} orphaned EC2 instance session(s)", sweptEc2Sessions);
|
||||
}
|
||||
schemaCreationWorker.recoverOrphans();
|
||||
schemaCreationWorker.rehydrateSchemas();
|
||||
stepFunctionsService.abortAbandonedExecutions();
|
||||
|
||||
@@ -582,7 +582,7 @@ public class Ec2ContainerManager {
|
||||
namespace.helperId(), prefixLists);
|
||||
}
|
||||
ContainerSpec spec = buildContainerSpec(containerName, image, region, serviceEndpoint, imdsEndpoint,
|
||||
instanceId, sshHostPort, namespace);
|
||||
instanceId, sshHostPort, namespace, instance.getIamInstanceProfileArn() != null);
|
||||
containerId = image.dockerPlatform() == null
|
||||
? lifecycleManager.create(spec)
|
||||
: lifecycleManager.create(spec, image.dockerPlatform());
|
||||
@@ -636,13 +636,15 @@ public class Ec2ContainerManager {
|
||||
|
||||
private ContainerSpec buildContainerSpec(String containerName, ResolvedAmiImage image, String region,
|
||||
String serviceEndpoint, String imdsEndpoint, String instanceId,
|
||||
int sshHostPort, SecurityGroupFirewallManager.Namespace namespace) {
|
||||
int sshHostPort, SecurityGroupFirewallManager.Namespace namespace,
|
||||
boolean hasInstanceProfile) {
|
||||
// Minimal images keep the historic tail command, while cloud-image AMI guests can boot their init.
|
||||
ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image.dockerImage())
|
||||
.withName(containerName)
|
||||
.withEmbeddedDns()
|
||||
.withDockerNetwork(Optional.empty())
|
||||
.withEnv(localAwsEnvironment(region, serviceEndpoint, imdsEndpoint))
|
||||
.withEnv(localAwsEnvironment(region, serviceEndpoint, imdsEndpoint,
|
||||
hasInstanceProfile))
|
||||
.withEnv("AWS_EC2_INSTANCE_ID", instanceId)
|
||||
.withHostDockerInternalOnLinux()
|
||||
.withLogRotation()
|
||||
@@ -1797,14 +1799,21 @@ public class Ec2ContainerManager {
|
||||
|
||||
|
||||
static List<String> localAwsEnvironment(String region, String serviceEndpoint, String imdsEndpoint) {
|
||||
return List.of(
|
||||
return localAwsEnvironment(region, serviceEndpoint, imdsEndpoint, false);
|
||||
}
|
||||
|
||||
static List<String> localAwsEnvironment(String region, String serviceEndpoint, String imdsEndpoint,
|
||||
boolean hasInstanceProfile) {
|
||||
List<String> environment = new ArrayList<>(List.of(
|
||||
"AWS_EC2_METADATA_SERVICE_ENDPOINT=" + imdsEndpoint,
|
||||
"AWS_ENDPOINT_URL=" + serviceEndpoint,
|
||||
"AWS_DEFAULT_REGION=" + region,
|
||||
"AWS_REGION=" + region,
|
||||
"AWS_ACCESS_KEY_ID=test",
|
||||
"AWS_SECRET_ACCESS_KEY=test",
|
||||
"AWS_SESSION_TOKEN=test-session-token");
|
||||
"AWS_REGION=" + region));
|
||||
if (!hasInstanceProfile) {
|
||||
environment.addAll(List.of("AWS_ACCESS_KEY_ID=test", "AWS_SECRET_ACCESS_KEY=test",
|
||||
"AWS_SESSION_TOKEN=test-session-token"));
|
||||
}
|
||||
return environment;
|
||||
}
|
||||
|
||||
static String summarizeUserDataOutput(BoundedOutput output) {
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
package io.github.hectorvent.floci.services.ec2;
|
||||
|
||||
import io.github.hectorvent.floci.services.ec2.model.Instance;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamRole;
|
||||
import io.github.hectorvent.floci.services.iam.model.SessionCredential;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.HexFormat;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
/** Owns credentials for the lifetime of each registered EC2 guest. */
|
||||
final class Ec2InstanceCredentials {
|
||||
private final IamService iam;
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
private final Map<Instance, List<Issued>> sessions = new IdentityHashMap<>();
|
||||
|
||||
Ec2InstanceCredentials(IamService iam) {
|
||||
this.iam = iam;
|
||||
}
|
||||
|
||||
synchronized void register(Instance instance) {
|
||||
sessions.computeIfAbsent(instance, ignored -> new ArrayList<>());
|
||||
}
|
||||
|
||||
synchronized void unregister(Instance instance) {
|
||||
List<Issued> issued = sessions.remove(instance);
|
||||
if (issued != null) {
|
||||
issued.forEach(this::revoke);
|
||||
}
|
||||
}
|
||||
|
||||
synchronized void clear() {
|
||||
sessions.values().forEach(issued -> issued.forEach(this::revoke));
|
||||
sessions.clear();
|
||||
}
|
||||
|
||||
synchronized Optional<IamRole> role(Instance instance) {
|
||||
String arn = instance.getIamInstanceProfileArn();
|
||||
if (!sessions.containsKey(instance) || arn == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String[] parts = arn.split(":", 6);
|
||||
if (parts.length != 6 || !"arn".equals(parts[0]) || !"iam".equals(parts[2])
|
||||
|| !parts[3].isEmpty() || !parts[4].matches("[0-9]{12}")
|
||||
|| !parts[5].startsWith("instance-profile/")) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String name = arn.substring(arn.lastIndexOf('/') + 1);
|
||||
return iam.findInstanceProfile(parts[4], name)
|
||||
.filter(profile -> arn.equals(profile.getArn()))
|
||||
.filter(profile -> profile.getRoleNames() != null && profile.getRoleNames().size() == 1)
|
||||
.flatMap(profile -> iam.findRole(parts[4], profile.getRoleNames().getFirst()))
|
||||
.filter(role -> role.getArn() != null && role.getArn().startsWith(
|
||||
"arn:" + parts[1] + ":iam::" + parts[4] + ":role/"));
|
||||
}
|
||||
|
||||
synchronized Optional<SessionCredential> get(Instance instance, String roleName, Instant now) {
|
||||
List<Issued> history = sessions.get(instance);
|
||||
if (history == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
Optional<IamRole> resolved = role(instance);
|
||||
history.removeIf(issued -> {
|
||||
boolean obsolete = !issued.session().getExpiration().isAfter(now) || resolved.isEmpty()
|
||||
|| !Objects.equals(issued.roleId(), resolved.get().getRoleId())
|
||||
|| !Objects.equals(issued.session().getRoleArn(), resolved.get().getArn())
|
||||
|| !Objects.equals(issued.profileArn(), instance.getIamInstanceProfileArn());
|
||||
if (obsolete) {
|
||||
revoke(issued);
|
||||
}
|
||||
return obsolete;
|
||||
});
|
||||
if (resolved.isEmpty() || !resolved.get().getRoleName().equals(roleName)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
if (!history.isEmpty()) {
|
||||
SessionCredential current = history.getLast().session();
|
||||
if (current.getExpiration().isAfter(now.plusSeconds(300))) {
|
||||
return Optional.of(current);
|
||||
}
|
||||
}
|
||||
IamRole role = resolved.get();
|
||||
String account = role.getArn().split(":", 6)[4];
|
||||
byte[] key = new byte[10];
|
||||
random.nextBytes(key);
|
||||
String accessKey = "ASIA" + HexFormat.of().withUpperCase().formatHex(key).substring(0, 16);
|
||||
SessionCredential session = new SessionCredential(accessKey, randomString(30), randomString(48),
|
||||
role.getArn(), now.plusSeconds(3600), null, account);
|
||||
session.setEc2InstanceId(instance.getInstanceId());
|
||||
iam.registerEc2InstanceSession(session);
|
||||
history.add(new Issued(session, role.getRoleId(), instance.getIamInstanceProfileArn()));
|
||||
return Optional.of(session);
|
||||
}
|
||||
|
||||
private String randomString(int size) {
|
||||
byte[] bytes = new byte[size];
|
||||
random.nextBytes(bytes);
|
||||
return Base64.getEncoder().encodeToString(bytes);
|
||||
}
|
||||
|
||||
private void revoke(Issued issued) {
|
||||
iam.unregisterSession(issued.session().getOriginAccountId(), issued.session().getAccessKeyId());
|
||||
}
|
||||
|
||||
private record Issued(SessionCredential session, String roleId, String profileArn) {}
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
package io.github.hectorvent.floci.services.ec2;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Instance;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamRole;
|
||||
import io.github.hectorvent.floci.services.iam.model.SessionCredential;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.http.HttpServer;
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import io.vertx.ext.web.Router;
|
||||
import io.vertx.ext.web.RoutingContext;
|
||||
import io.vertx.ext.web.handler.BodyHandler;
|
||||
@@ -43,7 +45,7 @@ public class Ec2MetadataServer {
|
||||
|
||||
private final Vertx vertx;
|
||||
private final EmulatorConfig config;
|
||||
private final IamService iamService;
|
||||
private final Ec2InstanceCredentials credentials;
|
||||
|
||||
/** IMDSv2: token value → Instance */
|
||||
private final Map<String, Instance> tokenToInstance = new ConcurrentHashMap<>();
|
||||
@@ -56,12 +58,13 @@ public class Ec2MetadataServer {
|
||||
public Ec2MetadataServer(Vertx vertx, EmulatorConfig config, IamService iamService) {
|
||||
this.vertx = vertx;
|
||||
this.config = config;
|
||||
this.iamService = iamService;
|
||||
this.credentials = new Ec2InstanceCredentials(iamService);
|
||||
}
|
||||
|
||||
/** Called by Ec2ContainerManager after a container starts to register its IP. */
|
||||
public void registerContainer(String containerIp, String instanceId, Instance instance) {
|
||||
if (containerIp != null && !containerIp.isBlank()) {
|
||||
credentials.register(instance);
|
||||
containerIpToInstance.put(containerIp, instance);
|
||||
LOG.debugv("IMDS: registered container {0} → instance {1}", containerIp, instanceId);
|
||||
}
|
||||
@@ -85,6 +88,8 @@ public class Ec2MetadataServer {
|
||||
|
||||
public void unregisterInstance(Instance instance) {
|
||||
if (instance != null) {
|
||||
credentials.unregister(instance);
|
||||
tokenToInstance.entrySet().removeIf(entry -> entry.getValue() == instance);
|
||||
containerIpToInstance.entrySet().removeIf(entry -> entry.getValue() == instance);
|
||||
}
|
||||
}
|
||||
@@ -143,6 +148,9 @@ public class Ec2MetadataServer {
|
||||
}
|
||||
|
||||
public synchronized void stop() {
|
||||
credentials.clear();
|
||||
tokenToInstance.clear();
|
||||
containerIpToInstance.clear();
|
||||
if (httpServer != null) {
|
||||
httpServer.close();
|
||||
httpServer = null;
|
||||
@@ -250,15 +258,12 @@ public class Ec2MetadataServer {
|
||||
if (inst == null) {
|
||||
return;
|
||||
}
|
||||
String profileArn = inst.getIamInstanceProfileArn();
|
||||
if (profileArn == null) {
|
||||
Optional<IamRole> role = credentials.role(inst);
|
||||
if (role.isEmpty()) {
|
||||
ctx.response().setStatusCode(404).end();
|
||||
return;
|
||||
}
|
||||
String roleName = resolveRoleName(profileArn);
|
||||
ctx.response().setStatusCode(200)
|
||||
.putHeader("content-type", "text/plain")
|
||||
.end(roleName);
|
||||
ctx.response().putHeader("content-type", "text/plain").end(role.get().getRoleName());
|
||||
}
|
||||
|
||||
private void handleCredentials(RoutingContext ctx) {
|
||||
@@ -266,22 +271,20 @@ public class Ec2MetadataServer {
|
||||
if (inst == null) {
|
||||
return;
|
||||
}
|
||||
if (inst.getIamInstanceProfileArn() == null) {
|
||||
Optional<SessionCredential> result = credentials.get(inst, ctx.pathParam("role"), Instant.now());
|
||||
if (result.isEmpty()) {
|
||||
ctx.response().setStatusCode(404).end();
|
||||
return;
|
||||
}
|
||||
|
||||
String expiration = ISO.format(Instant.now().plusSeconds(3600));
|
||||
String body = "{\"Code\":\"Success\","
|
||||
+ "\"LastUpdated\":\"" + now() + "\","
|
||||
+ "\"Type\":\"AWS-HMAC\","
|
||||
+ "\"AccessKeyId\":\"test\","
|
||||
+ "\"SecretAccessKey\":\"test\","
|
||||
+ "\"Token\":\"test-session-token\","
|
||||
+ "\"Expiration\":\"" + expiration + "\"}";
|
||||
ctx.response().setStatusCode(200)
|
||||
.putHeader("content-type", "application/json")
|
||||
.end(body);
|
||||
SessionCredential session = result.get();
|
||||
ctx.response().putHeader("content-type", "application/json").end(new JsonObject()
|
||||
.put("Code", "Success")
|
||||
.put("LastUpdated", ISO.format(session.getExpiration().minusSeconds(3600)))
|
||||
.put("Type", "AWS-HMAC")
|
||||
.put("AccessKeyId", session.getAccessKeyId())
|
||||
.put("SecretAccessKey", session.getSecretAccessKey())
|
||||
.put("Token", session.getSessionToken())
|
||||
.put("Expiration", ISO.format(session.getExpiration())).encode());
|
||||
}
|
||||
|
||||
private void handleInstanceTagKeys(RoutingContext ctx) {
|
||||
@@ -404,31 +407,6 @@ public class Ec2MetadataServer {
|
||||
|
||||
// ── Utilities ─────────────────────────────────────────────────────────────
|
||||
|
||||
String resolveRoleName(String profileArn) {
|
||||
if (iamService != null) {
|
||||
String profileName = extractProfileName(profileArn);
|
||||
try {
|
||||
var profile = iamService.getInstanceProfile(profileName);
|
||||
if (profile.getRoleNames() != null && !profile.getRoleNames().isEmpty()) {
|
||||
return profile.getRoleNames().getFirst();
|
||||
}
|
||||
} catch (AwsException e) {
|
||||
LOG.debugf(e, "IMDS: instance profile %s unavailable; falling back to profile name", profileName);
|
||||
// Fall back to the profile name when only the EC2 profile ARN was modeled.
|
||||
}
|
||||
}
|
||||
return extractProfileName(profileArn);
|
||||
}
|
||||
|
||||
private static String extractProfileName(String profileArn) {
|
||||
// arn:aws:iam::000000000000:instance-profile/my-role
|
||||
int lastSlash = profileArn.lastIndexOf('/');
|
||||
if (lastSlash >= 0 && lastSlash < profileArn.length() - 1) {
|
||||
return profileArn.substring(lastSlash + 1);
|
||||
}
|
||||
return "instance-role";
|
||||
}
|
||||
|
||||
private static String now() {
|
||||
return ISO.format(Instant.now());
|
||||
}
|
||||
|
||||
@@ -1424,6 +1424,13 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
return profile;
|
||||
}
|
||||
|
||||
public Optional<InstanceProfile> findInstanceProfile(String accountId, String profileName) {
|
||||
if (instanceProfiles instanceof AccountAwareStorageBackend<InstanceProfile> aware) {
|
||||
return aware.getForAccount(accountId, profileName);
|
||||
}
|
||||
return instanceProfiles.get(profileName);
|
||||
}
|
||||
|
||||
public InstanceProfile getInstanceProfile(String instanceProfileName) {
|
||||
return instanceProfiles.get(instanceProfileName)
|
||||
.orElseThrow(() -> new AwsException("NoSuchEntity",
|
||||
@@ -2020,6 +2027,33 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
sessionAccessKeyId, accountId, roleArn);
|
||||
}
|
||||
|
||||
/** Registers an IMDS session in the profile's account, outside request scope. */
|
||||
public void registerEc2InstanceSession(SessionCredential session) {
|
||||
if (session.getOriginAccountId() == null || session.getOriginAccountId().isBlank()
|
||||
|| session.getEc2InstanceId() == null || session.getEc2InstanceId().isBlank()) {
|
||||
throw new IllegalArgumentException("EC2 session account and instance ID must not be blank");
|
||||
}
|
||||
if (sessions instanceof AccountAwareStorageBackend<SessionCredential> aware) {
|
||||
aware.putForAccount(session.getOriginAccountId(), session.getAccessKeyId(), session);
|
||||
} else {
|
||||
sessions.put(session.getAccessKeyId(), session);
|
||||
}
|
||||
}
|
||||
|
||||
/** IMDS registrations are rebuilt on startup; discard credentials from the previous server. */
|
||||
public int sweepOrphanedEc2InstanceSessions() {
|
||||
List<SessionCredential> stored = sessions instanceof AccountAwareStorageBackend<SessionCredential> aware
|
||||
? aware.scanAllAccounts() : sessions.scan(key -> true);
|
||||
int removed = 0;
|
||||
for (SessionCredential session : stored) {
|
||||
if (session.getEc2InstanceId() != null) {
|
||||
deleteSession(session.getAccessKeyId(), session);
|
||||
removed++;
|
||||
}
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
|
||||
/** Removes a session from an explicit account namespace. */
|
||||
public void unregisterSession(String accountId, String sessionAccessKeyId) {
|
||||
if (sessionAccessKeyId == null || sessionAccessKeyId.isBlank()) {
|
||||
@@ -2190,7 +2224,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
}
|
||||
String roleName = roleArn.contains("/") ? roleArn.substring(roleArn.lastIndexOf('/') + 1) : "UnknownRole";
|
||||
String accountId = AwsArnUtils.accountOrDefault(roleArn, regionResolver.getAccountId());
|
||||
return Optional.of(AwsArnUtils.Arn.of("sts", "", accountId, "assumed-role/" + roleName + "/floci-session").toString());
|
||||
return Optional.of(AwsArnUtils.Arn.of("sts", "", accountId, "assumed-role/" + roleName + "/"
|
||||
+ (session.getEc2InstanceId() != null ? session.getEc2InstanceId() : "floci-session")).toString());
|
||||
}
|
||||
|
||||
return Optional.empty();
|
||||
|
||||
@@ -23,6 +23,7 @@ public class SessionCredential {
|
||||
private String originAccountId;
|
||||
/** True when this session belongs to a Floci-launched Lambda container. */
|
||||
private boolean lambdaExecutionRole;
|
||||
private String ec2InstanceId;
|
||||
|
||||
public SessionCredential() {}
|
||||
|
||||
@@ -91,6 +92,9 @@ public class SessionCredential {
|
||||
public String getOriginAccountId() { return originAccountId; }
|
||||
public void setOriginAccountId(String originAccountId) { this.originAccountId = originAccountId; }
|
||||
|
||||
public String getEc2InstanceId() { return ec2InstanceId; }
|
||||
public void setEc2InstanceId(String ec2InstanceId) { this.ec2InstanceId = ec2InstanceId; }
|
||||
|
||||
public boolean isLambdaExecutionRole() { return lambdaExecutionRole; }
|
||||
public void setLambdaExecutionRole(boolean lambdaExecutionRole) { this.lambdaExecutionRole = lambdaExecutionRole; }
|
||||
}
|
||||
Reference in new issue
Block a user