fix(iam): check iam:PassRole when Lambda or EC2 is passed a role (#5938)

Under IAM enforcement no request was checked for iam:PassRole. A user
allowed only lambda:CreateFunction, or ec2:RunInstances, could give the
function or the instance any role in the account, and Floci runs the
function with that role and serves the instance its credentials, so the
user could act with the role's permissions.

A request that passes a role to Lambda or EC2 now also needs
iam:PassRole on that role, as the IAM user guide requires: "To pass a
role (and its permissions) to an AWS service, a user must have
permissions to pass the role to the service." The check offers
iam:PassedToService, the service AWS's Service Reference names for the
operation, so a grant to pass a role to one service does not cover
another. It covers Lambda's CreateFunction, UpdateFunctionConfiguration
when it sets the role, CreateWebFunction and CreateWebFunctionRevision,
and EC2's RunInstances, RequestSpotInstances,
AssociateIamInstanceProfile, ReplaceIamInstanceProfileAssociation,
CreateLaunchTemplate and CreateLaunchTemplateVersion, which pass the
roles of the instance profile they name, and CreateFlowLogs. A Spot
Instance request now takes its instance profile by name as well as by
ARN, as RunInstances does, so the role checked is the one the instance
gets.

Launching from a launch template checks nothing, as on AWS: the EC2 user
guide warns that whoever can create a template version can pass its
role without iam:PassRole. The role parameters of other services are
left for later changes.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-18 20:43:15 -05:00
1 parent 494a6725a1
commit f0975a9f47
6 files changed
+513 -4

No files matched your search

@@ -61,7 +61,7 @@ public class IamConditionContextResolver {
private static final Logger LOG = Logger.getLogger(IamConditionContextResolver.class);
/** Set by {@code ResourceArnBuilder.readJsonBody}, which runs earlier in the same filter pass. */
private static final String BUFFERED_JSON_BODY = "floci.bufferedJsonBody";
static final String BUFFERED_JSON_BODY = "floci.bufferedJsonBody";
private static final String BUFFERED_FORM_BODY = "floci.bufferedFormBody";
private static final String REQUEST_TAG_PREFIX = "aws:RequestTag/";
private static final String RESOURCE_TAG_PREFIX = "aws:ResourceTag/";
@@ -657,7 +657,7 @@ public class IamConditionContextResolver {
* resource this context describes is the resource the handler acts on.
*/
@SuppressWarnings("unchecked")
private static Map<String, String> formParameters(ContainerRequestContext ctx) {
static Map<String, String> formParameters(ContainerRequestContext ctx) {
Object cached = ctx.getProperty(BUFFERED_FORM_BODY);
if (cached instanceof Map<?, ?> map) {
return (Map<String, String>) map;
@@ -688,7 +688,7 @@ public class IamConditionContextResolver {
}
/** Reads the entity fully and puts an equivalent stream back for downstream readers. */
private static byte[] bufferEntity(ContainerRequestContext ctx) {
static byte[] bufferEntity(ContainerRequestContext ctx) {
InputStream in = ctx.getEntityStream();
if (in == null) {
return null;
@@ -18,6 +18,7 @@ import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider;
import io.github.hectorvent.floci.services.iam.ResourcePolicyProviders;
import io.github.hectorvent.floci.services.iam.ScpProvider;
import io.github.hectorvent.floci.services.iam.model.CallerContext;
import io.github.hectorvent.floci.services.iam.model.IamRole;
import io.github.hectorvent.floci.services.s3.S3ObjectActions;
import io.quarkus.vertx.http.runtime.CurrentVertxRequest;
import io.vertx.core.http.HttpServerRequest;
@@ -521,6 +522,10 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
region, accountId, akid)) {
return;
}
if (abortIfRolePassDenied(ctx, caller, principal, callerArns.orElse(null), action, credentialScope,
region, accountId, akid)) {
return;
}
// Tagged group creation requires either tagging permission, using the same resolved
// caller (including session, boundary and SCP ceilings) as the primary operation.
@@ -861,6 +866,44 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
return CallerArns.accountRoot(rootArn, accountId);
}
/**
* A request that passes a role to a service also needs {@code iam:PassRole} on that role (see
* {@link PassedRoles}), checked as the caller with {@code iam:PassedToService} naming the
* service and the keys that say who is calling, which {@code callerArns} writes when it is known.
* An instance profile is looked up in the request's account, as EC2 resolves it; one that does
* not exist passes nothing, and the operation reports it. Returns true when the request was
* aborted.
*/
private boolean abortIfRolePassDenied(ContainerRequestContext ctx, CallerContext caller, RequestPrincipal principal,
CallerArns callerArns, String action, String credentialScope,
String region, String accountId, String akid) {
for (PassedRoles.PassedRole passed : PassedRoles.of(action, ctx,
(name, arn) -> instanceProfileRoleArns(accountId, name, arn))) {
Map<String, List<String>> context = new HashMap<>();
if (callerArns != null) {
callerArns.putPrincipalKeys(context);
}
context.put("iam:PassedToService", List.of(passed.passedToService()));
if (abortIfDenied(ctx, caller, principal, "iam:PassRole", action, credentialScope,
List.of(passed.roleArn()), List.of(context), region, accountId, akid)) {
return true;
}
}
return false;
}
/** The ARNs of the roles the instance profile, named by {@code name} or {@code arn}, holds. */
private List<String> instanceProfileRoleArns(String accountId, String name, String arn) {
String profileName = arn != null ? arn.substring(arn.lastIndexOf('/') + 1) : name;
return iamService.findInstanceProfile(accountId, profileName)
.filter(profile -> arn == null || arn.equals(profile.getArn()))
.map(profile -> profile.getRoleNames().stream()
.flatMap(roleName -> iamService.findRole(accountId, roleName).stream())
.map(IamRole::getArn)
.toList())
.orElse(List.of());
}
/**
* Evaluates one action against every resource and target context, aborting the request with
* AccessDenied on the first DENY. Returns true when the request was aborted.
@@ -0,0 +1,129 @@
package io.github.hectorvent.floci.core.common;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.ws.rs.container.ContainerRequestContext;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
/**
* The IAM roles a request passes to a service, which the caller also needs {@code iam:PassRole} on.
* The IAM user guide: "To pass a role (and its permissions) to an AWS service, a user must have
* permissions to pass the role to the service." AWS's Service Reference names, for each operation
* that passes one, the service the role goes to, which the check offers as {@code iam:PassedToService};
* where the request carries the role differs per operation and is listed here.
*
* <p>An EC2 request names an instance profile rather than a role, and passes the roles the profile
* holds. Launching from a launch template passes nothing here: the EC2 user guide warns that a user
* who can create launch template versions "can potentially update a launch template to pass an IAM
* role to an instance even if they don't have the iam:PassRole permission", so the role is checked
* where the template is created.
*/
final class PassedRoles {
private static final Logger LOG = Logger.getLogger(PassedRoles.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
/** An IAM role ARN, the only resource {@code iam:PassRole} acts on. */
private static final Pattern ROLE_ARN = Pattern.compile("^arn:[a-z0-9-]+:iam::\\d{12}:role/.+");
private static final String LAMBDA = ServicePrincipals.of("lambda");
private static final String EC2 = ServicePrincipals.of("ec2");
private static final String VPC_FLOW_LOGS = ServicePrincipals.of("vpc-flow-logs");
/** A role a request passes, and the service principal it is passed to. */
record PassedRole(String roleArn, String passedToService) {
}
/** The ARNs of the roles an EC2 instance profile holds, looked up by its name or its ARN. */
@FunctionalInterface
interface InstanceProfileRoles {
List<String> roleArns(String profileName, String profileArn);
}
private PassedRoles() {
}
/** The roles a request for {@code action} passes; empty when the operation passes none or the request names none. */
static List<PassedRole> of(String action, ContainerRequestContext ctx, InstanceProfileRoles profiles) {
return switch (action) {
case "lambda:CreateFunction", "lambda:UpdateFunctionConfiguration" -> fromJson(ctx, LAMBDA, "Role");
case "lambda:CreateWebFunction" ->
fromJson(ctx, LAMBDA, "revisionConfig", "serviceConfig", "executionRoleArn");
case "lambda:CreateWebFunctionRevision" -> fromJson(ctx, LAMBDA, "serviceConfig", "executionRoleArn");
case "ec2:RunInstances", "ec2:AssociateIamInstanceProfile", "ec2:ReplaceIamInstanceProfileAssociation" ->
fromInstanceProfile(ctx, profiles, "IamInstanceProfile");
case "ec2:RequestSpotInstances" ->
fromInstanceProfile(ctx, profiles, "LaunchSpecification.IamInstanceProfile");
case "ec2:CreateLaunchTemplate", "ec2:CreateLaunchTemplateVersion" ->
fromInstanceProfile(ctx, profiles, "LaunchTemplateData.IamInstanceProfile");
case "ec2:CreateFlowLogs" -> fromForm(ctx, VPC_FLOW_LOGS, "DeliverLogsPermissionArn");
default -> List.of();
};
}
private static List<PassedRole> fromJson(ContainerRequestContext ctx, String service, String... path) {
JsonNode node = jsonBody(ctx);
for (String member : path) {
node = node == null ? null : node.get(member);
}
return node != null && node.isTextual() ? passed(List.of(node.asText()), service) : List.of();
}
private static List<PassedRole> fromForm(ContainerRequestContext ctx, String service, String parameter) {
String roleArn = IamConditionContextResolver.formParameters(ctx).get(parameter);
return roleArn == null ? List.of() : passed(List.of(roleArn), service);
}
/** The roles of the instance profile named by {@code prefix}.Name or {@code prefix}.Arn. */
private static List<PassedRole> fromInstanceProfile(ContainerRequestContext ctx, InstanceProfileRoles profiles,
String prefix) {
Map<String, String> form = IamConditionContextResolver.formParameters(ctx);
String name = blankToNull(form.get(prefix + ".Name"));
String arn = blankToNull(form.get(prefix + ".Arn"));
if (name == null && arn == null) {
return List.of();
}
return passed(profiles.roleArns(name, arn), EC2);
}
/** The roles that are IAM role ARNs; anything else is left for the operation to refuse. */
private static List<PassedRole> passed(List<String> roleArns, String service) {
List<PassedRole> passed = new ArrayList<>();
for (String roleArn : roleArns) {
if (roleArn != null && ROLE_ARN.matcher(roleArn).matches()) {
passed.add(new PassedRole(roleArn, service));
}
}
return passed;
}
/** The request's JSON body, read once and kept where the other request readers look for it. */
private static JsonNode jsonBody(ContainerRequestContext ctx) {
if (ctx.getProperty(IamConditionContextResolver.BUFFERED_JSON_BODY) instanceof JsonNode cached) {
return cached;
}
byte[] body = IamConditionContextResolver.bufferEntity(ctx);
if (body == null || body.length == 0) {
return null;
}
try {
JsonNode node = MAPPER.readTree(body);
ctx.setProperty(IamConditionContextResolver.BUFFERED_JSON_BODY, node);
return node;
} catch (IOException e) {
// The operation answers a body it cannot parse itself; nothing here names a role.
LOG.debugv(e, "Request body is not JSON, so it passes no role");
return null;
}
}
private static String blankToNull(String value) {
return value == null || value.isBlank() ? null : value;
}
}
@@ -6308,10 +6308,11 @@ public class Ec2QueryHandler {
userDataEncoded = null;
}
String userData = Ec2UserDataDecoder.decode(userDataEncoded);
String iamInstanceProfileArn = p.getFirst("LaunchSpecification.IamInstanceProfile.Arn");
List<Tag> spotRequestTags = parseTagsForResource(p, "spot-instances-request");
List<Tag> instanceTags = parseTagsForResource(p, "instance");
// The profile is named by ARN or by name, as for RunInstances.
String iamInstanceProfileArn = resolveIamInstanceProfileArn(p, "LaunchSpecification.IamInstanceProfile");
List<SpotInstanceRequest> requests = service.requestSpotInstances(region, spotPrice, instanceCount,
type, productDescription, imageId, instanceType, keyName, subnetId, securityGroupIds, userData, iamInstanceProfileArn,