mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
feat(iam): resolve policy variables in Resource patterns and Condition values (#5639)
A ${...} in a Resource pattern or a Condition value was matched as the text it
is written as, so a statement scoped to arn:aws:iam::*:user/${aws:username}
matched no user at all. AWS's own IAMUserChangePassword policy is written that
way and floci vendors it verbatim, so under enforcement it authorized nothing,
and it is not alone: 244 of the 1586 vendored managed policy documents carry a
variable, and of the 1635 occurrences in them 1443 sit in a Condition value
and 192 in a Resource. The Condition share is where the loss bites hardest,
since a variable that cannot resolve quietly drops a Deny that AWS honours.
The keys a variable resolves against arrived with #5568, which put
aws:username, aws:userid and aws:PrincipalType into the request context. This
is the other half of that work: without substitution the keys answer nobody,
and without the keys substitution has nothing to find.
Variables now resolve wherever the evaluator matches a statement, which covers
every document it reads: identity policies, resource policies, session
policies, permissions boundaries, SCPs, and the Condition of a role trust
policy, whose own Version now reaches the condition check. A trust policy is
the narrow case, since sts:AssumeRole is authorized before there is a session
to describe: that context carries aws:PrincipalArn, the account and region
keys, sts:RoleSessionName and sts:ExternalId, so a variable naming
aws:username, aws:userid or aws:PrincipalType finds nothing there, which
iam.md now says.
Two of the rules are easy to miss. Substitution is gated on "Version":
"2012-10-17", because under the older 2008-10-17, which is also the default
when the element is absent, the user guide says variables "are instead treated
as literal strings in the policy"; the version therefore rides on each parsed
statement, since statements from many documents are evaluated as one list. And
a variable with no value is not an empty string: in Resource the pattern "will
not match any resource", in NotResource that same rule excludes nothing, and
in a Condition the positive operators do not match while the inverted ones do,
which is what makes the Deny AWS documents for an unset principal tag fire.
The rest, also from the user guide: a variable resolves only in the resource
portion of an ARN, after the fifth colon; only with the string and ARN
condition operators, never Numeric, Date, Bool, IpAddress or Null; only for a
single-valued key, a multivalued one having no one value to stand in, which a
default does not rescue, since a default answers a key with no value rather
than one with several; and case-insensitively by key name, a name that holds
no space, the guide allowing one inside a quoted default and nowhere else. A
spaced name, an empty ${}, a missing brace and an unquoted default are the
forms the guide's policy checks call errors, and each stays the text it is.
${*}, ${?} and ${$} stand for a literal character, so the glob gained an
escape marker, honoured only on a pattern that came back from substitution and
stripped from whatever arrived in the policy: a document can write the marker
as a JSON escape, and reading it as one would turn a wildcard of the
document's own into a literal character and narrow the statement it sits in. A
resolved value is not escaped, matching AWS, whose policy checks warn that
variables "can be evaluated as effective wildcards".
Verified at this commit: 7442 tests across the 439 IAM, core, enforcement and
resource-policy classes the evaluator is reached from, Checkstyle and
docs-check clean. AWS's own IAMUserChangePassword document is attached to a
user and called on the request path, both of its patterns included, the second
scoping a user under a path. Each rule was probed by reverting it alone, which
is how two weak tests were found: a valueless variable beside a wildcard and
the operator restriction both needed a case whose answer flips. The escape
marker is probed from both sides, by letting the resolver keep one that
arrived in a policy and by honouring markers on every pattern rather than only
a substituted one, and each side fails a different case of the same test.
This commit is contained in:
1 parent
a55352bf9d
commit
425cd3167d
8 files changed
+1213
-58
No files matched your search
+21
-14
@@ -21,9 +21,10 @@ import java.util.regex.Pattern;
|
||||
* <p>Trust policies are principal-centric and carry no {@code Resource} element, so they cannot be
|
||||
* evaluated by {@link IamPolicyEvaluator} (which is identity/resource oriented). This focused
|
||||
* evaluator matches each statement's {@code Action} and {@code Principal} against the caller, hands
|
||||
* its {@code Condition} to {@link IamPolicyEvaluator#conditionMatches} with the request's context,
|
||||
* and applies AWS precedence: an explicit {@code Deny} wins, otherwise a matching {@code Allow}
|
||||
* grants.
|
||||
* its {@code Condition} to {@link IamPolicyEvaluator#conditionMatches} with the request's context
|
||||
* and the document's own {@code Version}, which is what decides whether a {@code ${...}} in a
|
||||
* condition value is a policy variable, and applies AWS precedence: an explicit {@code Deny} wins,
|
||||
* otherwise a matching {@code Allow} grants.
|
||||
*
|
||||
* <p>Only AWS principals are modeled (account-root, bare account id, exact principal ARN, and
|
||||
* {@code "*"}); {@code Service} and {@code Federated} principals never match a SigV4 caller and are
|
||||
@@ -94,16 +95,18 @@ public class AssumeRolePolicyEvaluator {
|
||||
if (trustPolicyDocument == null || trustPolicyDocument.isBlank()) {
|
||||
return TrustDecision.NEUTRAL;
|
||||
}
|
||||
JsonNode statements;
|
||||
JsonNode root;
|
||||
try {
|
||||
statements = objectMapper.readTree(trustPolicyDocument).path("Statement");
|
||||
root = objectMapper.readTree(trustPolicyDocument);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Failed to parse trust policy: {0}", e.getMessage());
|
||||
return TrustDecision.NEUTRAL;
|
||||
}
|
||||
JsonNode statements = root.path("Statement");
|
||||
if (!isWellFormed(statements)) {
|
||||
return TrustDecision.NEUTRAL;
|
||||
}
|
||||
String version = root.path("Version").asText(null);
|
||||
Map<String, List<String>> context = new HashMap<>(requestContext);
|
||||
if (principalArn != null) {
|
||||
context.put("aws:PrincipalArn", List.of(principalArn));
|
||||
@@ -111,7 +114,8 @@ public class AssumeRolePolicyEvaluator {
|
||||
Iterable<JsonNode> statementList = statements.isArray() ? statements : List.of(statements);
|
||||
TrustDecision decision = TrustDecision.NEUTRAL;
|
||||
for (JsonNode stmt : statementList) {
|
||||
TrustDecision match = evaluateStatement(stmt, callerArn, principalArn, callerAccount, context);
|
||||
TrustDecision match =
|
||||
evaluateStatement(stmt, callerArn, principalArn, callerAccount, context, version);
|
||||
if (match == TrustDecision.EXPLICIT_DENY) {
|
||||
return TrustDecision.EXPLICIT_DENY;
|
||||
}
|
||||
@@ -165,16 +169,18 @@ public class AssumeRolePolicyEvaluator {
|
||||
if (trustPolicyDocument == null || trustPolicyDocument.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
JsonNode statements;
|
||||
JsonNode root;
|
||||
try {
|
||||
statements = objectMapper.readTree(trustPolicyDocument).path("Statement");
|
||||
root = objectMapper.readTree(trustPolicyDocument);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Failed to parse trust policy: {0}", e.getMessage());
|
||||
return false;
|
||||
}
|
||||
JsonNode statements = root.path("Statement");
|
||||
if (!isWellFormed(statements)) {
|
||||
return false;
|
||||
}
|
||||
String version = root.path("Version").asText(null);
|
||||
Map<String, List<String>> context = new HashMap<>();
|
||||
if (sourceArn != null) {
|
||||
context.put("aws:SourceArn", List.of(sourceArn));
|
||||
@@ -185,14 +191,14 @@ public class AssumeRolePolicyEvaluator {
|
||||
boolean allow = false;
|
||||
if (statements.isArray()) {
|
||||
for (JsonNode statement : statements) {
|
||||
switch (evaluateServiceStatement(statement, servicePrincipal, context)) {
|
||||
switch (evaluateServiceStatement(statement, servicePrincipal, context, version)) {
|
||||
case DENY -> { return false; }
|
||||
case ALLOW -> allow = true;
|
||||
case NO_MATCH -> { }
|
||||
}
|
||||
}
|
||||
} else if (statements.isObject()) {
|
||||
return evaluateServiceStatement(statements, servicePrincipal, context) == Match.ALLOW;
|
||||
return evaluateServiceStatement(statements, servicePrincipal, context, version) == Match.ALLOW;
|
||||
}
|
||||
return allow;
|
||||
}
|
||||
@@ -244,7 +250,8 @@ public class AssumeRolePolicyEvaluator {
|
||||
}
|
||||
|
||||
private TrustDecision evaluateStatement(JsonNode stmt, String callerArn, String principalArn,
|
||||
String callerAccount, Map<String, List<String>> context) {
|
||||
String callerAccount, Map<String, List<String>> context,
|
||||
String policyVersion) {
|
||||
if (!actionApplies(stmt)) {
|
||||
return TrustDecision.NEUTRAL;
|
||||
}
|
||||
@@ -252,7 +259,7 @@ public class AssumeRolePolicyEvaluator {
|
||||
if (principal == PrincipalMatch.NONE) {
|
||||
return TrustDecision.NEUTRAL;
|
||||
}
|
||||
if (!policyEvaluator.conditionMatches(stmt.get("Condition"), context)) {
|
||||
if (!policyEvaluator.conditionMatches(stmt.get("Condition"), context, policyVersion)) {
|
||||
return TrustDecision.NEUTRAL;
|
||||
}
|
||||
return switch (effectOf(stmt)) {
|
||||
@@ -270,11 +277,11 @@ public class AssumeRolePolicyEvaluator {
|
||||
}
|
||||
|
||||
private Match evaluateServiceStatement(JsonNode stmt, String servicePrincipal,
|
||||
Map<String, List<String>> context) {
|
||||
Map<String, List<String>> context, String policyVersion) {
|
||||
if (!actionApplies(stmt) || !matchesServicePrincipal(stmt.get("Principal"), servicePrincipal)) {
|
||||
return Match.NO_MATCH;
|
||||
}
|
||||
if (!policyEvaluator.conditionMatches(stmt.get("Condition"), context)) {
|
||||
if (!policyEvaluator.conditionMatches(stmt.get("Condition"), context, policyVersion)) {
|
||||
return Match.NO_MATCH;
|
||||
}
|
||||
return effectOf(stmt);
|
||||
|
||||
@@ -908,8 +908,8 @@ public class IamPolicyEvaluator {
|
||||
return false;
|
||||
}
|
||||
return matchesAction(stmt, action)
|
||||
&& matchesResource(stmt, resource)
|
||||
&& matchesConditions(stmt.getConditions(), ctx);
|
||||
&& matchesResource(stmt, resource, ctx)
|
||||
&& matchesConditions(stmt.getConditions(), ctx, policyVariables(stmt));
|
||||
}
|
||||
|
||||
private boolean conditionDirectlyMatchesPrincipalArn(Map<String, Map<String, List<String>>> conditions, String principalArn) {
|
||||
@@ -944,8 +944,8 @@ public class IamPolicyEvaluator {
|
||||
PrincipalMatch match = principalMatch(stmt, principal);
|
||||
if (match == PrincipalMatch.NONE
|
||||
|| !matchesAction(stmt, action)
|
||||
|| !matchesResource(stmt, resource)
|
||||
|| !matchesConditions(stmt.getConditions(), ctx)) {
|
||||
|| !matchesResource(stmt, resource, ctx)
|
||||
|| !matchesConditions(stmt.getConditions(), ctx, policyVariables(stmt))) {
|
||||
return PrincipalMatch.NONE;
|
||||
}
|
||||
return match;
|
||||
@@ -1121,8 +1121,13 @@ public class IamPolicyEvaluator {
|
||||
private boolean matchesStatement(PolicyStatement stmt, String action, String resource,
|
||||
Map<String, List<String>> ctx) {
|
||||
return matchesAction(stmt, action)
|
||||
&& matchesResource(stmt, resource)
|
||||
&& matchesConditions(stmt.getConditions(), ctx);
|
||||
&& matchesResource(stmt, resource, ctx)
|
||||
&& matchesConditions(stmt.getConditions(), ctx, policyVariables(stmt));
|
||||
}
|
||||
|
||||
/** Whether this statement's document declares the version that gives {@code ${...}} meaning. */
|
||||
private static boolean policyVariables(PolicyStatement stmt) {
|
||||
return PolicyVariableResolver.enabledFor(stmt.getVersion());
|
||||
}
|
||||
|
||||
/** Action: matches if any Action pattern matches; NotAction: matches if NO pattern matches. */
|
||||
@@ -1137,12 +1142,37 @@ public class IamPolicyEvaluator {
|
||||
}
|
||||
|
||||
/** Resource: matches if any Resource pattern matches; NotResource: matches if NO pattern matches. */
|
||||
private boolean matchesResource(PolicyStatement stmt, String resource) {
|
||||
private boolean matchesResource(PolicyStatement stmt, String resource,
|
||||
Map<String, List<String>> ctx) {
|
||||
if (stmt.getResources() != null) {
|
||||
return matchesAny(stmt.getResources(), resource);
|
||||
return matchesAnyResource(stmt.getResources(), resource, ctx, policyVariables(stmt));
|
||||
}
|
||||
if (stmt.getNotResources() != null) {
|
||||
return !matchesAny(stmt.getNotResources(), resource);
|
||||
return !matchesAnyResource(stmt.getNotResources(), resource, ctx, policyVariables(stmt));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Glob over the Resource or NotResource patterns, with each pattern's policy variables
|
||||
* resolved first. A pattern holding a variable with no value matches nothing, which the user
|
||||
* guide states for both elements: "the resource that includes a policy variable with no value
|
||||
* will not match any resource". In NotResource that reads the other way round, since a
|
||||
* pattern matching no resource excludes none, so the statement covers every resource.
|
||||
*/
|
||||
private boolean matchesAnyResource(List<String> patterns, String resource,
|
||||
Map<String, List<String>> ctx, boolean policyVariables) {
|
||||
if (!policyVariables) {
|
||||
return matchesAny(patterns, resource);
|
||||
}
|
||||
if (resource == null) {
|
||||
return false;
|
||||
}
|
||||
for (String pattern : patterns) {
|
||||
String resolved = PolicyVariableResolver.resolveResourcePattern(pattern, ctx).orElse(null);
|
||||
if (resolved != null && globMatchesHelper(resolved, resource, true)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -1177,10 +1207,13 @@ public class IamPolicyEvaluator {
|
||||
* same operator semantics as every other policy this class reads. For policies this class
|
||||
* does not match statements for itself: trust policies carry no {@code Resource} element, so
|
||||
* {@link AssumeRolePolicyEvaluator} matches their principal and action and asks here for the
|
||||
* condition.
|
||||
* condition. {@code policyVersion} is that document's own {@code Version} element, since a
|
||||
* {@code ${...}} is only a policy variable under the version that introduced them.
|
||||
*/
|
||||
boolean conditionMatches(JsonNode condition, Map<String, List<String>> conditionCtx) {
|
||||
return matchesConditions(parseConditions(condition), normalizeConditionContext(conditionCtx));
|
||||
boolean conditionMatches(JsonNode condition, Map<String, List<String>> conditionCtx,
|
||||
String policyVersion) {
|
||||
return matchesConditions(parseConditions(condition), normalizeConditionContext(conditionCtx),
|
||||
PolicyVariableResolver.enabledFor(policyVersion));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1188,12 +1221,12 @@ public class IamPolicyEvaluator {
|
||||
* Returns true if ALL blocks pass (or there are no conditions).
|
||||
*/
|
||||
private boolean matchesConditions(Map<String, Map<String, List<String>>> conditions,
|
||||
Map<String, List<String>> ctx) {
|
||||
Map<String, List<String>> ctx, boolean policyVariables) {
|
||||
if (conditions == null || conditions.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
for (Map.Entry<String, Map<String, List<String>>> entry : conditions.entrySet()) {
|
||||
if (!evaluateConditionBlock(entry.getKey(), entry.getValue(), ctx)) {
|
||||
if (!evaluateConditionBlock(entry.getKey(), entry.getValue(), ctx, policyVariables)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1214,6 +1247,15 @@ public class IamPolicyEvaluator {
|
||||
"DateLessThan", "DateLessThanEquals", "DateGreaterThan", "DateGreaterThanEquals",
|
||||
"IpAddress", "NotIpAddress");
|
||||
|
||||
/**
|
||||
* The operators a policy variable may be used with: "Conditions support variables when you
|
||||
* use string operators or ARN operators", and not Numeric, Date, Boolean, Binary, IP Address
|
||||
* or Null. With one of those, a {@code ${...}} is the text it is written as.
|
||||
*/
|
||||
private static final Set<String> VARIABLE_CONDITION_OPERATORS = Set.of(
|
||||
"StringEquals", "StringNotEquals", "StringEqualsIgnoreCase", "StringNotEqualsIgnoreCase",
|
||||
"StringLike", "StringNotLike", "ArnEquals", "ArnNotEquals", "ArnLike", "ArnNotLike");
|
||||
|
||||
private record ParsedOperator(SetQuantifier quantifier, String baseOp, boolean ifExists) {}
|
||||
|
||||
/**
|
||||
@@ -1259,23 +1301,42 @@ public class IamPolicyEvaluator {
|
||||
* multi-valued negated condition and the deny-list idiom for keys such as
|
||||
* {@code dynamodb:Attributes} ({@code ForAllValues:StringNotEquals}).
|
||||
*/
|
||||
private boolean matchesCondValues(String baseOp, String ctxValue, List<String> condValues) {
|
||||
private boolean matchesCondValues(String baseOp, String ctxValue, List<String> condValues,
|
||||
Map<String, List<String>> ctx, boolean policyVariables) {
|
||||
if (isNegatedOperator(baseOp)) {
|
||||
for (String condValue : condValues) {
|
||||
if (!evaluateSingleCondition(baseOp, ctxValue, condValue)) {
|
||||
if (!matchesCondValue(baseOp, ctxValue, condValue, ctx, policyVariables)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
for (String condValue : condValues) {
|
||||
if (evaluateSingleCondition(baseOp, ctxValue, condValue)) {
|
||||
if (matchesCondValue(baseOp, ctxValue, condValue, ctx, policyVariables)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* One policy value against one request value, with the policy value's variables resolved
|
||||
* first. A value holding a variable with nothing to resolve to is effectively null: there is
|
||||
* "no equal or like value", so a positive operator does not match, while an inverted one does,
|
||||
* the request value being neither equal to nor like a null.
|
||||
*/
|
||||
private boolean matchesCondValue(String baseOp, String ctxValue, String condValue,
|
||||
Map<String, List<String>> ctx, boolean policyVariables) {
|
||||
String resolved = condValue;
|
||||
if (policyVariables) {
|
||||
resolved = PolicyVariableResolver.resolveValue(condValue, ctx).orElse(null);
|
||||
if (resolved == null) {
|
||||
return isNegatedOperator(baseOp);
|
||||
}
|
||||
}
|
||||
return evaluateSingleCondition(baseOp, ctxValue, resolved, policyVariables);
|
||||
}
|
||||
|
||||
private static boolean isNegatedOperator(String baseOp) {
|
||||
return switch (baseOp) {
|
||||
case "StringNotEquals", "StringNotEqualsIgnoreCase", "StringNotLike",
|
||||
@@ -1287,13 +1348,15 @@ public class IamPolicyEvaluator {
|
||||
|
||||
private boolean evaluateConditionBlock(String operator,
|
||||
Map<String, List<String>> keyValueMap,
|
||||
Map<String, List<String>> ctx) {
|
||||
Map<String, List<String>> ctx,
|
||||
boolean policyVariables) {
|
||||
if (!isSupportedConditionOperator(operator)) {
|
||||
return false;
|
||||
}
|
||||
ParsedOperator parsed = parseOperator(operator);
|
||||
String baseOp = parsed.baseOp();
|
||||
boolean ifExists = parsed.ifExists();
|
||||
boolean substitute = policyVariables && VARIABLE_CONDITION_OPERATORS.contains(baseOp);
|
||||
|
||||
for (Map.Entry<String, List<String>> entry : keyValueMap.entrySet()) {
|
||||
String condKey = entry.getKey().toLowerCase(java.util.Locale.ROOT);
|
||||
@@ -1341,14 +1404,14 @@ public class IamPolicyEvaluator {
|
||||
// matches vacuously, which is why real policies pair ForAllValues with a
|
||||
// Null:{key:"false"} guard.
|
||||
case FOR_ALL_VALUES -> ctxValues.stream()
|
||||
.allMatch(ctxValue -> matchesCondValues(baseOp, ctxValue, condValues));
|
||||
.allMatch(ctxValue -> matchesCondValues(baseOp, ctxValue, condValues, ctx, substitute));
|
||||
// At least one request value must match. An empty set never matches.
|
||||
case FOR_ANY_VALUE -> ctxValues.stream()
|
||||
.anyMatch(ctxValue -> matchesCondValues(baseOp, ctxValue, condValues));
|
||||
.anyMatch(ctxValue -> matchesCondValues(baseOp, ctxValue, condValues, ctx, substitute));
|
||||
// A bare operator against a multi-valued key is a policy authoring error in
|
||||
// AWS; mirror that by comparing only the first value.
|
||||
case NONE -> !ctxValues.isEmpty()
|
||||
&& matchesCondValues(baseOp, ctxValues.getFirst(), condValues);
|
||||
&& matchesCondValues(baseOp, ctxValues.getFirst(), condValues, ctx, substitute);
|
||||
};
|
||||
if (!keyMatch) {
|
||||
return false;
|
||||
@@ -1358,16 +1421,25 @@ public class IamPolicyEvaluator {
|
||||
}
|
||||
|
||||
|
||||
private boolean evaluateSingleCondition(String operator, String ctxValue, String condValue) {
|
||||
/**
|
||||
* One comparison. {@code escapes} says the policy value came back from substitution, which is
|
||||
* the only way a {@link PolicyVariableResolver#ESCAPE} marker can be in it: the glob operators
|
||||
* then read the marker themselves, while the operators comparing whole strings collapse it
|
||||
* first. Without substitution no marker is honoured, so one written into a document is the
|
||||
* character it is and cannot narrow the comparison.
|
||||
*/
|
||||
private boolean evaluateSingleCondition(String operator, String ctxValue, String condValue,
|
||||
boolean escapes) {
|
||||
String plain = escapes ? PolicyVariableResolver.literal(condValue) : condValue;
|
||||
return switch (operator) {
|
||||
case "StringEquals" -> ctxValue.equals(condValue);
|
||||
case "StringNotEquals" -> !ctxValue.equals(condValue);
|
||||
case "StringEqualsIgnoreCase" -> ctxValue.equalsIgnoreCase(condValue);
|
||||
case "StringNotEqualsIgnoreCase" -> !ctxValue.equalsIgnoreCase(condValue);
|
||||
case "StringLike" -> caseSensitiveGlobMatches(condValue, ctxValue);
|
||||
case "StringNotLike" -> !caseSensitiveGlobMatches(condValue, ctxValue);
|
||||
case "ArnEquals", "ArnLike" -> matchesArnCondition(condValue, ctxValue);
|
||||
case "ArnNotEquals", "ArnNotLike"-> !matchesArnCondition(condValue, ctxValue);
|
||||
case "StringEquals" -> ctxValue.equals(plain);
|
||||
case "StringNotEquals" -> !ctxValue.equals(plain);
|
||||
case "StringEqualsIgnoreCase" -> ctxValue.equalsIgnoreCase(plain);
|
||||
case "StringNotEqualsIgnoreCase" -> !ctxValue.equalsIgnoreCase(plain);
|
||||
case "StringLike" -> globMatches(condValue, ctxValue, true, escapes);
|
||||
case "StringNotLike" -> !globMatches(condValue, ctxValue, true, escapes);
|
||||
case "ArnEquals", "ArnLike" -> matchesArnCondition(condValue, ctxValue, escapes);
|
||||
case "ArnNotEquals", "ArnNotLike"-> !matchesArnCondition(condValue, ctxValue, escapes);
|
||||
case "Bool" -> Boolean.parseBoolean(condValue) == Boolean.parseBoolean(ctxValue);
|
||||
case "NumericEquals" -> compareNumeric(ctxValue, condValue, order -> order == 0);
|
||||
case "NumericNotEquals" -> compareNumeric(ctxValue, condValue, order -> order != 0);
|
||||
@@ -1453,17 +1525,35 @@ public class IamPolicyEvaluator {
|
||||
* Case-insensitive glob matching supporting {@code *} (any sequence) and {@code ?} (any char).
|
||||
*/
|
||||
public static boolean globMatches(String pattern, String value) {
|
||||
if (pattern == null || value == null) {
|
||||
return false;
|
||||
}
|
||||
return globMatchesHelper(pattern.toLowerCase(), value.toLowerCase());
|
||||
return globMatches(pattern, value, false, false);
|
||||
}
|
||||
|
||||
public static boolean caseSensitiveGlobMatches(String pattern, String value) {
|
||||
return pattern != null && value != null && globMatchesHelper(pattern, value);
|
||||
return globMatches(pattern, value, true, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* One glob, with {@code caseSensitive} choosing how the characters compare and
|
||||
* {@code escapes} saying whether a {@link PolicyVariableResolver#ESCAPE} marker in the pattern
|
||||
* protects the character behind it. Only a pattern that came back from substitution carries a
|
||||
* marker, so every other caller leaves escapes off and a marker written into a policy is just
|
||||
* a character.
|
||||
*/
|
||||
private static boolean globMatches(String pattern, String value, boolean caseSensitive,
|
||||
boolean escapes) {
|
||||
if (pattern == null || value == null) {
|
||||
return false;
|
||||
}
|
||||
return caseSensitive
|
||||
? globMatchesHelper(pattern, value, escapes)
|
||||
: globMatchesHelper(pattern.toLowerCase(), value.toLowerCase(), escapes);
|
||||
}
|
||||
|
||||
public static boolean matchesArnCondition(String pattern, String value) {
|
||||
return matchesArnCondition(pattern, value, false);
|
||||
}
|
||||
|
||||
private static boolean matchesArnCondition(String pattern, String value, boolean escapes) {
|
||||
if (pattern == null || value == null) {
|
||||
return false;
|
||||
}
|
||||
@@ -1474,21 +1564,43 @@ public class IamPolicyEvaluator {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < patternComponents.length; i++) {
|
||||
if (!caseSensitiveGlobMatches(patternComponents[i], valueComponents[i])) {
|
||||
if (!globMatches(patternComponents[i], valueComponents[i], true, escapes)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Matches {@code pattern} against {@code value}, where {@code *} is any sequence and
|
||||
* {@code ?} any single character. A character behind {@link PolicyVariableResolver#ESCAPE}
|
||||
* matches only itself, which is how {@code ${*}} and {@code ${?}} keep standing for an
|
||||
* asterisk and a question mark once they are substituted.
|
||||
*/
|
||||
private static boolean globMatchesHelper(String pattern, String value) {
|
||||
return globMatchesHelper(pattern, value, false);
|
||||
}
|
||||
|
||||
private static boolean globMatchesHelper(String pattern, String value, boolean escapes) {
|
||||
int patternIndex = 0;
|
||||
int valueIndex = 0;
|
||||
int starIndex = -1;
|
||||
int starValueIndex = -1;
|
||||
|
||||
while (valueIndex < value.length()) {
|
||||
if (patternIndex < pattern.length() && pattern.charAt(patternIndex) == '*') {
|
||||
if (escapes && patternIndex + 1 < pattern.length()
|
||||
&& pattern.charAt(patternIndex) == PolicyVariableResolver.ESCAPE) {
|
||||
if (pattern.charAt(patternIndex + 1) == value.charAt(valueIndex)) {
|
||||
patternIndex += 2;
|
||||
valueIndex++;
|
||||
continue;
|
||||
}
|
||||
if (starIndex < 0) {
|
||||
return false;
|
||||
}
|
||||
patternIndex = starIndex + 1;
|
||||
valueIndex = ++starValueIndex;
|
||||
} else if (patternIndex < pattern.length() && pattern.charAt(patternIndex) == '*') {
|
||||
starIndex = patternIndex++;
|
||||
starValueIndex = valueIndex;
|
||||
} else if (patternIndex < pattern.length()
|
||||
@@ -1569,18 +1681,19 @@ public class IamPolicyEvaluator {
|
||||
private List<PolicyStatement> parseStatements(String document) throws Exception {
|
||||
JsonNode root = objectMapper.readTree(document);
|
||||
JsonNode stmtNode = root.path("Statement");
|
||||
String version = root.path("Version").asText(null);
|
||||
List<PolicyStatement> result = new ArrayList<>();
|
||||
if (stmtNode.isArray()) {
|
||||
for (JsonNode s : stmtNode) {
|
||||
result.add(parseStatement(s));
|
||||
result.add(parseStatement(s, version));
|
||||
}
|
||||
} else if (stmtNode.isObject()) {
|
||||
result.add(parseStatement(stmtNode));
|
||||
result.add(parseStatement(stmtNode, version));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private PolicyStatement parseStatement(JsonNode stmt) {
|
||||
private PolicyStatement parseStatement(JsonNode stmt, String version) {
|
||||
String effect = stmt.path("Effect").asText("Allow");
|
||||
Map<String, List<String>> principals = parsePrincipals(stmt.get("Principal"));
|
||||
Map<String, List<String>> notPrincipals = parsePrincipals(stmt.get("NotPrincipal"));
|
||||
@@ -1599,7 +1712,8 @@ public class IamPolicyEvaluator {
|
||||
notActions.isEmpty() ? null : notActions,
|
||||
resources.isEmpty() ? null : resources,
|
||||
notResources.isEmpty()? null : notResources,
|
||||
conditions);
|
||||
conditions,
|
||||
version);
|
||||
}
|
||||
|
||||
private Map<String, List<String>> parsePrincipals(JsonNode node) {
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Substitutes IAM policy variables, the {@code ${...}} placeholders a policy writes where it
|
||||
* cannot know a value until the request arrives.
|
||||
*
|
||||
* <p>A variable names a condition context key, so {@code ${aws:username}} in a Resource pattern
|
||||
* resolves to the name of the user making the request. Key names are case-insensitive, matching
|
||||
* the user guide, and only a single-valued key resolves: the guide says a multivalued key cannot
|
||||
* be used as a variable, and there is no one value to put in its place.
|
||||
*
|
||||
* <p>An empty {@link Optional} means the text held a variable with nothing to resolve to. The
|
||||
* caller decides what that means, because AWS gives the two elements different answers: a
|
||||
* Resource pattern "will not match any resource", while a Condition value is effectively null,
|
||||
* which a positive operator does not match and an inverted one does.
|
||||
*
|
||||
* <p>Three variables name a character rather than a key: {@code ${*}}, {@code ${?}} and
|
||||
* {@code ${$}} stand for a literal asterisk, question mark and dollar sign. The first two have to
|
||||
* survive glob matching as themselves, so they resolve to the character behind {@link #ESCAPE},
|
||||
* which {@code IamPolicyEvaluator}'s glob reads as "the next character matches literally".
|
||||
* Operators that compare whole strings instead of globbing take {@link #literal} first.
|
||||
*
|
||||
* <p>A substituted value is not escaped, so a value carrying a {@code *} widens the pattern it
|
||||
* lands in. That is AWS's own behaviour: its policy checks warn that "policy variables can be
|
||||
* evaluated as effective wildcards".
|
||||
*
|
||||
* <p>Reporting the key names a document references, which is what
|
||||
* {@code GetContextKeysForCustomPolicy} answers, is a different question and keeps its own pattern
|
||||
* in {@code IamPolicyEvaluator}: it has to name the key even where the variable around it is
|
||||
* written in a form that resolves to nothing here, such as a default value missing its quotes.
|
||||
*/
|
||||
final class PolicyVariableResolver {
|
||||
|
||||
/**
|
||||
* Marks the character after it as a literal, so a substituted asterisk or question mark is
|
||||
* not read as a wildcard. Only text this class has substituted carries a marker: it strips
|
||||
* any that arrived in the policy, and the matcher honours markers only on a pattern that came
|
||||
* back from substitution. A document can hold one as the JSON escape {@code \u0000}, and left
|
||||
* to act as a marker it would turn a wildcard of the document's own into a literal character
|
||||
* and narrow the statement it sits in. AWS refuses such a document outright, its
|
||||
* {@code policyDocumentType} admitting tab, newline, carriage return and the printable range
|
||||
* from the space character upward and nothing below it, but that is AWS's pattern to enforce
|
||||
* and not a property of what reaches this class.
|
||||
*/
|
||||
static final char ESCAPE = '\u0000';
|
||||
|
||||
/**
|
||||
* A variable: {@code ${key}}, or {@code ${key, 'default'}} where the default runs to its
|
||||
* closing quote rather than to the first brace, so one carrying a brace of its own survives.
|
||||
* The key is one or more characters and holds no whitespace, the guide saying "you cannot
|
||||
* include a space in the variable name" while "you can include a space when you specify a
|
||||
* default variable". Anything else written between {@code ${} and {@code }} matches nothing
|
||||
* here and stays the text it is, which is what an empty {@code ${}}, a spaced name, an
|
||||
* unquoted default and a missing brace all come to.
|
||||
*/
|
||||
private static final Pattern VARIABLE =
|
||||
Pattern.compile("\\$\\{([^\\s,}]+)(?:,\\s*'([^']*)'\\s*)?}");
|
||||
|
||||
/** The policy language version that introduced variables. */
|
||||
private static final String VARIABLES_VERSION = "2012-10-17";
|
||||
|
||||
private static final int ARN_RESOURCE_COLON = 5;
|
||||
|
||||
private PolicyVariableResolver() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a document declaring this {@code Version} has policy variables at all. They arrived
|
||||
* with 2012-10-17; under the older 2008-10-17, which is also the default when the element is
|
||||
* absent, the user guide says they "are instead treated as literal strings in the policy".
|
||||
* The policy-check reference reads "2012-10-17 or later", and equality covers that: the guide
|
||||
* lists exactly two values IAM supports for the element, and no later one exists to admit.
|
||||
*/
|
||||
static boolean enabledFor(String policyVersion) {
|
||||
return VARIABLES_VERSION.equals(policyVersion);
|
||||
}
|
||||
|
||||
/**
|
||||
* Substitutes every variable in a Condition value. Empty when one of them has no value, which
|
||||
* leaves the whole value effectively null rather than partly resolved.
|
||||
*/
|
||||
static Optional<String> resolveValue(String text, Map<String, List<String>> context) {
|
||||
String plain = withoutMarker(text);
|
||||
if (plain == null || !plain.contains("${")) {
|
||||
return Optional.ofNullable(plain);
|
||||
}
|
||||
Matcher matcher = VARIABLE.matcher(plain);
|
||||
StringBuilder resolved = new StringBuilder(plain.length());
|
||||
int copiedTo = 0;
|
||||
while (matcher.find()) {
|
||||
String substitution = substitutionFor(matcher.group(1), matcher.group(2), context);
|
||||
if (substitution == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
resolved.append(plain, copiedTo, matcher.start()).append(substitution);
|
||||
copiedTo = matcher.end();
|
||||
}
|
||||
resolved.append(plain, copiedTo, plain.length());
|
||||
return Optional.of(resolved.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Substitutes variables in the resource portion of an ARN pattern, which is what follows the
|
||||
* fifth colon. The user guide is explicit that a variable cannot replace any part before it,
|
||||
* such as the service or the account, so anything written there stays the literal text it is
|
||||
* and matches nothing. A pattern that is not an ARN, {@code *} among them, has no resource
|
||||
* portion and is returned unchanged.
|
||||
*/
|
||||
static Optional<String> resolveResourcePattern(String pattern, Map<String, List<String>> context) {
|
||||
if (pattern == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String plain = withoutMarker(pattern);
|
||||
int resourceStart = resourcePortionStart(plain);
|
||||
if (resourceStart < 0) {
|
||||
return Optional.of(plain);
|
||||
}
|
||||
return resolveValue(plain.substring(resourceStart), context)
|
||||
.map(resource -> plain.substring(0, resourceStart) + resource);
|
||||
}
|
||||
|
||||
/**
|
||||
* The text with every {@link #ESCAPE} character removed, applied to whatever arrives from a
|
||||
* policy. One written into a document is not a marker but a forgery of one, and dropping it
|
||||
* leaves the document's own wildcards to glob as they are written.
|
||||
*/
|
||||
private static String withoutMarker(String text) {
|
||||
return text == null || text.indexOf(ESCAPE) < 0
|
||||
? text
|
||||
: text.replace(String.valueOf(ESCAPE), "");
|
||||
}
|
||||
|
||||
/** The text with every {@link #ESCAPE} marker dropped, leaving the character it protected. */
|
||||
static String literal(String text) {
|
||||
if (text == null || text.indexOf(ESCAPE) < 0) {
|
||||
return text;
|
||||
}
|
||||
StringBuilder plain = new StringBuilder(text.length());
|
||||
for (int i = 0; i < text.length(); i++) {
|
||||
char current = text.charAt(i);
|
||||
if (current != ESCAPE) {
|
||||
plain.append(current);
|
||||
} else if (i + 1 < text.length()) {
|
||||
plain.append(text.charAt(++i));
|
||||
}
|
||||
}
|
||||
return plain.toString();
|
||||
}
|
||||
|
||||
/** The value to put in a variable's place, or null when it has none. */
|
||||
private static String substitutionFor(String key, String defaultValue,
|
||||
Map<String, List<String>> context) {
|
||||
if ("*".equals(key)) {
|
||||
return ESCAPE + "*";
|
||||
}
|
||||
if ("?".equals(key)) {
|
||||
return ESCAPE + "?";
|
||||
}
|
||||
if ("$".equals(key)) {
|
||||
return "$";
|
||||
}
|
||||
List<String> values = context.get(key.toLowerCase(Locale.ROOT));
|
||||
if (values == null || values.isEmpty()) {
|
||||
return defaultValue;
|
||||
}
|
||||
if (values.size() > 1) {
|
||||
// "You can't use a multivalued condition key as a variable", and the guide gives a
|
||||
// default no part in that rule: it stands in for a key with no value, not for one
|
||||
// holding several. So the variable resolves to nothing and the value it sits in
|
||||
// matches nothing, rather than quietly widening to the default.
|
||||
return null;
|
||||
}
|
||||
return values.getFirst();
|
||||
}
|
||||
|
||||
/** The index just past the fifth colon, or -1 when the pattern has fewer than five. */
|
||||
private static int resourcePortionStart(String pattern) {
|
||||
int colons = 0;
|
||||
for (int i = 0; i < pattern.length(); i++) {
|
||||
if (pattern.charAt(i) == ':') {
|
||||
colons++;
|
||||
if (colons == ARN_RESOURCE_COLON) {
|
||||
return i + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,11 @@ public class PolicyStatement {
|
||||
private final List<String> notResources;// NotResource patterns; null when resources is set
|
||||
// Condition: outer key = operator (e.g. "StringEquals"), inner key = context key, value = list of values
|
||||
private final Map<String, Map<String, List<String>>> conditions;
|
||||
// The document's Version element, which decides whether this statement's ${...} are policy
|
||||
// variables or literal text. It belongs to the document rather than the statement, but
|
||||
// statements from many documents are evaluated as one list, so each carries its own. Null
|
||||
// when the document has no Version element, which is the 2008-10-17 default.
|
||||
private final String version;
|
||||
|
||||
public PolicyStatement(String effect,
|
||||
Map<String, List<String>> principals,
|
||||
@@ -27,7 +32,8 @@ public class PolicyStatement {
|
||||
List<String> notActions,
|
||||
List<String> resources,
|
||||
List<String> notResources,
|
||||
Map<String, Map<String, List<String>>> conditions) {
|
||||
Map<String, Map<String, List<String>>> conditions,
|
||||
String version) {
|
||||
this.effect = effect;
|
||||
this.principals = principals;
|
||||
this.notPrincipals = notPrincipals;
|
||||
@@ -36,20 +42,22 @@ public class PolicyStatement {
|
||||
this.resources = resources;
|
||||
this.notResources = notResources;
|
||||
this.conditions = conditions;
|
||||
this.version = version;
|
||||
}
|
||||
|
||||
/** Without a version, {@code ${...}} stays literal text, as it does under 2008-10-17. */
|
||||
public PolicyStatement(String effect,
|
||||
List<String> actions,
|
||||
List<String> notActions,
|
||||
List<String> resources,
|
||||
List<String> notResources,
|
||||
Map<String, Map<String, List<String>>> conditions) {
|
||||
this(effect, null, null, actions, notActions, resources, notResources, conditions);
|
||||
this(effect, null, null, actions, notActions, resources, notResources, conditions, null);
|
||||
}
|
||||
|
||||
/** Convenience constructor for simple allow/deny without conditions or Not* fields. */
|
||||
public PolicyStatement(String effect, List<String> actions, List<String> resources) {
|
||||
this(effect, null, null, actions, null, resources, null, null);
|
||||
this(effect, null, null, actions, null, resources, null, null, null);
|
||||
}
|
||||
|
||||
public String getEffect() { return effect; }
|
||||
@@ -60,6 +68,7 @@ public class PolicyStatement {
|
||||
public List<String> getResources() { return resources; }
|
||||
public List<String> getNotResources() { return notResources; }
|
||||
public Map<String, Map<String, List<String>>> getConditions() { return conditions; }
|
||||
public String getVersion() { return version; }
|
||||
|
||||
public boolean isDeny() { return "Deny".equalsIgnoreCase(effect); }
|
||||
public boolean isAllow() { return "Allow".equalsIgnoreCase(effect); }
|
||||
|
||||
Reference in new issue
Block a user