From 76fc1ad6b2aee4fa4fe648924290a8f515e9a1bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Iv=C3=A1n=20SZKIBA?= Date: Fri, 30 Jan 2026 18:39:31 +0000 Subject: [PATCH] fix(security): patch CVE-2022-41404 DoS vulnerability (CRITICAL) Implement configurable recursion depth limit to prevent stack overflow from circular variable references in INI file variable substitution. **Changes:** - Add CircularReferenceException for clear error reporting - Add Config.maxResolveDepth property (default: 16, configurable via -Dorg.ini4j.config.maxResolveDepth=N) - Implement depth tracking through fetchInternal() methods in BasicProfile and BasicOptionMap - Add package-protected getConfig() methods for config access - Add hasVariableSubstitution() helper to check for ${...} patterns **Security Impact:** CVE-2022-41404: Denial of Service via infinite recursion - Attack vector: Circular references like [a] x=${b/y} and [b] y=${a/x} - Impact: StackOverflowError crashes JVM - Mitigation: Throw CircularReferenceException when depth limit exceeded **Testing:** - Add 3 regression tests for circular reference detection: * BasicProfileTest.testFetchRecursiveInfiniteLoop * BasicOptionMapTest.testFetchCircularReference * BasicProfileSectionTest.testFetchCircularReferenceAcrossSections - All 206 tests passing **Acknowledgments:** Thanks to [bingdian](https://sourceforge.net/u/bingdians/profile/) for the original vulnerability report on SourceForge ticket #56. Additional thanks to Marc Lafon, paradox, and Craig for their contributions to identifying and documenting this issue. Fixes #6 --- src/main/java/org/ini4j/BasicOptionMap.java | 32 +++++++- src/main/java/org/ini4j/BasicProfile.java | 21 +++++ .../java/org/ini4j/BasicProfileSection.java | 19 +++++ .../org/ini4j/CircularReferenceException.java | 79 +++++++++++++++++++ src/main/java/org/ini4j/Config.java | 26 ++++++ .../java/org/ini4j/BasicOptionMapTest.java | 38 +++++++++ .../org/ini4j/BasicProfileSectionTest.java | 40 ++++++++++ src/test/java/org/ini4j/BasicProfileTest.java | 47 +++++++++++ 8 files changed, 299 insertions(+), 3 deletions(-) create mode 100644 src/main/java/org/ini4j/CircularReferenceException.java diff --git a/src/main/java/org/ini4j/BasicOptionMap.java b/src/main/java/org/ini4j/BasicOptionMap.java index c62de09..7a8730c 100644 --- a/src/main/java/org/ini4j/BasicOptionMap.java +++ b/src/main/java/org/ini4j/BasicOptionMap.java @@ -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 getAll(Object key, Class clazz) { @@ -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(); } @@ -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()) { @@ -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) { diff --git a/src/main/java/org/ini4j/BasicProfile.java b/src/main/java/org/ini4j/BasicProfile.java index 8e74f90..cc6f8bc 100644 --- a/src/main/java/org/ini4j/BasicProfile.java +++ b/src/main/java/org/ini4j/BasicProfile.java @@ -47,6 +47,10 @@ public BasicProfile(boolean treeMode, boolean propertyFirstUpper) { _propertyFirstUpper = propertyFirstUpper; } + Config getConfig() { + return Config.getGlobal(); + } + @Override public String getComment() { return _comment; @@ -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()) { @@ -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) diff --git a/src/main/java/org/ini4j/BasicProfileSection.java b/src/main/java/org/ini4j/BasicProfileSection.java index c524a82..066858e 100644 --- a/src/main/java/org/ini4j/BasicProfileSection.java +++ b/src/main/java/org/ini4j/BasicProfileSection.java @@ -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)); @@ -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); diff --git a/src/main/java/org/ini4j/CircularReferenceException.java b/src/main/java/org/ini4j/CircularReferenceException.java new file mode 100644 index 0000000..2a97d71 --- /dev/null +++ b/src/main/java/org/ini4j/CircularReferenceException.java @@ -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. + * + *

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: + * + *

+ * [section1]
+ * a = ${section2/b}
+ *
+ * [section2]
+ * b = ${section1/a}
+ * 
+ * + *

This exception prevents {@link StackOverflowError} that would otherwise occur from infinite + * recursion. + * + *

Security Note: 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); + } +} diff --git a/src/main/java/org/ini4j/Config.java b/src/main/java/org/ini4j/Config.java index bb254d2..5388722 100644 --- a/src/main/java/org/ini4j/Config.java +++ b/src/main/java/org/ini4j/Config.java @@ -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; @@ -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; @@ -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(); @@ -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 { @@ -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) { @@ -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; + } + } } diff --git a/src/test/java/org/ini4j/BasicOptionMapTest.java b/src/test/java/org/ini4j/BasicOptionMapTest.java index 8b56aa7..e68e854 100644 --- a/src/test/java/org/ini4j/BasicOptionMapTest.java +++ b/src/test/java/org/ini4j/BasicOptionMapTest.java @@ -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; @@ -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(); diff --git a/src/test/java/org/ini4j/BasicProfileSectionTest.java b/src/test/java/org/ini4j/BasicProfileSectionTest.java index c789355..9565463 100644 --- a/src/test/java/org/ini4j/BasicProfileSectionTest.java +++ b/src/test/java/org/ini4j/BasicProfileSectionTest.java @@ -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; @@ -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"); + } + } } diff --git a/src/test/java/org/ini4j/BasicProfileTest.java b/src/test/java/org/ini4j/BasicProfileTest.java index d0c367a..0d374bc 100644 --- a/src/test/java/org/ini4j/BasicProfileTest.java +++ b/src/test/java/org/ini4j/BasicProfileTest.java @@ -38,6 +38,53 @@ public class BasicProfileTest extends Ini4jCase { private static final String LOCATION_1 = "http://www.ini4j.org"; private static final String LOCATION_2 = "http://ini4j.org"; + /* + * Test case for CVE-2022-41404 + * https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2022-41404 + * + * Original issue: + * When resolving variables in INI files, it was possible to create a circular + * dependency that would lead to a StackOverflowError, effectively crashing the JVM. + * This happened because there was no limit on the depth of recursion when resolving variables. + * Fix: + * A maximum recursion depth was introduced to prevent infinite loops during variable resolution. + * When the limit is reached, an IllegalArgumentException is thrown instead of allowing + * the recursion to continue indefinitely. + * + * Thanks to [bingdian](https://sourceforge.net/u/bingdians/profile/) + * for the original vulnerability report on SourceForge ticket #56. + */ + @Test + public void testFetchRecursiveInfiniteLoop() { + // 1. Setup a circular dependency + // section/a -> section/b -> section/a ... + Ini ini = new Ini(); + ini.put("section", "a", "${section/b}"); + ini.put("section", "b", "${section/a}"); + + try { + // 2. Trigger the resolution + ini.fetch("section", "a"); + + // If we get here, the depth limit didn't work (or wasn't hit) + fail("Should have thrown CircularReferenceException due to infinite recursion"); + + } catch (CircularReferenceException e) { + // 3. SUCCESS (After Fix) + // The fix converts a crash into a safe exception + // System.out.println("Verified: " + e.getMessage()); + assertTrue( + "Message should indicate recursion/loop", + e.getMessage().contains("Circular reference") || e.getMessage().contains("depth limit")); + + } catch (StackOverflowError e) { + // 4. FAILURE (Before Fix) + // This block catches the JVM crash so JUnit can report it cleanly + // instead of effectively killing the test runner. + fail("Reproduced CVE-2022-41404: StackOverflowError occurred during variable resolution"); + } + } + /* * thanx to Gary Pampara for bug report */