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
9 changes: 9 additions & 0 deletions src/main/java/org/apache/commons/csv/CSVFormat.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InvalidObjectException;
import java.io.NotActiveException;
import java.io.ObjectInputStream;
import java.io.OutputStream;
Expand Down Expand Up @@ -2648,6 +2649,14 @@ private void printWithQuotes(final Reader reader, final Appendable appendable) t
private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
writeLock = new Object();
// The constructor validates these invariants, but deserialization bypasses it, so a crafted stream
// could yield a format the Builder rejects (for example the quote char equal to the delimiter, or
// QuoteMode.NONE with no escape char) that then misparses or throws in a print/parse callee.
try {
validate();
} catch (final IllegalArgumentException e) {
throw (InvalidObjectException) new InvalidObjectException(e.getMessage()).initCause(e);
}
}

@Override
Expand Down
19 changes: 19 additions & 0 deletions src/test/java/org/apache/commons/csv/CSVFormatTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,12 @@
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.sql.ResultSet;
Expand Down Expand Up @@ -1158,6 +1160,23 @@ void testSerialization() throws Exception {
assertEquals(CSVFormat.DEFAULT.getIgnoreEmptyLines(), format.getIgnoreEmptyLines(), "empty lines");
}

@Test
void testSerializationRejectsInvalidInvariant() throws Exception {
// A format the Builder rejects: QuoteMode.NONE with no escape character. Reflection corrupts a fresh
// instance to build a serialized stream a hostile source could send.
final CSVFormat format = CSVFormat.DEFAULT.builder().get();
final Field quoteModeField = CSVFormat.class.getDeclaredField("quoteMode");
quoteModeField.setAccessible(true);
quoteModeField.set(format, QuoteMode.NONE);
final ByteArrayOutputStream out = new ByteArrayOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(out)) {
oos.writeObject(format);
}
try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(out.toByteArray()))) {
assertThrows(InvalidObjectException.class, in::readObject);
}
}

@Test
void testToString() {

Expand Down
Loading