Skip to content
Merged
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
32 changes: 29 additions & 3 deletions src/main/java/org/ini4j/BasicOptionMap.java
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,14 @@ public BasicOptionMap(boolean propertyFirstUpper) {
_propertyFirstUpper = propertyFirstUpper;
}

Config getConfig() {
return Config.getGlobal();
}

boolean hasVariableSubstitution(String value) {
return (value != null) && (value.indexOf(SUBST_CHAR) >= 0);
}

@Override
@SuppressWarnings(Warnings.UNCHECKED)
public <T> T getAll(Object key, Class<T> clazz) {
Expand Down Expand Up @@ -99,12 +107,16 @@ public String fetch(Object key, String defaultValue) {

@Override
public String fetch(Object key, int index) {
return fetchInternal(key, index, 0);
}

protected String fetchInternal(Object key, int index, int depth) {
String value = get(key, index);

if ((value != null) && (value.indexOf(SUBST_CHAR) >= 0)) {
if (hasVariableSubstitution(value)) {
StringBuilder buffer = new StringBuilder(value);

resolve(buffer);
resolve(buffer, depth);
value = buffer.toString();
}

Expand Down Expand Up @@ -238,6 +250,14 @@ BeanAccess newBeanAccess(String propertyNamePrefix) {
}

void resolve(StringBuilder buffer) {
resolve(buffer, 0);
}

void resolve(StringBuilder buffer, int depth) {
if (depth >= getConfig().getMaxResolveDepth()) {
throw new CircularReferenceException(getConfig().getMaxResolveDepth());
}

Matcher m = EXPRESSION.matcher(buffer);

while (m.find()) {
Expand All @@ -250,7 +270,13 @@ void resolve(StringBuilder buffer) {
} else if (name.startsWith(SYSTEM_PROPERTY_PREFIX)) {
value = Config.getSystemProperty(name.substring(SYSTEM_PROPERTY_PREFIX_LEN));
} else {
value = (index == -1) ? fetch(name) : fetch(name, index);
if (index == -1) {
// When no index specified, use the default behavior: get the last value
int len = length(name);
value = (len == 0) ? null : fetchInternal(name, len - 1, depth + 1);
} else {
value = fetchInternal(name, index, depth + 1);
}
}

if (value != null) {
Expand Down
21 changes: 21 additions & 0 deletions src/main/java/org/ini4j/BasicProfile.java
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@ public BasicProfile(boolean treeMode, boolean propertyFirstUpper) {
_propertyFirstUpper = propertyFirstUpper;
}

Config getConfig() {
return Config.getGlobal();
}

@Override
public String getComment() {
return _comment;
Expand Down Expand Up @@ -159,6 +163,14 @@ Section newSection(String name) {
}

void resolve(StringBuilder buffer, Section owner) {
resolve(buffer, owner, 0);
}

void resolve(StringBuilder buffer, Section owner, int depth) {
if (depth >= getConfig().getMaxResolveDepth()) {
throw new CircularReferenceException(getConfig().getMaxResolveDepth());
}

Matcher m = EXPRESSION.matcher(buffer);

while (m.find()) {
Expand All @@ -172,6 +184,15 @@ void resolve(StringBuilder buffer, Section owner) {
value = Config.getEnvironment(optionName);
} else if (SECTION_SYSTEM_PROPERTIES.equals(sectionName)) {
value = Config.getSystemProperty(optionName);
} else if (section instanceof BasicProfileSection) {
BasicProfileSection bps = (BasicProfileSection) section;
if (optionIndex == -1) {
// When no index specified, use the default behavior: get the last value
int len = bps.length(optionName);
value = (len == 0) ? null : bps.fetchInternal(optionName, len - 1, depth + 1);
} else {
value = bps.fetchInternal(optionName, optionIndex, depth + 1);
}
} else if (section != null) {
value =
(optionIndex == -1)
Expand Down
19 changes: 19 additions & 0 deletions src/main/java/org/ini4j/BasicProfileSection.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ protected BasicProfileSection(BasicProfile profile, String name) {
_childPattern = newChildPattern(name);
}

@Override
Config getConfig() {
return _profile.getConfig();
}

@Override
public Profile.Section getChild(String key) {
return _profile.get(childName(key));
Expand Down Expand Up @@ -116,6 +121,20 @@ void resolve(StringBuilder buffer) {
_profile.resolve(buffer, this);
}

@Override
protected String fetchInternal(Object key, int index, int depth) {
String value = get(key, index);

if (hasVariableSubstitution(value)) {
StringBuilder buffer = new StringBuilder(value);

_profile.resolve(buffer, this, depth);
value = buffer.toString();
}

return value;
}

private String childName(String key) {
StringBuilder buff = new StringBuilder(_name);

Expand Down
79 changes: 79 additions & 0 deletions src/main/java/org/ini4j/CircularReferenceException.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/*
* Copyright 2005,2009 Ivan SZKIBA
*
* Licensed 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.ini4j;

/**
* Exception thrown when a circular reference is detected during variable resolution.
*
* <p>This exception is thrown when the maximum recursion depth is exceeded while resolving variable
* substitutions in INI files or option maps. This typically indicates a circular reference in the
* configuration, such as:
*
* <pre>
* [section1]
* a = ${section2/b}
*
* [section2]
* b = ${section1/a}
* </pre>
*
* <p>This exception prevents {@link StackOverflowError} that would otherwise occur from infinite
* recursion.
*
* <p><b>Security Note:</b> This exception is part of the fix for CVE-2022-41404, which addressed a
* Denial of Service vulnerability where circular variable references could crash the JVM.
*
* @see Config#getMaxResolveDepth()
* @see Config#setMaxResolveDepth(int)
* @since 0.6.0
*/
public class CircularReferenceException extends IllegalArgumentException {
private static final long serialVersionUID = 1L;

/**
* Constructs a new circular reference exception with the specified maximum resolve depth.
*
* @param maxResolveDepth the maximum recursion depth that was exceeded
*/
public CircularReferenceException(int maxResolveDepth) {
super(
"Variable resolution depth limit ("
+ maxResolveDepth
+ ") exceeded. "
+ "Circular reference detected in variable substitution. "
+ "Check for circular dependencies in variable references. "
+ "Increase org.ini4j.config.maxResolveDepth if legitimate deep nesting is needed.");
}

/**
* Constructs a new circular reference exception with the specified detail message.
*
* @param message the detail message
*/
public CircularReferenceException(String message) {
super(message);
}

/**
* Constructs a new circular reference exception with the specified detail message and cause.
*
* @param message the detail message
* @param cause the cause
*/
public CircularReferenceException(String message, Throwable cause) {
super(message, cause);
}
}
26 changes: 26 additions & 0 deletions src/main/java/org/ini4j/Config.java
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ public class Config implements Cloneable, Serializable {
public static final String PROP_LINE_SEPARATOR = "lineSeparator";
public static final String PROP_COMMENT = "comment";
public static final String PROP_HEADER_COMMENT = "headerComment";
public static final String PROP_MAX_RESOLVE_DEPTH = "maxResolveDepth";
public static final boolean DEFAULT_EMPTY_OPTION = false;
public static final boolean DEFAULT_EMPTY_SECTION = false;
public static final boolean DEFAULT_GLOBAL_SECTION = false;
Expand All @@ -63,6 +64,7 @@ public class Config implements Cloneable, Serializable {
public static final char DEFAULT_PATH_SEPARATOR = '/';
public static final String DEFAULT_LINE_SEPARATOR = getSystemProperty("line.separator", "\n");
public static final Charset DEFAULT_FILE_ENCODING = Charset.forName("UTF-8");
public static final int DEFAULT_MAX_RESOLVE_DEPTH = 16;
private static final Config GLOBAL = new Config();
private static final long serialVersionUID = 2865793267410367814L;
private boolean _comment;
Expand All @@ -86,6 +88,7 @@ public class Config implements Cloneable, Serializable {
private boolean _strictOperator;
private boolean _tree;
private boolean _unnamedSection;
private int _maxResolveDepth;

public Config() {
reset();
Expand Down Expand Up @@ -295,6 +298,14 @@ public boolean isEscapeKeyOnly() {
return _escapeKeyOnly;
}

public int getMaxResolveDepth() {
return _maxResolveDepth;
}

public void setMaxResolveDepth(int value) {
_maxResolveDepth = value;
}

@Override
public Config clone() {
try {
Expand Down Expand Up @@ -326,6 +337,7 @@ public final void reset() {
_fileEncoding = getCharset(PROP_FILE_ENCODING, DEFAULT_FILE_ENCODING);
_comment = getBoolean(PROP_COMMENT, DEFAULT_COMMENT);
_headerComment = getBoolean(PROP_HEADER_COMMENT, DEFAULT_HEADER_COMMENT);
_maxResolveDepth = getInt(PROP_MAX_RESOLVE_DEPTH, DEFAULT_MAX_RESOLVE_DEPTH);
}

private boolean getBoolean(String name, boolean defaultValue) {
Expand All @@ -349,4 +361,18 @@ private Charset getCharset(String name, Charset defaultValue) {
private String getString(String name, String defaultValue) {
return getSystemProperty(KEY_PREFIX + name, defaultValue);
}

private int getInt(String name, int defaultValue) {
String value = getSystemProperty(KEY_PREFIX + name);

if (value == null) {
return defaultValue;
}

try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
return defaultValue;
}
}
}
38 changes: 38 additions & 0 deletions src/test/java/org/ini4j/BasicOptionMapTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.net.URI;
import org.ini4j.sample.Dwarf;
Expand Down Expand Up @@ -54,6 +55,43 @@ public void test_bug_2817403() throws Exception {
assertEquals("Joe@foo.bar", map.fetch("player.email"));
}

/*
* Test case for CVE-2022-41404
* https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2022-41404
*
* Tests that BasicOptionMap properly prevents infinite recursion when
* resolving circular variable references within a single option map.
*
* Example: a -> ${b}, b -> ${a}
*
* Thanks to [bingdian](https://sourceforge.net/u/bingdians/profile/)
* for the original vulnerability report on SourceForge ticket #56.
*/
@Test
public void testFetchCircularReference() {
OptionMap map = new BasicOptionMap();

// Setup circular dependency: a -> b -> a
map.put("a", "${b}");
map.put("b", "${a}");

try {
// Trigger the resolution
map.fetch("a");

fail("Should have thrown CircularReferenceException due to circular reference");

} catch (CircularReferenceException e) {
// SUCCESS: The fix prevents infinite recursion
assertTrue(
"Message should indicate circular reference detected",
e.getMessage().contains("Circular reference") || e.getMessage().contains("depth limit"));

} catch (StackOverflowError e) {
fail("Reproduced CVE-2022-41404: StackOverflowError occurred during variable resolution");
}
}

@Test
public void testAddPutNullAndString() {
OptionMap map = new BasicOptionMap();
Expand Down
40 changes: 40 additions & 0 deletions src/test/java/org/ini4j/BasicProfileSectionTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import org.ini4j.sample.Dwarf;
import org.ini4j.sample.Dwarfs;
Expand Down Expand Up @@ -88,4 +90,42 @@ public void testLoad() throws Exception {
Helper.assertEquals(DwarfsData.sleepy, dwarfs.getChild(Dwarfs.PROP_SLEEPY).as(Dwarf.class));
Helper.assertEquals(DwarfsData.sneezy, dwarfs.getChild(Dwarfs.PROP_SNEEZY).as(Dwarf.class));
}

/*
* Test case for CVE-2022-41404
* https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2022-41404
*
* Tests that BasicProfileSection properly prevents infinite recursion when
* resolving circular variable references across different sections.
*
* Example: section1/a -> ${section2/b}, section2/b -> ${section1/a}
*
* Thanks to [bingdian](https://sourceforge.net/u/bingdians/profile/)
* for the original vulnerability report on SourceForge ticket #56.
*/
@Test
public void testFetchCircularReferenceAcrossSections() {
Ini ini = new Ini();

// Setup circular dependency across sections
ini.put("section1", "a", "${section2/b}");
ini.put("section2", "b", "${section1/a}");

try {
// Trigger the resolution through a section
Profile.Section section1 = ini.get("section1");
section1.fetch("a");

fail("Should have thrown CircularReferenceException due to circular reference");

} catch (CircularReferenceException e) {
// SUCCESS: The fix prevents infinite recursion
assertTrue(
"Message should indicate circular reference detected",
e.getMessage().contains("Circular reference") || e.getMessage().contains("depth limit"));

} catch (StackOverflowError e) {
fail("Reproduced CVE-2022-41404: StackOverflowError occurred during variable resolution");
}
}
}
Loading