Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,6 @@
import java.util.Arrays;
import java.util.Optional;

import static org.apache.commons.lang3.StringUtils.indexOfAny;
import static org.apache.struts2.security.DefaultAcceptedPatternsChecker.NESTING_CHARS;
import static org.apache.struts2.security.DefaultAcceptedPatternsChecker.NESTING_CHARS_STR;

/**
* Default {@link ParameterAllowlister}. Registers the root property's class (and generic type args for {@code depth >= 2})
Expand Down Expand Up @@ -85,13 +82,13 @@ public void primeAllowlistForPath(String parameterName, Object target) {
if (parameterName == null || parameterName.isEmpty() || target == null) {
return;
}
long paramDepth = parameterName.codePoints().mapToObj(c -> (char) c).filter(NESTING_CHARS::contains).count();
if (paramDepth == 0) {
// Root property and depth come from the expression OGNL will evaluate, not from the text of the name
ParameterPath path = ParameterPath.of(parameterName, ognlUtil);
if (path == null || path.getDepth() == 0) {
return;
}

int nestingIndex = indexOfAny(parameterName, NESTING_CHARS_STR);
String rootProperty = nestingIndex == -1 ? parameterName : parameterName.substring(0, nestingIndex);
long paramDepth = path.getDepth();
String rootProperty = path.getRootProperty();
String normalisedRootProperty = Character.toLowerCase(rootProperty.charAt(0)) + rootProperty.substring(1);

if (allowlistViaPropertyDescriptor(target, normalisedRootProperty, paramDepth)) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.struts2.interceptor.parameter;

import ognl.ASTChain;
import ognl.ASTConst;
import ognl.ASTMethod;
import ognl.ASTProperty;
import ognl.Node;
import ognl.OgnlException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.ognl.OgnlUtil;

import static org.apache.commons.lang3.StringUtils.indexOfAny;
import static org.apache.struts2.security.DefaultAcceptedPatternsChecker.NESTING_CHARS;
import static org.apache.struts2.security.DefaultAcceptedPatternsChecker.NESTING_CHARS_STR;

/**
* The root property and nesting depth of a parameter name, as OGNL parses it.
* <p>
* Both are read from the expression tree that OGNL evaluates when the parameter is bound, rather than from the text
* of the name, so authorization and allowlist priming judge exactly the path that will be walked:
* <table>
* <caption>Examples</caption>
* <tr><th>Name</th><th>Root property</th><th>Depth</th></tr>
* <tr><td>{@code name}</td><td>{@code name}</td><td>0</td></tr>
* <tr><td>{@code user.address.city}</td><td>{@code user}</td><td>2</td></tr>
* <tr><td>{@code list[0].name}</td><td>{@code list}</td><td>2</td></tr>
* <tr><td>{@code map['key']}</td><td>{@code map}</td><td>1</td></tr>
* <tr><td>{@code map['a.b']}</td><td>{@code map}</td><td>1</td></tr>
* <tr><td>{@code users(1)}</td><td>{@code users}</td><td>1</td></tr>
* </table>
* A method call such as {@code users(1)} counts as one level, as its {@code (} did in the text-based derivation.
*
* @since 7.6.0
*/
final class ParameterPath {

private static final Logger LOG = LogManager.getLogger(ParameterPath.class);

private final String rootProperty;
private final long depth;

private ParameterPath(String rootProperty, long depth) {
this.rootProperty = rootProperty;
this.depth = depth;
}

/**
* @return the name of the first property (or method) of the path, never empty
*/
String getRootProperty() {
return rootProperty;
}

/**
* @return the number of nesting levels below the root property
*/
long getDepth() {
return depth;
}

/**
* Derives the root property and depth of a parameter name from its parsed OGNL expression.
*
* @param parameterName the parameter name
* @param ognlUtil used to parse the name through the expression cache; if {@code null}, the root property
* and depth are derived from the text of the name, as before 7.6.0
* @return the path, or {@code null} if the name does not parse, or does not start with a named property or method
*/
static ParameterPath of(String parameterName, OgnlUtil ognlUtil) {
if (parameterName == null || parameterName.isEmpty()) {
return null;
}
if (ognlUtil == null) {
return fromText(parameterName);
}
Object tree;
try {
tree = ognlUtil.compile(parameterName);
} catch (OgnlException | RuntimeException e) {
LOG.debug("Parameter [{}] cannot be parsed as an OGNL expression", parameterName, e);
return null;
}
return tree instanceof Node node ? fromTree(node) : null;
}

static ParameterPath fromTree(Node tree) {
Node first = tree;
long levelsAfterFirst = 0;
if (tree instanceof ASTChain) {
if (tree.jjtGetNumChildren() == 0) {
return null;
}
first = tree.jjtGetChild(0);
levelsAfterFirst = tree.jjtGetNumChildren() - 1L;
}

if (first instanceof ASTMethod method) {
String methodName = method.getMethodName();
return methodName == null || methodName.isEmpty() ? null : new ParameterPath(methodName, levelsAfterFirst + 1);
}
if (first instanceof ASTProperty property && !property.isIndexedAccess()
&& property.jjtGetNumChildren() == 1 && property.jjtGetChild(0) instanceof ASTConst constant
&& constant.getValue() instanceof String name && !name.isEmpty()) {
return new ParameterPath(name, levelsAfterFirst);
}
// e.g. an expression that starts with an index ("[0].name"), a constant or any other node
return null;
}

private static ParameterPath fromText(String parameterName) {
long depth = parameterName.codePoints().mapToObj(c -> (char) c).filter(NESTING_CHARS::contains).count();
int nestingIndex = indexOfAny(parameterName, NESTING_CHARS_STR);
String rootProperty = nestingIndex == -1 ? parameterName : parameterName.substring(0, nestingIndex);
return rootProperty.isEmpty() ? null : new ParameterPath(rootProperty, depth);
}

@Override
public String toString() {
return rootProperty + " (depth " + depth + ")";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,6 @@

import static java.lang.String.format;
import static java.util.Comparator.comparingInt;
import static org.apache.commons.lang3.StringUtils.indexOfAny;
import static org.apache.struts2.security.DefaultAcceptedPatternsChecker.NESTING_CHARS;
import static org.apache.struts2.security.DefaultAcceptedPatternsChecker.NESTING_CHARS_STR;
import static org.apache.struts2.util.DebugUtils.notifyDeveloperOfError;

/**
Expand Down Expand Up @@ -128,16 +125,15 @@ public boolean isAuthorized(String parameterName, Object target, Object action)
return true;
}

long paramDepth = parameterDepth(parameterName);

int nestingIndex = indexOfAny(parameterName, NESTING_CHARS_STR);
String rootProperty = nestingIndex == -1 ? parameterName : parameterName.substring(0, nestingIndex);
if (rootProperty.isEmpty()) {
LOG.debug("Parameter [{}] begins with a nesting character, so it names no root property to authorize; rejecting",
// Root property and depth come from the expression OGNL will evaluate, not from the text of the name
ParameterPath path = ParameterPath.of(parameterName, ognlUtil);
if (path == null) {
LOG.debug("Parameter [{}] does not start with a named property, so it names no root property to authorize; rejecting",
parameterName);
return false;
}
String normalisedRootProperty = Introspector.decapitalize(rootProperty);
long paramDepth = path.getDepth();
String normalisedRootProperty = Introspector.decapitalize(path.getRootProperty());

// Transition mode: depth-0 (non-nested) parameters are exempt. Checked before the ModelDriven
// exemption so that it also covers a ModelDriven action's own members, which would otherwise
Expand All @@ -158,8 +154,13 @@ public boolean isAuthorized(String parameterName, Object target, Object action)
return hasValidAnnotatedMember(normalisedRootProperty, target, paramDepth);
}

private static long parameterDepth(String parameterName) {
return parameterName.codePoints().mapToObj(c -> (char) c).filter(NESTING_CHARS::contains).count();
/**
* The nesting depth of a parameter name as OGNL parses it, or {@link Long#MAX_VALUE} (the most restrictive depth)
* if it does not parse to a path that starts with a named property.
*/
private long parameterDepth(String parameterName) {
ParameterPath path = ParameterPath.of(parameterName, ognlUtil);
return path == null ? Long.MAX_VALUE : path.getDepth();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -507,6 +507,43 @@ public void modelDriven_mapModel_classAtDepthZero_rejected() {

// --- Inner test classes ---

// --- WW-5884: root property and depth are taken from the parsed OGNL expression ---

@Test
public void quotedKeyContainingADot_isOneLevel_authorizedAtDepthOne() {
// The text-based derivation counted the '.' inside the key and asked for depth 2
var action = new MapHolderAction();
assertThat(authorizer.isAuthorized("settings['a.b']", action, action)).isTrue();
}

@Test
public void quotedKeyContainingADot_secondLevel_stillRejectedAtDepthOne() {
var action = new MapHolderAction();
assertThat(authorizer.isAuthorized("settings['a.b'].c", action, action)).isFalse();
}

@Test
public void nameWithoutNamedRoot_rejected() {
var action = new SecureAction();
assertThat(authorizer.isAuthorized("[0].name", action, action)).isFalse();
assertThat(authorizer.isAuthorized("['name']", action, action)).isFalse();
}

@Test
public void unparsableName_rejected() {
var action = new SecureAction();
assertThat(authorizer.isAuthorized("address..city", action, action)).isFalse();
}

public static class MapHolderAction {
private final Map<String, Object> settings = new HashMap<>();

@StrutsParameter(depth = 1)
public Map<String, Object> getSettings() {
return settings;
}
}

public static class PreviousAction {
private String foo;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.struts2.interceptor.parameter;

import org.apache.struts2.ognl.DefaultOgnlBeanInfoCacheFactory;
import org.apache.struts2.ognl.DefaultOgnlExpressionCacheFactory;
import org.apache.struts2.ognl.OgnlUtil;
import org.apache.struts2.ognl.StrutsOgnlGuard;
import org.junit.Before;
import org.junit.Test;

import static org.apache.struts2.ognl.OgnlCacheFactory.CacheType.LRU;
import static org.assertj.core.api.Assertions.assertThat;

/**
* Tests for {@link ParameterPath} (WW-5884).
*/
public class ParameterPathTest {

private OgnlUtil ognlUtil;

@Before
public void setUp() {
ognlUtil = new OgnlUtil(
new DefaultOgnlExpressionCacheFactory<>(String.valueOf(1000), LRU.toString()),
new DefaultOgnlBeanInfoCacheFactory<>(String.valueOf(1000), LRU.toString()),
new StrutsOgnlGuard());
}

@Test
public void examplesFromTheTicket() {
assertPath("name", "name", 0);
assertPath("user.address.city", "user", 2);
assertPath("list[0].name", "list", 2);
assertPath("map['key']", "map", 1);
assertPath("users(1)", "users", 1);
}

@Test
public void agreesWithTheTextForNamesWithoutQuotedNestingCharacters() {
for (String name : new String[]{"name", "a.b", "a.b.c.d", "list[0]", "list[0].name", "map['key'].value",
"users(1).name", "Name", "a_b.c1"}) {
ParameterPath fromTree = ParameterPath.of(name, ognlUtil);
ParameterPath fromText = ParameterPath.of(name, null);
assertThat(fromTree).as(name).isNotNull();
assertThat(fromTree.getRootProperty()).as(name).isEqualTo(fromText.getRootProperty());
assertThat(fromTree.getDepth()).as(name).isEqualTo(fromText.getDepth());
}
}

@Test
public void nestingCharactersInsideAQuotedKeyDoNotCount() {
// The text-based derivation counted the '.' inside the key as a level, OGNL does not
assertPath("map['a.b']", "map", 1);
assertThat(ParameterPath.of("map['a.b']", null).getDepth()).isEqualTo(2);

assertPath("map['a[0]'].value", "map", 2);
assertPath("map['f(x)']", "map", 1);
}

@Test
public void pathWithoutANamedRootIsRejected() {
assertThat(ParameterPath.of("[0].name", ognlUtil)).isNull();
assertThat(ParameterPath.of("['key']", ognlUtil)).isNull();
assertThat(ParameterPath.of("'literal'", ognlUtil)).isNull();
assertThat(ParameterPath.of("1", ognlUtil)).isNull();
}

@Test
public void evaluationOfAResultIsNotAPath() {
// a('k')('k') parses as an ASTEval (the result of a('k') evaluated as an expression), not as two subscripts
assertThat(ParameterPath.of("a('k')('k')", ognlUtil)).isNull();
assertThat(ParameterPath.of("(a)(b)", ognlUtil)).isNull();
}

@Test
public void unparsableNameIsRejected() {
assertThat(ParameterPath.of("a..b", ognlUtil)).isNull();
assertThat(ParameterPath.of("map['unterminated", ognlUtil)).isNull();
assertThat(ParameterPath.of("", ognlUtil)).isNull();
assertThat(ParameterPath.of(null, ognlUtil)).isNull();
}

@Test
public void textFallbackWithoutOgnlUtil() {
ParameterPath path = ParameterPath.of("user.address.city", null);
assertThat(path.getRootProperty()).isEqualTo("user");
assertThat(path.getDepth()).isEqualTo(2);
assertThat(ParameterPath.of(".name", null)).isNull();
}

private void assertPath(String name, String expectedRoot, long expectedDepth) {
ParameterPath path = ParameterPath.of(name, ognlUtil);
assertThat(path).as(name).isNotNull();
assertThat(path.getRootProperty()).as(name).isEqualTo(expectedRoot);
assertThat(path.getDepth()).as(name).isEqualTo(expectedDepth);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -232,12 +232,15 @@ public void publicNestedPojoDepthTwo_sqrBracket() {
}

/**
* Public Pojo field can be injected two levels when annotated with depth two, using the bracket syntax.
* {@code a('key')('key')} is not a chain of subscripts: OGNL parses it as an {@code ASTEval}, which evaluates the
* result of {@code a('key')} as a further expression. {@code StrutsParameterNodeGuard} already refuses that node when
* the parameter is bound (WW-5881), and since WW-5884 the authorizer, which reads the root property and depth from
* the same parse, rejects it too instead of guessing a depth from the parentheses.
*/
@Test
public void publicNestedPojoDepthTwo_bracket() {
testParameter(new FieldAction(), "publicPojoDepthTwo('key')('key')", true);
assertThat(threadAllowlist.getAllowlist()).containsExactlyInAnyOrderElementsOf(getParentClasses(Pojo.class));
testParameter(new FieldAction(), "publicPojoDepthTwo('key')('key')", false);
assertThat(threadAllowlist.getAllowlist()).isEmpty();
}

/**
Expand Down