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 @@ -29,14 +29,7 @@

public final class JsonTemplateLayoutCodecFuzzer {

// Choosing a reasonable JSON document length sufficing following needs:
//
// 1. Long enough to give fuzzer room to try breaking stuff
//
// 2. Short enough to avoid stack overflows, which are interpreted as fuzzer failures, though they are not.
// Consider a JSON document containing more than 1024 nested objects.
// This triggers a stack overflow, which is expected, hence nothing to signal.
public static final int MAX_STRING_LENGTH = 512;
public static final int MAX_STRING_LENGTH = 4096;

public static void fuzzerTestOneInput(final FuzzedDataProvider dataProvider) {
final boolean encodeFirst = dataProvider.consumeBoolean();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,36 @@ void test_nesting() {
})));
}

@Test
void test_maximum_nesting_depth() {
for (final String[] delimiters : new String[][] {{"[", "]"}, {"{\"key\":", "}"}}) {
final String json = nestedJson(delimiters[0], delimiters[1], 128);
Assertions.assertThatCode(() -> JsonReader.read(json)).doesNotThrowAnyException();
}
}

@Test
void test_exceeding_maximum_nesting_depth() {
for (final String[] delimiters : new String[][] {{"[", "]"}, {"{\"key\":", "}"}}) {
final String json = nestedJson(delimiters[0], delimiters[1], 129);
Assertions.assertThatThrownBy(() -> JsonReader.read(json))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("maximum JSON nesting depth of 128 exceeded");
}
}

private String nestedJson(final String openingDelimiter, final String closingDelimiter, final int nestingDepth) {
final StringBuilder json = new StringBuilder();
for (int i = 0; i < nestingDepth; i++) {
json.append(openingDelimiter);
}
json.append("null");
for (int i = 0; i < nestingDepth; i++) {
json.append(closingDelimiter);
}
return json.toString();
}

private void test(final String json, final Object expected) {
// Wrapping the assertion one more time to decorate it with the input.
Assertions.assertThatCode(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@
import java.util.Objects;

/**
* A simple JSON parser mapping tokens to basic Java types.
* A simple JSON parser mapping tokens to basic Java types. This is an internal
* implementation detail intended for trusted Log4j input, not a general-purpose
* parser for untrusted input.
* <p>
* The type mapping is as follows:
* <p>
Expand All @@ -48,6 +50,8 @@
*/
public final class JsonReader {

private static final int MAX_NESTING_DEPTH = 128;

private enum Delimiter {
OBJECT_START("{"),

Expand Down Expand Up @@ -87,6 +91,8 @@ private static boolean exists(final Object token) {

private Object readToken;

private int nestingDepth;

private final StringBuilder buffer;

private JsonReader() {
Expand Down Expand Up @@ -269,54 +275,76 @@ private char readUnicodeChar() {
}

private Map<String, Object> readObject() {
final Map<String, Object> object = new LinkedHashMap<>();
String key = readObjectKey();
while (readToken != Delimiter.OBJECT_END) {
expectDelimiter(Delimiter.COLON, readToken());
if (readToken != Delimiter.OBJECT_END) {
final Object value = readToken();
object.put(key, value);
if (readToken() == Delimiter.COMMA) {
key = readObjectKey();
if (key == null || Delimiter.exists(key)) {
final String message = String.format(
"was expecting an object key at index %d: %s", readTokenStartIndex, readToken);
throw new IllegalArgumentException(message);
} else if (object.containsKey(key)) {
final String message =
String.format("found duplicate object key at index %d: %s", readTokenStartIndex, key);
throw new IllegalArgumentException(message);
checkNestingDepth();
nestingDepth++;
try {
final Map<String, Object> object = new LinkedHashMap<>();
String key = readObjectKey();
while (readToken != Delimiter.OBJECT_END) {
expectDelimiter(Delimiter.COLON, readToken());
if (readToken != Delimiter.OBJECT_END) {
final Object value = readToken();
object.put(key, value);
if (readToken() == Delimiter.COMMA) {
key = readObjectKey();
if (key == null || Delimiter.exists(key)) {
final String message = String.format(
"was expecting an object key at index %d: %s", readTokenStartIndex, readToken);
throw new IllegalArgumentException(message);
} else if (object.containsKey(key)) {
final String message = String.format(
"found duplicate object key at index %d: %s", readTokenStartIndex, key);
throw new IllegalArgumentException(message);
}
} else {
expectDelimiter(Delimiter.OBJECT_END, readToken);
}
} else {
expectDelimiter(Delimiter.OBJECT_END, readToken);
}
}
return object;
} finally {
nestingDepth--;
}
return object;
}

private List<Object> readArray() {
@SuppressWarnings("JdkObsolete")
final List<Object> array = new LinkedList<>();
readToken();
while (readToken != Delimiter.ARRAY_END) {
if (readToken instanceof Delimiter) {
final String message =
String.format("was expecting an array element at index %d: %s", readTokenStartIndex, readToken);
throw new IllegalArgumentException(message);
}
array.add(readToken);
if (readToken() == Delimiter.COMMA) {
if (readToken() == Delimiter.ARRAY_END) {
checkNestingDepth();
nestingDepth++;
try {
@SuppressWarnings("JdkObsolete")
final List<Object> array = new LinkedList<>();
readToken();
while (readToken != Delimiter.ARRAY_END) {
if (readToken instanceof Delimiter) {
final String message = String.format(
"was expecting an array element at index %d: %s", readTokenStartIndex, readToken);
"was expecting an array element at index %d: %s",
readTokenStartIndex, readToken);
throw new IllegalArgumentException(message);
}
} else {
expectDelimiter(Delimiter.ARRAY_END, readToken);
array.add(readToken);
if (readToken() == Delimiter.COMMA) {
if (readToken() == Delimiter.ARRAY_END) {
final String message = String.format(
"was expecting an array element at index %d: %s",
readTokenStartIndex, readToken);
throw new IllegalArgumentException(message);
}
} else {
expectDelimiter(Delimiter.ARRAY_END, readToken);
}
}
return array;
} finally {
nestingDepth--;
}
}

private void checkNestingDepth() {
if (nestingDepth >= MAX_NESTING_DEPTH) {
final String message = String.format(
"maximum JSON nesting depth of %d exceeded", MAX_NESTING_DEPTH);
throw new IllegalArgumentException(message);
}
return array;
}

private String readObjectKey() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Utility classes used by the JSON Template Layout. In particular,
* {@link org.apache.logging.log4j.layout.template.json.util.JsonReader} is an
* internal parser intended for trusted Log4j input, not untrusted input.
*/
@Export
@Version("2.25.3")
@Open("org.apache.logging.log4j.core")
Expand Down
12 changes: 12 additions & 0 deletions src/changelog/.2.x.x/4463_limit_json_reader_nesting_depth.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns="https://logging.apache.org/xml/ns"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
https://logging.apache.org/xml/ns
https://logging.apache.org/xml/ns/log4j-changelog-0.xsd"
type="fixed">
<issue id="4463" link="https://github.com/apache/logging-log4j2/issues/4463"/>
<description format="asciidoc">
Limit the nesting depth of the JSON reader to prevent stack overflows.
</description>
</entry>