diff --git a/core/src/main/java/hudson/util/RobustReflectionConverter.java b/core/src/main/java/hudson/util/RobustReflectionConverter.java index e3a9ed3370..d7c49d931e 100644 --- a/core/src/main/java/hudson/util/RobustReflectionConverter.java +++ b/core/src/main/java/hudson/util/RobustReflectionConverter.java @@ -44,6 +44,7 @@ import com.thoughtworks.xstream.io.HierarchicalStreamReader; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import com.thoughtworks.xstream.mapper.Mapper; import com.thoughtworks.xstream.security.InputManipulationException; +import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.diagnosis.OldDataMonitor; import hudson.model.JobProperty; @@ -93,6 +94,12 @@ public class RobustReflectionConverter implements Converter { static /* non-final for Groovy */ boolean DISABLE_XSTREAM_NOT_DESERIALIZABLE_CHECK = SystemProperties.getBoolean(RobustReflectionConverter.class.getName() + ".DISABLE_XSTREAM_NOT_DESERIALIZABLE_CHECK", false); static /* non-final for Groovy */ boolean TRANSIENT_FIELD_STRICT_MODE = SystemProperties.getBoolean(RobustReflectionConverter.class.getName() + ".TRANSIENT_FIELD_STRICT_MODE", false); + static /* non-final for Groovy */ boolean SKIP_FIELD_VALUE_ELEMENT_TYPE_CHECK = SystemProperties.getBoolean(RobustReflectionConverter.class.getName() + ".skipFieldValueElementTypeCheck", false); + static /* non-final for Groovy */ boolean ACCEPT_NON_ITERABLE_COLLECTIONS = SystemProperties.getBoolean(RobustReflectionConverter.class.getName() + ".acceptNonIterableCollections", false); + static /* non-final for Groovy */ int FIELD_VALUE_ELEMENT_CHECK_LIMIT = SystemProperties.getInteger(RobustReflectionConverter.class.getName() + ".fieldValueElementCheckLimit", 1_000_000); + static /* non-final for Groovy */ int FIELD_VALUE_ELEMENT_CHECK_WARNING_THRESHOLD = SystemProperties.getInteger(RobustReflectionConverter.class.getName() + ".fieldValueElementCheckWarningThreshold", FIELD_VALUE_ELEMENT_CHECK_LIMIT / 5); + private static final String FIELD_VALUE_ELEMENTS_CHECKED = RobustReflectionConverter.class.getName() + ".fieldValueElementsChecked"; + static /* non-final for Groovy */ boolean RECORD_FAILURES_FOR_ALL_AUTHENTICATIONS = SystemProperties.getBoolean(RobustReflectionConverter.class.getName() + ".recordFailuresForAllAuthentications", false); private static /* non-final for Groovy */ boolean RECORD_FAILURES_FOR_ADMINS = SystemProperties.getBoolean(RobustReflectionConverter.class.getName() + ".recordFailuresForAdmins", false); @@ -379,7 +386,7 @@ public class RobustReflectionConverter implements Converter { Class type = determineType(reader, fieldExistsInClass, result, fieldName, classDefiningField); final Object value; if (fieldExistsInClass) { - Field field = reflectionProvider.getField(result.getClass(), fieldName); + Field field = reflectionProvider.getField(classDefiningField != null ? classDefiningField : result.getClass(), fieldName); // JobProperty as a workaround for promoted-builds plugin's `JobPropertyImpl` being both if (PersistenceRoot.class.isAssignableFrom(type) && !JobProperty.class.isAssignableFrom(type) && !isSafePersistenceRootReference(reader, type)) { final String msg = "Refusing to unmarshal PersistenceRoot subtype '" + type.getName() + "' into field '" @@ -389,6 +396,9 @@ public class RobustReflectionConverter implements Converter { throw new CriticalXStreamException(new XStreamException(msg)); } value = unmarshalField(context, result, type, field); + if (value != null) { + checkFieldValueElementTypes(context, reader, field, value); + } // TODO the reflection provider should have returned the proper field in first place .... Class definedType = reflectionProvider.getFieldType(result, fieldName, classDefiningField); if (!definedType.isPrimitive()) { @@ -453,6 +463,22 @@ public class RobustReflectionConverter implements Converter { } context.put("ReadError", null); } + + if (context.get("Saveable") == result) { + // If we're at the top level, emit a log message about the number of collection elements we type-checked. + Integer checked = (Integer) context.get(FIELD_VALUE_ELEMENTS_CHECKED); + if (checked != null) { + if (checked > FIELD_VALUE_ELEMENT_CHECK_WARNING_THRESHOLD) { + // Emit a warning when we're getting close to the limit + LOGGER.log(Level.WARNING, + "Collection type checked {0} elements while deserializing {1}. The limit is {2} and deserialization will fail when exceeded. It can be changed by setting the system property `" + + RobustReflectionConverter.class.getName() + ".fieldValueElementCheckLimit`", + new Object[] { checked, result.getClass().getName(), FIELD_VALUE_ELEMENT_CHECK_LIMIT }); + } else { + LOGGER.log(FINE, "Collection type checked {0} elements while deserializing {1}", new Object[] { checked, result.getClass().getName() }); + } + } + } return result; } @@ -606,7 +632,7 @@ public class RobustReflectionConverter implements Converter { * Extracts the element type from a generic list type. * For example, given {@code DescribableList>}, returns {@code Foo.class}. */ - private Class extractElementType(Type genericType, Class listClass) { + static Class extractElementType(Type genericType, Class listClass) { if (genericType != null && listClass.isAssignableFrom(Types.erasure(genericType))) { var baseType = Types.getBaseClass(genericType, listClass); // Get the first type argument (the element type T) @@ -616,6 +642,84 @@ public class RobustReflectionConverter implements Converter { return null; } + /** + * Validates the elements (or keys and values) of a Collection, Map, or CopyOnWriteList field value + * against the type arguments declared on the field, regardless of which converter produced the value. + * Rejects the whole value rather than individual elements, as the container may be immutable. + * + * @throws ConversionException if an element has an invalid type + */ + private void checkFieldValueElementTypes(UnmarshallingContext context, HierarchicalStreamReader reader, Field field, Object value) { + if (SKIP_FIELD_VALUE_ELEMENT_TYPE_CHECK) { + return; + } + Type genericType = field.getGenericType(); + if (value instanceof Map map) { + if (Map.class.isAssignableFrom(Types.erasure(genericType))) { + var baseType = Types.getBaseClass(genericType, Map.class); + try { + checkFieldValueElements(context, reader, field, map.keySet(), + Types.erasure(Types.getTypeArgument(baseType, 0, Object.class))); + checkFieldValueElements(context, reader, field, map.values(), + Types.erasure(Types.getTypeArgument(baseType, 1, Object.class))); + } catch (XStreamException e) { + throw e; + } catch (RuntimeException e) { + if (ACCEPT_NON_ITERABLE_COLLECTIONS) { + return; + } + var exception = new ConversionException( + "Map field '" + field.getName() + "' cannot be validated: broken internal state after deserialization", e); + exception.add("converter-type", getClass().getName()); + reader.appendErrors(exception); + throw exception; + } + } + } else if (value instanceof Collection collection) { + checkFieldValueElements(context, reader, field, collection, extractElementType(genericType, Collection.class)); + } else if (value instanceof CopyOnWriteList cowl) { + checkFieldValueElements(context, reader, field, cowl, extractElementType(genericType, CopyOnWriteList.class)); + } + } + + private void checkFieldValueElements(UnmarshallingContext context, HierarchicalStreamReader reader, Field field, + Iterable elements, @CheckForNull Class elementType) { + if (elementType == null || elementType == Object.class) { + return; + } + try { + for (Object element : elements) { + Integer checked = (Integer) context.get(FIELD_VALUE_ELEMENTS_CHECKED); + int count = (checked != null ? checked : 0) + 1; + if (count > FIELD_VALUE_ELEMENT_CHECK_LIMIT) { + throw new InputManipulationException( + "Validation budget exceeded: checked " + count + " collection/map elements during deserialization (limit: " + + FIELD_VALUE_ELEMENT_CHECK_LIMIT + ")"); + } + context.put(FIELD_VALUE_ELEMENTS_CHECKED, count); + if (element != null && !elementType.isInstance(element)) { + var exception = new ConversionException("Invalid element type in value for field: " + field.getName()); + exception.add("required-type", elementType.getName()); + exception.add("class", element.getClass().getName()); + exception.add("converter-type", getClass().getName()); + reader.appendErrors(exception); + throw exception; + } + } + } catch (XStreamException e) { + throw e; + } catch (RuntimeException e) { + if (ACCEPT_NON_ITERABLE_COLLECTIONS) { + return; + } + var exception = new ConversionException( + "Collection field '" + field.getName() + "' cannot be validated: broken internal state after deserialization", e); + exception.add("converter-type", getClass().getName()); + reader.appendErrors(exception); + throw exception; + } + } + private void writeValueToImplicitCollection( HierarchicalStreamReader reader, UnmarshallingContext context, diff --git a/core/src/test/java/hudson/util/PersistedListTest.java b/core/src/test/java/hudson/util/PersistedListTest.java index 6f0b1916d0..bd507ba810 100644 --- a/core/src/test/java/hudson/util/PersistedListTest.java +++ b/core/src/test/java/hudson/util/PersistedListTest.java @@ -9,6 +9,7 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.nullValue; import hudson.model.Describable; import hudson.model.Descriptor; @@ -36,7 +37,6 @@ class PersistedListTest { assertThat(list, empty()); } - // Arguably not the "expected" behavior. @Test void defaultSerializationForSubclass() { XStream2 xstream = new XStream2(); @@ -60,9 +60,7 @@ class PersistedListTest { final Object o = xstream.fromXML(craftedXml); assertThat(o, instanceOf(Data.class)); - final PersistedList list = ((Data) o).strings; - assertThat(list, instanceOf(PersistedListSubtype.class)); - assertThat(list, contains(instanceOf(Integer.class))); // TODO FIXME this seems wrong + assertThat(((Data) o).strings, nullValue()); } @Test @@ -98,8 +96,7 @@ class PersistedListTest { """; final Object fromXML = xstream.fromXML(serialized); assertThat(fromXML, instanceOf(Data.class)); - final PersistedList strings = ((Data) fromXML).strings; - assertThat(strings, contains(instanceOf(Integer.class))); // TODO FIXME this seems wrong + assertThat(((Data) fromXML).strings, nullValue()); } @Test diff --git a/core/src/test/java/hudson/util/RobustReflectionConverterTest.java b/core/src/test/java/hudson/util/RobustReflectionConverterTest.java index 5b60420081..36f9e7b766 100644 --- a/core/src/test/java/hudson/util/RobustReflectionConverterTest.java +++ b/core/src/test/java/hudson/util/RobustReflectionConverterTest.java @@ -25,10 +25,14 @@ package hudson.util; import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.nullValue; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -44,30 +48,37 @@ import com.thoughtworks.xstream.mapper.Mapper; import com.thoughtworks.xstream.security.InputManipulationException; import hudson.model.Saveable; import java.io.IOException; +import java.io.Serializable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; +import java.lang.reflect.Type; import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; import java.util.HashSet; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; import jenkins.util.xstream.CriticalXStreamException; -import org.hamcrest.Matchers; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.jvnet.hudson.test.Issue; +import org.jvnet.tiger_types.Types; /** * @author Kohsuke Kawaguchi */ class RobustReflectionConverterTest { private final boolean originalRecordFailures = RobustReflectionConverter.RECORD_FAILURES_FOR_ALL_AUTHENTICATIONS; + private final boolean originalSkipFieldCheck = RobustReflectionConverter.SKIP_FIELD_VALUE_ELEMENT_TYPE_CHECK; + private final boolean originalAcceptNonIterable = RobustReflectionConverter.ACCEPT_NON_ITERABLE_COLLECTIONS; static { Logger.getLogger(RobustReflectionConverter.class.getName()).setLevel(Level.OFF); @@ -76,11 +87,17 @@ class RobustReflectionConverterTest { @BeforeEach void before() { RobustReflectionConverter.RECORD_FAILURES_FOR_ALL_AUTHENTICATIONS = true; + RobustReflectionConverter.SKIP_FIELD_VALUE_ELEMENT_TYPE_CHECK = false; + RobustReflectionConverter.ACCEPT_NON_ITERABLE_COLLECTIONS = false; + ConstructionDetector.wasConstructed.set(false); } @AfterEach void after() { RobustReflectionConverter.RECORD_FAILURES_FOR_ALL_AUTHENTICATIONS = originalRecordFailures; + RobustReflectionConverter.SKIP_FIELD_VALUE_ELEMENT_TYPE_CHECK = originalSkipFieldCheck; + RobustReflectionConverter.ACCEPT_NON_ITERABLE_COLLECTIONS = originalAcceptNonIterable; + ConstructionDetector.wasConstructed.set(false); } @Test @@ -144,7 +161,7 @@ class RobustReflectionConverterTest { xs.alias("hold", Hold.class); xs.addImplicitCollection(Hold.class, "items", "item", String.class); Hold h = (Hold) xs.fromXML("ab"); - assertThat(h.items, Matchers.containsInAnyOrder("a", "b")); + assertThat(h.items, containsInAnyOrder("a", "b")); assertEquals(""" a @@ -152,21 +169,6 @@ class RobustReflectionConverterTest { """, xs.toXML(h)); } - @Disabled("Throws an NPE in writeValueToImplicitCollection. Issue has existed since RobustReflectionConverter was created.") - @Test - void implicitCollectionsAllowNullElements() { - XStream2 xs = new XStream2(); - xs.alias("hold", Hold.class); - xs.addImplicitCollection(Hold.class, "items", "item", String.class); - Hold h = (Hold) xs.fromXML("b"); - assertThat(h.items, Matchers.containsInAnyOrder(null, "b")); - assertEquals(""" - - - b - """, xs.toXML(h)); - } - @Issue("JENKINS-63343") @Test void robustAgainstImplicitCollectionElementsWithBadTypes() { @@ -462,4 +464,711 @@ class RobustReflectionConverterTest { } } } + + public static class ConstructionDetector implements Serializable { + static final AtomicBoolean wasConstructed = new AtomicBoolean(false); + String value; + + @SuppressWarnings("unused") + private Object readResolve() { + wasConstructed.set(true); + return this; + } + } + + public static class HoldTyped implements Saveable { + List items; + Set set; + Map map; + CopyOnWriteList cowl; + + @Override + public void save() {} + } + + private static XStream2 newXStream() { + XStream2 xs = new XStream2(); + xs.alias("hold", HoldTyped.class); + xs.alias("detector", ConstructionDetector.class); + return xs; + } + + @Test + @Issue("SECURITY-4225") + void catchAllRejectsWrongTypedElementInArrayList() { + var h = (HoldTyped) newXStream().fromXML( + "bad"); + assertNotNull(h.items, "RobustCollectionConverter already dropped the bad element; catch-all sees empty list"); + assertTrue(h.items.isEmpty()); + } + + @Test + @Issue("SECURITY-4225") + void catchAllRejectsWrongTypedElementInImmutableList() { + var h = (HoldTyped) newXStream().fromXML( + "bad"); + assertThat(h.items, nullValue()); + assertTrue(ConstructionDetector.wasConstructed.get()); + } + + @Test + @Issue("SECURITY-4225") + void catchAllRejectsWrongTypedElementInImmutableSet() { + var h = (HoldTyped) newXStream().fromXML( + "bad"); + assertThat(h.set, nullValue()); + } + + @Test + @Issue("SECURITY-4225") + void catchAllRejectsWrongTypedElementInImmutableSortedSet() { + var h = (HoldTyped) newXStream().fromXML( + "bad"); + assertThat(h.set, nullValue()); + } + + @Test + @Issue("SECURITY-4225") + void catchAllRejectsWrongTypedElementInSingletonList() { + var h = (HoldTyped) newXStream().fromXML( + "bad"); + assertThat(h.items, nullValue()); + assertTrue(ConstructionDetector.wasConstructed.get()); + } + + @Test + @Issue("SECURITY-4225") + void catchAllRejectsWrongTypedValueInImmutableMap() { + var h = (HoldTyped) newXStream().fromXML( + "" + + "kbad" + + ""); + assertThat(h.map, nullValue()); + } + + @Test + @Issue("SECURITY-4225") + void catchAllRejectsWrongTypedKeyInImmutableMap() { + var h = (HoldTyped) newXStream().fromXML( + "" + + "badv" + + ""); + assertThat(h.map, nullValue()); + } + + @Test + @Issue("SECURITY-4225") + void catchAllRejectsWrongTypedValueInCopyOnWriteMapHash() { + var h = (HoldTyped) newXStream().fromXML( + "" + + "kbad" + + ""); + assertThat(h.map, nullValue()); + } + + @Test + @Issue("SECURITY-4225") + void catchAllRejectsWrongTypedValueInHashMap() { + var h = (HoldTyped) newXStream().fromXML( + "kbad"); + assertNotNull(h.map); + assertTrue(h.map.isEmpty()); + } + + @Test + @Issue("SECURITY-4225") + void catchAllRejectsWrongTypedValueInSingletonMap() { + var h = (HoldTyped) newXStream().fromXML( + "" + + "kbad" + + ""); + assertThat(h.map, nullValue()); + } + + @Test + @Issue("SECURITY-4225") + void validDataAcceptedInImmutableList() { + var h = (HoldTyped) newXStream().fromXML( + "abc"); + assertThat(h.items, equalTo(List.of("abc"))); + } + + @Test + @Issue("SECURITY-4225") + void validDataAcceptedInImmutableSet() { + var h = (HoldTyped) newXStream().fromXML( + "abc"); + assertThat(h.set, equalTo(Set.of("abc"))); + } + + @Test + @Issue("SECURITY-4225") + void validDataAcceptedInImmutableMap() { + var h = (HoldTyped) newXStream().fromXML( + "" + + "kv" + + ""); + assertThat(h.map, equalTo(Map.of("k", "v"))); + } + + @Test + @Issue("SECURITY-4225") + void validDataAcceptedInCopyOnWriteMapHash() { + var h = (HoldTyped) newXStream().fromXML( + "" + + "kv" + + ""); + assertNotNull(h.map); + assertThat(h.map.get("k"), equalTo("v")); + } + + @Test + @Issue("SECURITY-4225") + void escapeHatchDisablesCatchAll() { + RobustReflectionConverter.SKIP_FIELD_VALUE_ELEMENT_TYPE_CHECK = true; + var h = (HoldTyped) newXStream().fromXML( + "bad"); + assertNotNull(h.items); + assertFalse(h.items.isEmpty()); + assertTrue(ConstructionDetector.wasConstructed.get()); + } + + @Test + @Issue("SECURITY-4225") + void escapeHatchDisablesCatchAllForSingletonList() { + RobustReflectionConverter.SKIP_FIELD_VALUE_ELEMENT_TYPE_CHECK = true; + var h = (HoldTyped) newXStream().fromXML( + "bad"); + assertNotNull(h.items); + assertTrue(ConstructionDetector.wasConstructed.get()); + } + + @Test + @Issue("SECURITY-4225") + void catchAllRejectsEntireImmutableListWithMixedElements() { + var h = (HoldTyped) newXStream().fromXML( + """ + + good + bad + also-good + """); + assertThat(h.items, nullValue()); + } + + @Test + @Issue("SECURITY-4225") + void perConverterCheckDropsIndividualBadElements() { + var h = (HoldTyped) newXStream().fromXML( + """ + + good + bad + also-good + """); + assertNotNull(h.items); + assertThat("RobustCollectionConverter drops the bad element individually", h.items, equalTo(List.of("good", "also-good"))); + assertTrue(ConstructionDetector.wasConstructed.get(), + "RobustCollectionConverter constructs the object before checking its type"); + } + + public static class DecoupledList extends ArrayList { + } + + @Test + void extractElementTypeResolvesClassHierarchyNotFieldTypeParam() { + // DecoupledList extends ArrayList: the element type is String, not T + assertThat(RobustReflectionConverter.extractElementType( + HoldDecoupled.class.getDeclaredFields()[0].getGenericType(), Collection.class), + equalTo(String.class)); + } + + public static class HoldDecoupled { + DecoupledList items; + } + + public static class ThreadedList extends ArrayList { + } + + @Test + @Issue("SECURITY-4225") + void extractElementTypeResolvesThreadedTypeParam() { + // ThreadedList extends ArrayList: with field ThreadedList, element type is String + assertThat(RobustReflectionConverter.extractElementType( + HoldThreaded.class.getDeclaredFields()[0].getGenericType(), Collection.class), + equalTo(String.class)); + } + + public static class HoldThreaded { + ThreadedList items; + } + + public static class HoldRawList implements Saveable { + @SuppressWarnings("rawtypes") + List items; + + @Override + public void save() {} + } + + @Test + @Issue("SECURITY-4225") + void catchAllSkipsRawTypeFields() { + XStream2 xs = newXStream(); + xs.alias("hr", HoldRawList.class); + var h = (HoldRawList) xs.fromXML( + "
42abc"); + assertNotNull(h.items); + assertThat(h.items.size(), equalTo(2)); + } + + public static class HoldNumbers implements Saveable { + List numbers; + + @Override + public void save() {} + } + + @Test + @Issue("SECURITY-4225") + void catchAllAcceptsSubtypesOfDeclaredElementType() { + XStream2 xs = newXStream(); + xs.alias("hn", HoldNumbers.class); + var h = (HoldNumbers) xs.fromXML( + """ + + 1 + 2 + 3.0 + 4.0 + 5 + 6 + """); + assertNotNull(h.numbers); + assertThat(h.numbers.size(), equalTo(6)); + assertThat(h.numbers.get(0), instanceOf(Integer.class)); + assertThat(h.numbers.get(1), instanceOf(Long.class)); + } + + public static class HoldSerializables implements Saveable { + List items; + + @Override + public void save() {} + } + + @Test + @Issue("SECURITY-4225") + void catchAllAcceptsInterfaceSubtypes() { + XStream2 xs = newXStream(); + xs.alias("hs", HoldSerializables.class); + var h = (HoldSerializables) xs.fromXML( + "abc42"); + assertNotNull(h.items); + assertThat(h.items.size(), equalTo(2)); + } + + @Test + @Issue("SECURITY-4225") + void catchAllRejectsNonSerializable() { + XStream2 xs = newXStream(); + xs.alias("hs", HoldSerializables.class); + xs.alias("non-ser", NonSerializableType.class); + var h = (HoldSerializables) xs.fromXML( + ""); + assertNotNull(h.items, "RobustCollectionConverter already dropped the bad element; catch-all sees empty list"); + assertTrue(h.items.isEmpty()); + } + + public static class NonSerializableType { + } + + public static class HoldNestedList implements Saveable { + List> nested; + + @Override + public void save() {} + } + + @Test + @Issue("SECURITY-4225") + void catchAllChecksOuterElementTypeOnly() { + XStream2 xs = newXStream(); + xs.alias("hn", HoldNestedList.class); + var h = (HoldNestedList) xs.fromXML( + """ + + 12 + a + """); + assertNotNull(h.nested); + assertThat(h.nested.size(), equalTo(2)); + } + + @Test + @Issue("SECURITY-4225") + void catchAllRejectsNonListElementInNestedList() { + XStream2 xs = newXStream(); + xs.alias("hn", HoldNestedList.class); + var h = (HoldNestedList) xs.fromXML( + "not-a-list"); + assertNotNull(h.nested, "RobustCollectionConverter already dropped the non-List element"); + assertTrue(h.nested.isEmpty()); + } + + public static class DecoupledMap extends HashMap { + } + + public static class HoldDecoupledMap { + DecoupledMap map; + } + + public static class ThreadedMap extends HashMap { + } + + public static class HoldThreadedMap { + ThreadedMap map; + } + + @Test + @Issue("SECURITY-4225") + void extractElementTypeResolvesDecoupledMapKeyType() throws Exception { + // DecoupledMap extends HashMap: key type is String, not Long + Type gt = HoldDecoupledMap.class.getDeclaredField("map").getGenericType(); + var baseType = Types.getBaseClass(gt, Map.class); + assertThat(Types.erasure(Types.getTypeArgument(baseType, 0, Object.class)), equalTo(String.class)); + assertThat(Types.erasure(Types.getTypeArgument(baseType, 1, Object.class)), equalTo(Integer.class)); + } + + @Test + @Issue("SECURITY-4225") + void extractElementTypeResolvesThreadedMapKeyType() throws Exception { + // ThreadedMap extends HashMap: key type is String, value type is Integer + Type gt = HoldThreadedMap.class.getDeclaredField("map").getGenericType(); + var baseType = Types.getBaseClass(gt, Map.class); + assertThat(Types.erasure(Types.getTypeArgument(baseType, 0, Object.class)), equalTo(String.class)); + assertThat(Types.erasure(Types.getTypeArgument(baseType, 1, Object.class)), equalTo(Integer.class)); + } + + @Test + @Issue("SECURITY-4225") + void catchAllSkipsRawMapFields() { + XStream2 xs = newXStream(); + xs.alias("hrm", HoldRawMap.class); + var h = (HoldRawMap) xs.fromXML( + "1true"); + assertNotNull(h.map); + assertThat(h.map.size(), equalTo(1)); + } + + public static class HoldRawMap implements Saveable { + @SuppressWarnings("rawtypes") + Map map; + + @Override + public void save() {} + } + + @Test + @Issue("SECURITY-4225") + void cowlConverterDropsBadElement() { + var h = (HoldTyped) newXStream().fromXML( + "bad"); + assertNotNull(h.cowl, "CopyOnWriteList.ConverterImpl drops the bad element; catch-all sees empty COWL"); + assertThat(h.cowl.getView(), equalTo(List.of())); + } + + @Test + @Issue("SECURITY-4225") + void validDataAcceptedInCOWL() { + var h = (HoldTyped) newXStream().fromXML( + "abcdef"); + assertNotNull(h.cowl); + assertThat(h.cowl.getView(), equalTo(List.of("abc", "def"))); + } + + @Test + @Issue("SECURITY-4225") + void cowlConverterDropsBadElementFromMixed() { + var h = (HoldTyped) newXStream().fromXML( + "goodbad"); + assertNotNull(h.cowl, "CopyOnWriteList.ConverterImpl drops the bad element individually"); + assertThat(h.cowl.getView(), equalTo(List.of("good"))); + } + + public static class DecoupledCOWL extends CopyOnWriteList { + } + + public static class HoldDecoupledCOWL { + DecoupledCOWL items; + } + + public static class ThreadedCOWL extends CopyOnWriteList { + } + + public static class HoldThreadedCOWL { + ThreadedCOWL items; + } + + @Test + @Issue("SECURITY-4225") + void extractElementTypeResolvesCOWLDecoupledType() { + // DecoupledCOWL extends CopyOnWriteList: element type is String, not Integer + assertThat(RobustReflectionConverter.extractElementType( + HoldDecoupledCOWL.class.getDeclaredFields()[0].getGenericType(), CopyOnWriteList.class), + equalTo(String.class)); + } + + @Test + @Issue("SECURITY-4225") + void extractElementTypeResolvesCOWLThreadedType() { + // ThreadedCOWL extends CopyOnWriteList: element type is String + assertThat(RobustReflectionConverter.extractElementType( + HoldThreadedCOWL.class.getDeclaredFields()[0].getGenericType(), CopyOnWriteList.class), + equalTo(String.class)); + } + + @Test + @Issue("SECURITY-4225") + void catchAllSkipsRawCOWLFields() { + XStream2 xs = newXStream(); + xs.alias("hrc", HoldRawCOWL.class); + var h = (HoldRawCOWL) xs.fromXML( + "42abc"); + assertNotNull(h.items); + assertThat(h.items.getView().size(), equalTo(2)); + } + + public static class HoldRawCOWL implements Saveable { + @SuppressWarnings("rawtypes") + CopyOnWriteList items; + + @Override + public void save() {} + } + + /** + * A CopyOnWriteList subclass. Since no converter is registered for it, XStream uses + * RobustReflectionConverter which creates the object via reflection without calling + * CopyOnWriteList's constructor. The internal {@code core} field stays null, making + * the list non-iterable. + */ + public static class BrokenCOWLSubclass extends CopyOnWriteList { + } + + public static class HoldBrokenCOWL implements Saveable { + BrokenCOWLSubclass items; + + @Override + public void save() {} + } + + @Test + @Issue("SECURITY-4225") + void nonIterableCollectionIsRejected() { + XStream2 xs = newXStream(); + xs.alias("hb", HoldBrokenCOWL.class); + // The BrokenCOWLSubclass is deserialized by RobustReflectionConverter (no dedicated converter), + // leaving core=null. The catch-all cannot iterate it and rejects the field. + var h = (HoldBrokenCOWL) xs.fromXML(""); + assertThat(h.items, nullValue()); + } + + @Test + @Issue("SECURITY-4225") + void nonIterableCollectionAcceptedWithEscapeHatch() { + RobustReflectionConverter.ACCEPT_NON_ITERABLE_COLLECTIONS = true; + XStream2 xs = newXStream(); + xs.alias("hb", HoldBrokenCOWL.class); + var h = (HoldBrokenCOWL) xs.fromXML(""); + assertNotNull(h.items, "With escape hatch, broken collection is accepted"); + assertThrows(NullPointerException.class, () -> h.items.size()); + } + + @Test + @Issue("SECURITY-4225") + void nonIterableEscapeHatchDoesNotSuppressTypeMismatch() { + RobustReflectionConverter.ACCEPT_NON_ITERABLE_COLLECTIONS = true; + var h = (HoldTyped) newXStream().fromXML( + "bad"); + assertThat("Type mismatch is still rejected even with the non-iterable escape hatch enabled", + h.items, nullValue()); + } + + public static class BrokenMap implements Map { + @Override public Set keySet() { + throw new NullPointerException("broken"); + } + + @Override public Collection values() { + throw new NullPointerException("broken"); + } + + @Override public int size() { + return 0; + } + + @Override public boolean isEmpty() { + return true; + } + + @Override public boolean containsKey(Object key) { + return false; + } + + @Override public boolean containsValue(Object value) { + return false; + } + + @Override public V get(Object key) { + return null; + } + + @Override public V put(K key, V value) { + return null; + } + + @Override public V remove(Object key) { + return null; + } + + @Override public void putAll(Map m) { + } + + @Override public void clear() { + } + + @Override public Set> entrySet() { + return Set.of(); + } + } + + public static class HoldBrokenMap implements Saveable { + BrokenMap map; + + @Override + public void save() {} + } + + @Test + @Issue("SECURITY-4225") + void nonIterableMapIsRejected() { + XStream2 xs = newXStream(); + xs.alias("hbm", HoldBrokenMap.class); + var h = (HoldBrokenMap) xs.fromXML(""); + assertThat(h.map, nullValue()); + } + + @Test + @Issue("SECURITY-4225") + void nonIterableMapAcceptedWithEscapeHatch() { + RobustReflectionConverter.ACCEPT_NON_ITERABLE_COLLECTIONS = true; + XStream2 xs = newXStream(); + xs.alias("hbm", HoldBrokenMap.class); + var h = (HoldBrokenMap) xs.fromXML(""); + assertThat(h.map, not(nullValue())); + } + + @Test + @Issue("SECURITY-4225") + void validationBudgetRejectsOversizedCollection() { + int originalLimit = RobustReflectionConverter.FIELD_VALUE_ELEMENT_CHECK_LIMIT; + try { + RobustReflectionConverter.FIELD_VALUE_ELEMENT_CHECK_LIMIT = 3; + XStream2 xs = newXStream(); + // 5 valid elements, but budget is 3 — field must be rejected + assertThrows(CriticalXStreamException.class, () -> xs.fromXML( + "" + + "abcde" + + "")); + } finally { + RobustReflectionConverter.FIELD_VALUE_ELEMENT_CHECK_LIMIT = originalLimit; + } + } + + @Test + @Issue("SECURITY-4225") + void validationBudgetAcceptsWithinLimit() { + int originalLimit = RobustReflectionConverter.FIELD_VALUE_ELEMENT_CHECK_LIMIT; + try { + RobustReflectionConverter.FIELD_VALUE_ELEMENT_CHECK_LIMIT = 10; + XStream2 xs = newXStream(); + var h = (HoldTyped) xs.fromXML( + "" + + "abc" + + ""); + assertThat(h.items, equalTo(List.of("a", "b", "c"))); + } finally { + RobustReflectionConverter.FIELD_VALUE_ELEMENT_CHECK_LIMIT = originalLimit; + } + } + + @Test + @Issue("SECURITY-4225") + void validationBudgetIsCumulativeAcrossFields() { + int originalLimit = RobustReflectionConverter.FIELD_VALUE_ELEMENT_CHECK_LIMIT; + try { + RobustReflectionConverter.FIELD_VALUE_ELEMENT_CHECK_LIMIT = 5; + XStream2 xs = newXStream(); + // Two fields: items (3 elements) + set (3 elements) = 6 total, budget is 5 + assertThrows(CriticalXStreamException.class, () -> xs.fromXML( + "" + + "abc" + + "xyz" + + "")); + } finally { + RobustReflectionConverter.FIELD_VALUE_ELEMENT_CHECK_LIMIT = originalLimit; + } + } + + private static String immutableListXml(int count) { + var sb = new StringBuilder(""); + for (int i = 0; i < count; i++) { + sb.append("e").append(i).append(""); + } + sb.append(""); + return sb.toString(); + } + + @Test + @Issue("SECURITY-4225") + void largeCollectionBelowDefaultLimitAccepted() { + var h = (HoldTyped) newXStream().fromXML(immutableListXml(999_999)); + assertNotNull(h.items); + assertThat(h.items.size(), equalTo(999_999)); + } + + @Test + @Issue("SECURITY-4225") + void largeCollectionAboveDefaultLimitRejected() { + assertThrows(CriticalXStreamException.class, () -> newXStream().fromXML(immutableListXml(1_000_001))); + } + + public static class ParentWithList implements Saveable { + List items; + + @Override + public void save() {} + } + + public static class ChildHidingList extends ParentWithList implements Saveable { + List items; + + @Override + public void save() {} + } + + @Test + @Issue("SECURITY-4225") + void hiddenFieldRoundTripPreservesParentFieldType() { + XStream2 xs = newXStream(); + xs.alias("child", ChildHidingList.class); + var h = (ChildHidingList) xs.fromXML( + "" + + "12" + + "a" + + ""); + assertThat(((ParentWithList) h).items, equalTo(List.of(1, 2))); + assertThat(h.items, equalTo(List.of("a"))); + } } diff --git a/test/src/test/java/hudson/util/Security4225Test.java b/test/src/test/java/hudson/util/Security4225Test.java new file mode 100644 index 0000000000..534145d9fe --- /dev/null +++ b/test/src/test/java/hudson/util/Security4225Test.java @@ -0,0 +1,60 @@ +package hudson.util; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import hudson.model.Saveable; +import java.util.List; +import java.util.logging.Level; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.jvnet.hudson.test.Issue; +import org.jvnet.hudson.test.LogRecorder; + +class Security4225Test { + + private final int originalLimit = RobustReflectionConverter.FIELD_VALUE_ELEMENT_CHECK_LIMIT; + private final int originalThreshold = RobustReflectionConverter.FIELD_VALUE_ELEMENT_CHECK_WARNING_THRESHOLD; + + @AfterEach + void restore() { + RobustReflectionConverter.FIELD_VALUE_ELEMENT_CHECK_LIMIT = originalLimit; + RobustReflectionConverter.FIELD_VALUE_ELEMENT_CHECK_WARNING_THRESHOLD = originalThreshold; + } + + public static class HoldTyped implements Saveable { + List items; + + @Override + public void save() {} + } + + @Test + @Issue("SECURITY-4225") + void logsElementCountAtFineLevel() { + XStream2 xs = new XStream2(); + xs.alias("hold", HoldTyped.class); + try (var logRecorder = new LogRecorder().record(RobustReflectionConverter.class, Level.FINE).capture(10)) { + var h = (HoldTyped) xs.fromXML( + "ab"); + assertNotNull(h.items); + assertThat(logRecorder, LogRecorder.recorded(Level.FINE, containsString("Collection type checked {0} elements while deserializing {1}"))); + } + } + + @Test + @Issue("SECURITY-4225") + void logsWarningWhenApproachingLimit() { + RobustReflectionConverter.FIELD_VALUE_ELEMENT_CHECK_LIMIT = 100; + RobustReflectionConverter.FIELD_VALUE_ELEMENT_CHECK_WARNING_THRESHOLD = 2; + XStream2 xs = new XStream2(); + xs.alias("hold", HoldTyped.class); + try (var logRecorder = new LogRecorder().record(RobustReflectionConverter.class, Level.FINE).capture(10)) { + var h = (HoldTyped) xs.fromXML( + "abc"); + assertNotNull(h.items); + assertThat(logRecorder, LogRecorder.recorded(Level.WARNING, containsString("Collection type checked {0} elements while deserializing {1}. The limit is {2} and deserialization will fail when exceeded."))); + } + } +}