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
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
* 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.logging.log4j.test;

import org.apache.logging.log4j.message.Message;

/**
* A {@link Message} that cannot be serialized, although it implements {@link java.io.Serializable}.
* <p>
* One of its fields is not serializable, so serializing it throws {@link java.io.NotSerializableException}.
* It can be used to test that serializable Log4j classes, which contain arbitrary messages or objects,
* fall back to a serializable representation, like the formatted message.
* </p>
*/
public final class UnserializableMessage implements Message {

private static final long serialVersionUID = 1L;

private final String text;

@SuppressWarnings({"serial", "unused"})
private final Object unserializableField = new Object();

public UnserializableMessage(final String text) {
this.text = text;
}

@Override
public String getFormattedMessage() {
return text;
}

@Override
public String getFormat() {
return text;
}

@Override
public Object[] getParameters() {
return null;
}

@Override
public Throwable getThrowable() {
return null;
}

@Override
public String toString() {
return text;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,14 @@
package org.apache.logging.log4j.message;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.jupiter.api.Assertions.assertEquals;

import java.io.ObjectStreamException;
import java.math.BigDecimal;
import java.net.URI;
import java.util.stream.Stream;
import org.apache.logging.log4j.test.UnserializableMessage;
import org.apache.logging.log4j.test.junit.Mutable;
import org.apache.logging.log4j.test.junit.SerialUtil;
import org.junit.jupiter.api.Test;
Expand Down Expand Up @@ -95,6 +99,7 @@ public boolean equals(final Object other) {
return Stream.of(
"World",
new NonSerializable(),
new UnserializableMessage("World"),
new BigDecimal("123.456"),
// LOG4J2-3680
new RuntimeException(),
Expand All @@ -109,4 +114,12 @@ void testSerializable(final Object arg) {
assertThat(actual).isInstanceOf(ObjectMessage.class);
assertThat(actual).isEqualTo(expected);
}

@Test
void testDeserializationOfClassNotOnAllowlist() {
final byte[] data = SerialUtil.serialize(new ObjectMessage(URI.create("https://logging.apache.org/")));
assertThatThrownBy(() -> SerialUtil.deserialize(data))
.hasCauseInstanceOf(ObjectStreamException.class)
.hasStackTraceContaining("java.net.URI");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.status.StatusData;
import org.apache.logging.log4j.test.ListStatusListener;
import org.apache.logging.log4j.test.UnserializableMessage;
import org.apache.logging.log4j.test.junit.Mutable;
import org.apache.logging.log4j.test.junit.SerialUtil;
import org.apache.logging.log4j.test.junit.UsingStatusListener;
Expand Down Expand Up @@ -170,6 +171,7 @@ public boolean equals(final Object other) {
return Stream.of(
"World",
new NonSerializable(),
new UnserializableMessage("World"),
new BigDecimal("123.456"),
// LOG4J2-3680
new RuntimeException(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,15 +107,20 @@ void testSerializationOfNonSerializableValue() {
final SortedArrayStringMap original = new SortedArrayStringMap();
original.putValue("a", "avalue");
original.putValue("B", "Bvalue");
original.putValue("unserializable", new Object());
original.putValue("unserializable", new Object() {
@Override
public String toString() {
return "unserializable value";
}
});

final byte[] binary = serialize(original);
final SortedArrayStringMap copy = deserialize(binary);

final SortedArrayStringMap expected = new SortedArrayStringMap();
expected.putValue("a", "avalue");
expected.putValue("B", "Bvalue");
expected.putValue("unserializable", null);
expected.putValue("unserializable", "unserializable value");
assertEquals(expected, copy);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,12 @@
package org.apache.logging.log4j.util.internal;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InvalidClassException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
Expand Down Expand Up @@ -85,7 +87,7 @@ void readWrappedObjectUsesObjectInputFilterOfOuterStream() throws Exception {

final ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data));
setObjectInputFilter(in, "!" + Payload.class.getName());
assertThat(readParameter(in)).isNull();
assertThatThrownBy(() -> readParameter(in)).isInstanceOf(InvalidClassException.class);
}

@Test
Expand All @@ -97,7 +99,7 @@ void readWrappedObjectUsesObjectInputFilterOfOuterFilteredStream() throws Except

final ObjectInputStream in = new FilteredObjectInputStream(new ByteArrayInputStream(data));
setObjectInputFilter(in, "!" + Payload.class.getName());
assertThat(readParameter(in)).isNull();
assertThatThrownBy(() -> readParameter(in)).isInstanceOf(InvalidClassException.class);
}

private static byte[] serialize(final Serializable obj) throws IOException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import org.apache.logging.log4j.util.StringBuilderFormattable;
import org.apache.logging.log4j.util.StringBuilders;
import org.apache.logging.log4j.util.internal.SerializationUtil;
Expand Down Expand Up @@ -125,8 +124,7 @@ public String toString() {

private void writeObject(final ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
SerializationUtil.writeWrappedObject(
obj instanceof Serializable ? (Serializable) obj : String.valueOf(obj), out);
SerializationUtil.writeWrappedObject(obj, this::getFormattedMessage, out);
}

private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Objects;
import org.apache.logging.log4j.message.ParameterFormatter.MessagePatternAnalysis;
Expand Down Expand Up @@ -376,8 +375,7 @@ private void writeObject(final ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeInt(args.length);
for (final Object arg : args) {
final Serializable serializableArg = arg instanceof Serializable ? (Serializable) arg : String.valueOf(arg);
SerializationUtil.writeWrappedObject(serializableArg, out);
SerializationUtil.writeWrappedObject(arg, () -> String.valueOf(arg), out);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@
* <ul>
* <li>primitive types,</li>
* <li>{@code java.math.BigDecimal} and {@code java.math.BigInteger},</li>
* <li>{@code java.rmi.MarshalledObject},</li>
* <li>all classes whose name starts with {@code java.lang.}, {@code java.time.}, {@code java.util.}
* or {@code org.apache.logging.log4j.}.</li>
* </ul>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@

import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.Serializable;
import java.util.Arrays;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
Expand Down Expand Up @@ -470,8 +469,8 @@ private void writeObject(final java.io.ObjectOutputStream s) throws IOException
if (size > 0) {
for (int i = 0; i < size; i++) {
s.writeObject(keys[i]);
SerializationUtil.writeWrappedObject(
(values[i] instanceof Serializable) ? (Serializable) values[i] : null, s);
final Object value = values[i];
SerializationUtil.writeWrappedObject(value, () -> String.valueOf(value), s);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,10 @@
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.function.Supplier;
import org.apache.logging.log4j.internal.annotation.SuppressFBWarnings;
import org.apache.logging.log4j.status.StatusLogger;
import org.apache.logging.log4j.util.FilteredObjectInputStream;

Check warning on line 33 in log4j-api/src/main/java/org/apache/logging/log4j/util/internal/SerializationUtil.java

View workflow job for this annotation

GitHub Actions / analyze / Analyze

org.apache.logging.log4j.util.FilteredObjectInputStream in org.apache.logging.log4j.util has been deprecated

Check warning on line 33 in log4j-api/src/main/java/org/apache/logging/log4j/util/internal/SerializationUtil.java

View workflow job for this annotation

GitHub Actions / build / build (macos-latest)

org.apache.logging.log4j.util.FilteredObjectInputStream in org.apache.logging.log4j.util has been deprecated

Check warning on line 33 in log4j-api/src/main/java/org/apache/logging/log4j/util/internal/SerializationUtil.java

View workflow job for this annotation

GitHub Actions / build / build (ubuntu-latest)

org.apache.logging.log4j.util.FilteredObjectInputStream in org.apache.logging.log4j.util has been deprecated

/**
* Provides methods to increase the safety of object serialization/deserialization.
Expand All @@ -56,8 +57,6 @@
public static final List<String> REQUIRED_JAVA_CLASSES = Arrays.asList(
"java.math.BigDecimal",
"java.math.BigInteger",
// for Message delegate
"java.rmi.MarshalledObject",
// all primitives
"boolean",
"byte",
Expand All @@ -71,15 +70,49 @@
public static final List<String> REQUIRED_JAVA_PACKAGES =
Arrays.asList("java.lang.", "java.time.", "java.util.", "org.apache.logging.log4j.");

public static void writeWrappedObject(final Serializable obj, final ObjectOutputStream out) throws IOException {
/**
* Serializes an object into a byte array and writes the array to the output stream.
* <p>
* If the object is neither {@code null} nor {@link Serializable}, or its serialization fails, the value returned by
* {@code fallback} is written instead. Failed serializations are logged as warnings.
* </p>
*
* @param obj The object to write.
* @param fallback Provides the value to write if {@code obj} cannot be serialized.
* @param out The output stream.
*/
public static void writeWrappedObject(
final Object obj, final Supplier<Serializable> fallback, final ObjectOutputStream out) throws IOException {
byte[] data = null;
if (obj == null || obj instanceof Serializable) {
try {
data = toByteArray((Serializable) obj);
} catch (final IOException | RuntimeException e) {
StatusLogger.getLogger()
.warn("Unable to serialize an object of type {}, using a fallback value.", obj.getClass(), e);
}
}
out.writeObject(data != null ? data : toByteArray(fallback.get()));
}

private static byte[] toByteArray(final Serializable obj) throws IOException {
final ByteArrayOutputStream bout = new ByteArrayOutputStream();
try (final ObjectOutputStream oos = new ObjectOutputStream(bout)) {
oos.writeObject(obj);
oos.flush();
out.writeObject(bout.toByteArray());
}
return bout.toByteArray();
}

/**
* Reads an object written by {@link #writeWrappedObject}.
*
* <p>The object is read from a nested stream, filtered in the same way as {@code in}.
* If the class of the object is not available, {@code null} is returned and a warning is logged.
* Other errors, including classes rejected by the filter, are thrown.</p>
*
* @param in The input stream.
* @return The object or {@code null}.
*/
@SuppressFBWarnings(
value = "OBJECT_DESERIALIZATION",
justification = "The nested stream is filtered in the same way as the outer stream.")
Expand All @@ -93,7 +126,11 @@
copyObjectInputFilter(in, ois);
try {
return ois.readObject();
} catch (final IOException e) {
// Includes classes rejected by the stream's filter
throw e;
} catch (final Exception | LinkageError e) {
// The class is not available or not compatible
StatusLogger.getLogger().warn("Ignoring {} during deserialization", e.getMessage());
return null;
} finally {
Expand Down
2 changes: 1 addition & 1 deletion log4j-core-test/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -432,7 +432,7 @@
<goal>test</goal>
</goals>
<configuration>
<argLine>-Djdk.serialFilter=java.lang.**;java.time.**;java.util.**;java.math.BigDecimal;java.math.BigInteger;java.rmi.MarshalledObject;org.apache.logging.log4j.**;!*</argLine>
<argLine>-Djdk.serialFilter=java.lang.**;java.time.**;java.util.**;java.math.BigDecimal;java.math.BigInteger;org.apache.logging.log4j.**;!*</argLine>
<groups>serialization</groups>
</configuration>
</execution>
Expand Down
Loading
Loading