mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
feat(lambdaweb): reject resource policies whose principal does not exist (#6769)
* feat(lambdaweb): reject resource policies whose principal does not exist PutResourcePolicy now looks up every AWS principal a policy names, as Lambda does before it stores the policy. A role or user ARN has to name one IAM holds in that account, under its own path, and a unique id one in the function's account. A missing principal, an assumed-role session, a CanonicalUser or an ARN in another partition gets the invalid principal message, and a role or user named under another path gets the message that the ARN does not match the actual one. The principals are looked up after every statement passes its other checks and before any statement is refused as public, which is the order AWS checks them in. * docs(lambdaweb): drop the principal check from the items not implemented yet * refactor(lambdaweb): find policy principals through IamService and the resolver's partition IamService.heldPrincipalArn now gives the ARN IAM holds what a principal ARN names under, the root as given or the role or user at its own path. DSQL's principal check and Lambda Web's use it, and Lambda Web keeps only the path comparison and its messages. Lambda Web takes the partition from RegionResolver.partitionForRegion, so a custom region falls back to the deployment's partition.
This commit is contained in:
1 parent
02cc40bb40
commit
701b04c410
8 files changed
+271
-20
No files matched your search
@@ -1,6 +1,5 @@
|
||||
package io.github.hectorvent.floci.services.dsql;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.IamConditionContextResolver;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.RequestContext;
|
||||
@@ -64,16 +63,7 @@ public class DsqlPrincipals {
|
||||
* account's root always does; a role or a user is looked up in its account by its name.
|
||||
*/
|
||||
public boolean exists(String arn) {
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
||||
String resource = parsed.resource();
|
||||
String name = resource.substring(resource.lastIndexOf('/') + 1);
|
||||
if (resource.startsWith("role/")) {
|
||||
return iamService.findRole(parsed.accountId(), name).isPresent();
|
||||
}
|
||||
if (resource.startsWith("user/")) {
|
||||
return iamService.findUser(parsed.accountId(), name).isPresent();
|
||||
}
|
||||
return "root".equals(resource);
|
||||
return iamService.heldPrincipalArn(arn).isPresent();
|
||||
}
|
||||
|
||||
private String accessKeyId() {
|
||||
|
||||
@@ -1337,6 +1337,38 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
return requested.region().isEmpty() && requested.resource().equals(expectedResource);
|
||||
}
|
||||
|
||||
/**
|
||||
* The ARN IAM holds what an IAM principal ARN names under: the account root as given, or the role or user
|
||||
* of the name the ARN ends with in the ARN's account, at its own path. Empty for any other ARN, and for a
|
||||
* role or user IAM does not hold.
|
||||
*/
|
||||
public Optional<String> heldPrincipalArn(String principalArn) {
|
||||
if (!AwsArnUtils.isArn(principalArn)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
AwsArnUtils.Arn arn = AwsArnUtils.parse(principalArn);
|
||||
String resource = arn.resource();
|
||||
if (!"iam".equals(arn.service())) {
|
||||
return Optional.empty();
|
||||
}
|
||||
if ("root".equals(resource)) {
|
||||
return Optional.of(principalArn);
|
||||
}
|
||||
String name = resource.substring(resource.lastIndexOf('/') + 1);
|
||||
if (resource.startsWith("role/")) {
|
||||
return findRole(arn.accountId(), name).map(role -> heldArn(arn, "role", role.getPath(), role.getRoleName()));
|
||||
}
|
||||
if (resource.startsWith("user/")) {
|
||||
return findUser(arn.accountId(), name).map(user -> heldArn(arn, "user", user.getPath(), user.getUserName()));
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
private static String heldArn(AwsArnUtils.Arn named, String type, String path, String name) {
|
||||
return AwsArnUtils.Arn.global(named.partition(), "iam", named.accountId(), type + normalizePath(path) + name)
|
||||
.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* AWS publishes UnmodifiableEntity on twelve role actions, and its message names the linked
|
||||
* service the caller has to go through instead. This guards the ten of them that refuse a
|
||||
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
package io.github.hectorvent.floci.services.lambdaweb;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Whether the principals of a resource policy exist, as Lambda checks them before it stores the policy. A role
|
||||
* or a user is looked up in the account its ARN names, or in the function's account by its unique id, and an ARN
|
||||
* that names one under another path is refused on its own. Floci holds every account, so an account id or its
|
||||
* root always exists, and it keeps no list of service principals, so those are not checked.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class LambdaWebPolicyPrincipals {
|
||||
|
||||
private static final String OTHER_ARN = "The principal arn provided does not match the actual principal arn."
|
||||
+ " Please check your input and try again.";
|
||||
private static final Pattern ACCOUNT_ID = Pattern.compile("[0-9]{12}");
|
||||
|
||||
private final IamService iamService;
|
||||
|
||||
@Inject
|
||||
public LambdaWebPolicyPrincipals(IamService iamService) {
|
||||
this.iamService = iamService;
|
||||
}
|
||||
|
||||
/** Refuses the statement's {@code principal} when one it names does not exist in {@code partition}. */
|
||||
void requireExisting(String partition, JsonNode principal) {
|
||||
if (!principal.isObject()) {
|
||||
return;
|
||||
}
|
||||
if (principal.has("CanonicalUser")) {
|
||||
throw invalid();
|
||||
}
|
||||
JsonNode aws = principal.get("AWS");
|
||||
if (aws == null) {
|
||||
return;
|
||||
}
|
||||
List<String> values = new ArrayList<>();
|
||||
if (aws.isTextual()) {
|
||||
values.add(aws.textValue());
|
||||
} else {
|
||||
aws.forEach(value -> values.add(value.textValue()));
|
||||
}
|
||||
for (String value : values) {
|
||||
requireExisting(partition, value);
|
||||
}
|
||||
}
|
||||
|
||||
private void requireExisting(String partition, String value) {
|
||||
if ("*".equals(value) || ACCOUNT_ID.matcher(value).matches()) {
|
||||
return;
|
||||
}
|
||||
if (!AwsArnUtils.isArn(value)) {
|
||||
if (!heldUniqueId(value)) {
|
||||
throw invalid();
|
||||
}
|
||||
return;
|
||||
}
|
||||
AwsArnUtils.Arn arn = AwsArnUtils.parse(value);
|
||||
if (!arn.partition().equals(partition) || !arn.region().isEmpty()
|
||||
|| !ACCOUNT_ID.matcher(arn.accountId()).matches()) {
|
||||
throw invalid();
|
||||
}
|
||||
if ("iam".equals(arn.service())) {
|
||||
String held = iamService.heldPrincipalArn(value).orElseThrow(LambdaWebPolicyPrincipals::invalid);
|
||||
if (!AwsArnUtils.parse(held).resource().equals(arn.resource())) {
|
||||
throw new AwsException("ValidationException", OTHER_ARN, 400);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if ("sts".equals(arn.service()) && arn.resource().startsWith("federated-user/")) {
|
||||
return;
|
||||
}
|
||||
throw invalid();
|
||||
}
|
||||
|
||||
/** A role's or a user's unique id, as IAM gives it to one in the function's account. */
|
||||
private boolean heldUniqueId(String id) {
|
||||
return iamService.listRoles("/").stream().anyMatch(role -> id.equals(role.getRoleId()))
|
||||
|| iamService.listUsers("/").stream().anyMatch(user -> id.equals(user.getUserId()));
|
||||
}
|
||||
|
||||
private static AwsException invalid() {
|
||||
return new AwsException("ValidationException", LambdaWebService.INVALID_PRINCIPAL, 400);
|
||||
}
|
||||
}
|
||||
@@ -103,7 +103,7 @@ public class LambdaWebService implements Resettable {
|
||||
"Sid", "Effect", "Principal", "NotPrincipal", "Action", "NotAction", "Resource", "NotResource", "Condition");
|
||||
private static final Set<String> PRINCIPAL_KEYS = Set.of("AWS", "Service", "Federated", "CanonicalUser");
|
||||
private static final String POLICY_SYNTAX = "Policy has syntax errors.";
|
||||
private static final String INVALID_PRINCIPAL = "The provided principal was invalid. Please check the principal and try again.";
|
||||
static final String INVALID_PRINCIPAL = "The provided principal was invalid. Please check the principal and try again.";
|
||||
private static final String NOT_A_ZIP = "Failed to read zip file: zip: not a valid zip file";
|
||||
private static final String INVALID_TAGS = "One or more of your tags are invalid. Please ensure none of your tag keys"
|
||||
+ " start with \"aws:\", none are empty, and there are no duplicate tag keys.";
|
||||
@@ -153,6 +153,7 @@ public class LambdaWebService implements Resettable {
|
||||
private final LambdaWebExecutionRole executionRole;
|
||||
private final ServiceCallAuthorizer serviceCalls;
|
||||
private final LambdaMicrovmsService microvmsService;
|
||||
private final LambdaWebPolicyPrincipals policyPrincipals;
|
||||
|
||||
/** Keyed {@code region/functionName}. The backend adds the caller's account to every key. */
|
||||
private StorageBackend<String, WebFunction> functions;
|
||||
@@ -166,7 +167,8 @@ public class LambdaWebService implements Resettable {
|
||||
public LambdaWebService(RegionResolver regionResolver, StorageFactory storageFactory, EmulatorConfig config,
|
||||
S3Service s3Service, LambdaWebCode code, ObjectMapper objectMapper,
|
||||
Instance<RequestContext> requestContext, LambdaWebExecutionRole executionRole,
|
||||
ServiceCallAuthorizer serviceCalls, LambdaMicrovmsService microvmsService) {
|
||||
ServiceCallAuthorizer serviceCalls, LambdaMicrovmsService microvmsService,
|
||||
LambdaWebPolicyPrincipals policyPrincipals) {
|
||||
this.regionResolver = regionResolver;
|
||||
this.storageFactory = storageFactory;
|
||||
this.config = config;
|
||||
@@ -177,6 +179,7 @@ public class LambdaWebService implements Resettable {
|
||||
this.executionRole = executionRole;
|
||||
this.serviceCalls = serviceCalls;
|
||||
this.microvmsService = microvmsService;
|
||||
this.policyPrincipals = policyPrincipals;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
@@ -1332,7 +1335,7 @@ public class LambdaWebService implements Resettable {
|
||||
.length("policy", policy, 1, 20480)
|
||||
.pattern("revisionId", revisionId, POLICY_REVISION_ID)
|
||||
.throwIfAny();
|
||||
validatePolicy(policy, resourceArn);
|
||||
validatePolicy(region, policy, resourceArn);
|
||||
String functionName = resolveFunctionName(region, resourceArn, "PutResourcePolicy");
|
||||
synchronized (lockFor(region, functionName)) {
|
||||
WebFunction fn = function(region, functionName);
|
||||
@@ -1381,8 +1384,12 @@ public class LambdaWebService implements Resettable {
|
||||
return new AwsException("ResourceNotFoundException", "The function does not have a policy.", 404);
|
||||
}
|
||||
|
||||
/** The checks AWS runs on a policy document before it looks the function up. */
|
||||
private void validatePolicy(String policy, String functionArn) {
|
||||
/**
|
||||
* The checks AWS runs on a policy document before it looks the function up. Every statement passes its own
|
||||
* checks before any principal is looked up, and every principal exists before any statement is refused as
|
||||
* public.
|
||||
*/
|
||||
private void validatePolicy(String region, String policy, String functionArn) {
|
||||
JsonNode document;
|
||||
try {
|
||||
document = objectMapper.readTree(policy);
|
||||
@@ -1405,6 +1412,12 @@ public class LambdaWebService implements Resettable {
|
||||
for (JsonNode statement : each) {
|
||||
validateStatement(statement, functionArn);
|
||||
}
|
||||
for (JsonNode statement : each) {
|
||||
policyPrincipals.requireExisting(regionResolver.partitionForRegion(region), statement.get("Principal"));
|
||||
}
|
||||
for (JsonNode statement : each) {
|
||||
requireNotPublic(statement);
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateStatement(JsonNode statement, String functionArn) {
|
||||
@@ -1439,7 +1452,10 @@ public class LambdaWebService implements Resettable {
|
||||
throw policySyntax();
|
||||
}
|
||||
}
|
||||
if (effect.equalsIgnoreCase("Allow") && isWildcardPrincipal(principal)
|
||||
}
|
||||
|
||||
private static void requireNotPublic(JsonNode statement) {
|
||||
if (statement.path("Effect").asText().equalsIgnoreCase("Allow") && isWildcardPrincipal(statement.get("Principal"))
|
||||
&& !hasTrustedCondition(statement.path("Condition"))) {
|
||||
throw new AwsException("ValidationException", "Lambda blocked the creation of this policy"
|
||||
+ " because it would grant public access to your function.", 400);
|
||||
|
||||
Reference in new issue
Block a user