提交 46d40140 编写于 作者: R rriggs

8160108: Implement Serialization Filtering

8166739: Improve extensibility of ObjectInputFilter information passed to the filter
Reviewed-by: dfuchs, ahgross, chegar, skoivu
上级 11398405
...@@ -37,13 +37,18 @@ import java.security.PrivilegedActionException; ...@@ -37,13 +37,18 @@ import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction; import java.security.PrivilegedExceptionAction;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentMap;
import static java.io.ObjectStreamClass.processQueue; import static java.io.ObjectStreamClass.processQueue;
import sun.misc.ObjectInputFilter;
import sun.misc.ObjectStreamClassValidator; import sun.misc.ObjectStreamClassValidator;
import sun.misc.SharedSecrets; import sun.misc.SharedSecrets;
import sun.misc.Unsafe;
import sun.reflect.misc.ReflectUtil; import sun.reflect.misc.ReflectUtil;
import sun.misc.JavaOISAccess;
import sun.util.logging.PlatformLogger;
/** /**
* An ObjectInputStream deserializes primitive data and objects previously * An ObjectInputStream deserializes primitive data and objects previously
...@@ -239,12 +244,48 @@ public class ObjectInputStream ...@@ -239,12 +244,48 @@ public class ObjectInputStream
new ReferenceQueue<>(); new ReferenceQueue<>();
} }
static {
/* Setup access so sun.misc can invoke package private functions. */
sun.misc.SharedSecrets.setJavaOISAccess(new JavaOISAccess() {
public void setObjectInputFilter(ObjectInputStream stream, ObjectInputFilter filter) {
stream.setInternalObjectInputFilter(filter);
}
public ObjectInputFilter getObjectInputFilter(ObjectInputStream stream) {
return stream.getInternalObjectInputFilter();
}
});
}
/*
* Separate class to defer initialization of logging until needed.
*/
private static class Logging {
/*
* Logger for ObjectInputFilter results.
* Setup the filter logger if it is set to INFO or WARNING.
* (Assuming it will not change).
*/
private static final PlatformLogger traceLogger;
private static final PlatformLogger infoLogger;
static {
PlatformLogger filterLog = PlatformLogger.getLogger("java.io.serialization");
infoLogger = (filterLog != null &&
filterLog.isLoggable(PlatformLogger.Level.INFO)) ? filterLog : null;
traceLogger = (filterLog != null &&
filterLog.isLoggable(PlatformLogger.Level.FINER)) ? filterLog : null;
}
}
/** filter stream for handling block data conversion */ /** filter stream for handling block data conversion */
private final BlockDataInputStream bin; private final BlockDataInputStream bin;
/** validation callback list */ /** validation callback list */
private final ValidationList vlist; private final ValidationList vlist;
/** recursion depth */ /** recursion depth */
private int depth; private long depth;
/** Total number of references to any type of object, class, enum, proxy, etc. */
private long totalObjectRefs;
/** whether stream is closed */ /** whether stream is closed */
private boolean closed; private boolean closed;
...@@ -270,6 +311,12 @@ public class ObjectInputStream ...@@ -270,6 +311,12 @@ public class ObjectInputStream
*/ */
private SerialCallbackContext curContext; private SerialCallbackContext curContext;
/**
* Filter of class descriptors and classes read from the stream;
* may be null.
*/
private ObjectInputFilter serialFilter;
/** /**
* Creates an ObjectInputStream that reads from the specified InputStream. * Creates an ObjectInputStream that reads from the specified InputStream.
* A serialization stream header is read from the stream and verified. * A serialization stream header is read from the stream and verified.
...@@ -297,6 +344,7 @@ public class ObjectInputStream ...@@ -297,6 +344,7 @@ public class ObjectInputStream
bin = new BlockDataInputStream(in); bin = new BlockDataInputStream(in);
handles = new HandleTable(10); handles = new HandleTable(10);
vlist = new ValidationList(); vlist = new ValidationList();
serialFilter = ObjectInputFilter.Config.getSerialFilter();
enableOverride = false; enableOverride = false;
readStreamHeader(); readStreamHeader();
bin.setBlockDataMode(true); bin.setBlockDataMode(true);
...@@ -327,6 +375,7 @@ public class ObjectInputStream ...@@ -327,6 +375,7 @@ public class ObjectInputStream
bin = null; bin = null;
handles = null; handles = null;
vlist = null; vlist = null;
serialFilter = ObjectInputFilter.Config.getSerialFilter();
enableOverride = true; enableOverride = true;
} }
...@@ -334,7 +383,7 @@ public class ObjectInputStream ...@@ -334,7 +383,7 @@ public class ObjectInputStream
* Read an object from the ObjectInputStream. The class of the object, the * Read an object from the ObjectInputStream. The class of the object, the
* signature of the class, and the values of the non-transient and * signature of the class, and the values of the non-transient and
* non-static fields of the class and all of its supertypes are read. * non-static fields of the class and all of its supertypes are read.
* Default deserializing for a class can be overriden using the writeObject * Default deserializing for a class can be overridden using the writeObject
* and readObject methods. Objects referenced by this object are read * and readObject methods. Objects referenced by this object are read
* transitively so that a complete equivalent graph of objects is * transitively so that a complete equivalent graph of objects is
* reconstructed by readObject. * reconstructed by readObject.
...@@ -1075,6 +1124,138 @@ public class ObjectInputStream ...@@ -1075,6 +1124,138 @@ public class ObjectInputStream
return bin.readUTF(); return bin.readUTF();
} }
/**
* Returns the serialization filter for this stream.
* The serialization filter is the most recent filter set in
* {@link #setInternalObjectInputFilter setInternalObjectInputFilter} or
* the initial process-wide filter from
* {@link ObjectInputFilter.Config#getSerialFilter() ObjectInputFilter.Config.getSerialFilter}.
*
* @return the serialization filter for the stream; may be null
*/
private final ObjectInputFilter getInternalObjectInputFilter() {
return serialFilter;
}
/**
* Set the serialization filter for the stream.
* The filter's {@link ObjectInputFilter#checkInput checkInput} method is called
* for each class and reference in the stream.
* The filter can check any or all of the class, the array length, the number
* of references, the depth of the graph, and the size of the input stream.
* <p>
* If the filter returns {@link ObjectInputFilter.Status#REJECTED Status.REJECTED},
* {@code null} or throws a {@link RuntimeException},
* the active {@code readObject} or {@code readUnshared}
* throws {@link InvalidClassException}, otherwise deserialization
* continues uninterrupted.
* <p>
* The serialization filter is initialized to the value of
* {@link ObjectInputFilter.Config#getSerialFilter() ObjectInputFilter.Config.getSerialFilter}
* when the {@code ObjectInputStream} is constructed and can be set
* to a custom filter only once.
*
* @implSpec
* The filter, when not {@code null}, is invoked during {@link #readObject readObject}
* and {@link #readUnshared readUnshared} for each object
* (regular or class) in the stream including the following:
* <ul>
* <li>each object reference previously deserialized from the stream
* (class is {@code null}, arrayLength is -1),
* <li>each regular class (class is not {@code null}, arrayLength is -1),
* <li>each interface of a dynamic proxy and the dynamic proxy class itself
* (class is not {@code null}, arrayLength is -1),
* <li>each array is filtered using the array type and length of the array
* (class is the array type, arrayLength is the requested length),
* <li>each object replaced by its class' {@code readResolve} method
* is filtered using the replacement object's class, if not {@code null},
* and if it is an array, the arrayLength, otherwise -1,
* <li>and each object replaced by {@link #resolveObject resolveObject}
* is filtered using the replacement object's class, if not {@code null},
* and if it is an array, the arrayLength, otherwise -1.
* </ul>
*
* When the {@link ObjectInputFilter#checkInput checkInput} method is invoked
* it is given access to the current class, the array length,
* the current number of references already read from the stream,
* the depth of nested calls to {@link #readObject readObject} or
* {@link #readUnshared readUnshared},
* and the implementation dependent number of bytes consumed from the input stream.
* <p>
* Each call to {@link #readObject readObject} or
* {@link #readUnshared readUnshared} increases the depth by 1
* before reading an object and decreases by 1 before returning
* normally or exceptionally.
* The depth starts at {@code 1} and increases for each nested object and
* decrements when each nested call returns.
* The count of references in the stream starts at {@code 1} and
* is increased before reading an object.
*
* @param filter the filter, may be null
* @throws SecurityException if there is security manager and the
* {@code SerializablePermission("serialFilter")} is not granted
* @throws IllegalStateException if the {@linkplain #getInternalObjectInputFilter() current filter}
* is not {@code null} and is not the process-wide filter
*/
private final void setInternalObjectInputFilter(ObjectInputFilter filter) {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new SerializablePermission("serialFilter"));
}
// Allow replacement of the process-wide filter if not already set
if (serialFilter != null &&
serialFilter != ObjectInputFilter.Config.getSerialFilter()) {
throw new IllegalStateException("filter can not be set more than once");
}
this.serialFilter = filter;
}
/**
* Invoke the serialization filter if non-null.
* If the filter rejects or an exception is thrown, throws InvalidClassException.
*
* @param clazz the class; may be null
* @param arrayLength the array length requested; use {@code -1} if not creating an array
* @throws InvalidClassException if it rejected by the filter or
* a {@link RuntimeException} is thrown
*/
private void filterCheck(Class<?> clazz, int arrayLength)
throws InvalidClassException {
if (serialFilter != null) {
RuntimeException ex = null;
ObjectInputFilter.Status status;
try {
status = serialFilter.checkInput(new FilterValues(clazz, arrayLength,
totalObjectRefs, depth, bin.getBytesRead()));
} catch (RuntimeException e) {
// Preventive interception of an exception to log
status = ObjectInputFilter.Status.REJECTED;
ex = e;
}
if (status == null ||
status == ObjectInputFilter.Status.REJECTED) {
// Debug logging of filter checks that fail
if (Logging.infoLogger != null) {
Logging.infoLogger.info(
"ObjectInputFilter {0}: {1}, array length: {2}, nRefs: {3}, depth: {4}, bytes: {5}, ex: {6}",
status, clazz, arrayLength, totalObjectRefs, depth, bin.getBytesRead(),
Objects.toString(ex, "n/a"));
}
InvalidClassException ice = new InvalidClassException("filter status: " + status);
ice.initCause(ex);
throw ice;
} else {
// Trace logging for those that succeed
if (Logging.traceLogger != null) {
Logging.traceLogger.finer(
"ObjectInputFilter {0}: {1}, array length: {2}, nRefs: {3}, depth: {4}, bytes: {5}, ex: {6}",
status, clazz, arrayLength, totalObjectRefs, depth, bin.getBytesRead(),
Objects.toString(ex, "n/a"));
}
}
}
}
/** /**
* Provide access to the persistent fields read from the input stream. * Provide access to the persistent fields read from the input stream.
*/ */
...@@ -1324,6 +1505,7 @@ public class ObjectInputStream ...@@ -1324,6 +1505,7 @@ public class ObjectInputStream
} }
depth++; depth++;
totalObjectRefs++;
try { try {
switch (tc) { switch (tc) {
case TC_NULL: case TC_NULL:
...@@ -1400,6 +1582,15 @@ public class ObjectInputStream ...@@ -1400,6 +1582,15 @@ public class ObjectInputStream
} }
Object rep = resolveObject(obj); Object rep = resolveObject(obj);
if (rep != obj) { if (rep != obj) {
// The type of the original object has been filtered but resolveObject
// may have replaced it; filter the replacement's type
if (rep != null) {
if (rep.getClass().isArray()) {
filterCheck(rep.getClass(), Array.getLength(rep));
} else {
filterCheck(rep.getClass(), -1);
}
}
handles.setObject(passHandle, rep); handles.setObject(passHandle, rep);
} }
return rep; return rep;
...@@ -1470,6 +1661,7 @@ public class ObjectInputStream ...@@ -1470,6 +1661,7 @@ public class ObjectInputStream
throw new InvalidObjectException( throw new InvalidObjectException(
"cannot read back reference to unshared object"); "cannot read back reference to unshared object");
} }
filterCheck(null, -1); // just a check for number of references, depth, no class
return obj; return obj;
} }
...@@ -1574,6 +1766,10 @@ public class ObjectInputStream ...@@ -1574,6 +1766,10 @@ public class ObjectInputStream
ReflectUtil.checkProxyPackageAccess( ReflectUtil.checkProxyPackageAccess(
getClass().getClassLoader(), getClass().getClassLoader(),
cl.getInterfaces()); cl.getInterfaces());
// Filter the interfaces
for (Class<?> clazz : cl.getInterfaces()) {
filterCheck(clazz, -1);
}
} }
} catch (ClassNotFoundException ex) { } catch (ClassNotFoundException ex) {
resolveEx = ex; resolveEx = ex;
...@@ -1582,6 +1778,9 @@ public class ObjectInputStream ...@@ -1582,6 +1778,9 @@ public class ObjectInputStream
desc.initProxy(cl, resolveEx, readClassDesc(false)); desc.initProxy(cl, resolveEx, readClassDesc(false));
// Call filterCheck on the definition
filterCheck(desc.forClass(), -1);
handles.finish(descHandle); handles.finish(descHandle);
passHandle = descHandle; passHandle = descHandle;
return desc; return desc;
...@@ -1629,8 +1828,12 @@ public class ObjectInputStream ...@@ -1629,8 +1828,12 @@ public class ObjectInputStream
desc.initNonProxy(readDesc, cl, resolveEx, readClassDesc(false)); desc.initNonProxy(readDesc, cl, resolveEx, readClassDesc(false));
// Call filterCheck on the definition
filterCheck(desc.forClass(), -1);
handles.finish(descHandle); handles.finish(descHandle);
passHandle = descHandle; passHandle = descHandle;
return desc; return desc;
} }
...@@ -1671,6 +1874,8 @@ public class ObjectInputStream ...@@ -1671,6 +1874,8 @@ public class ObjectInputStream
ObjectStreamClass desc = readClassDesc(false); ObjectStreamClass desc = readClassDesc(false);
int len = bin.readInt(); int len = bin.readInt();
filterCheck(desc.forClass(), len);
Object array = null; Object array = null;
Class<?> cl, ccl = null; Class<?> cl, ccl = null;
if ((cl = desc.forClass()) != null) { if ((cl = desc.forClass()) != null) {
...@@ -1819,6 +2024,14 @@ public class ObjectInputStream ...@@ -1819,6 +2024,14 @@ public class ObjectInputStream
rep = cloneArray(rep); rep = cloneArray(rep);
} }
if (rep != obj) { if (rep != obj) {
// Filter the replacement object
if (rep != null) {
if (rep.getClass().isArray()) {
filterCheck(rep.getClass(), Array.getLength(rep));
} else {
filterCheck(rep.getClass(), -1);
}
}
handles.setObject(passHandle, obj = rep); handles.setObject(passHandle, obj = rep);
} }
} }
...@@ -2009,22 +2222,22 @@ public class ObjectInputStream ...@@ -2009,22 +2222,22 @@ public class ObjectInputStream
desc.setPrimFieldValues(obj, primVals); desc.setPrimFieldValues(obj, primVals);
} }
int objHandle = passHandle; int objHandle = passHandle;
ObjectStreamField[] fields = desc.getFields(false); ObjectStreamField[] fields = desc.getFields(false);
Object[] objVals = new Object[desc.getNumObjFields()]; Object[] objVals = new Object[desc.getNumObjFields()];
int numPrimFields = fields.length - objVals.length; int numPrimFields = fields.length - objVals.length;
for (int i = 0; i < objVals.length; i++) { for (int i = 0; i < objVals.length; i++) {
ObjectStreamField f = fields[numPrimFields + i]; ObjectStreamField f = fields[numPrimFields + i];
objVals[i] = readObject0(f.isUnshared()); objVals[i] = readObject0(f.isUnshared());
if (f.getField() != null) { if (f.getField() != null) {
handles.markDependency(objHandle, passHandle); handles.markDependency(objHandle, passHandle);
}
} }
}
if (obj != null) { if (obj != null) {
desc.setObjFieldValues(obj, objVals); desc.setObjFieldValues(obj, objVals);
} }
passHandle = objHandle; passHandle = objHandle;
} }
/** /**
* Reads in and returns IOException that caused serialization to abort. * Reads in and returns IOException that caused serialization to abort.
...@@ -2296,6 +2509,51 @@ public class ObjectInputStream ...@@ -2296,6 +2509,51 @@ public class ObjectInputStream
} }
} }
/**
* Hold a snapshot of values to be passed to an ObjectInputFilter.
*/
static class FilterValues implements ObjectInputFilter.FilterInfo {
final Class<?> clazz;
final long arrayLength;
final long totalObjectRefs;
final long depth;
final long streamBytes;
public FilterValues(Class<?> clazz, long arrayLength, long totalObjectRefs,
long depth, long streamBytes) {
this.clazz = clazz;
this.arrayLength = arrayLength;
this.totalObjectRefs = totalObjectRefs;
this.depth = depth;
this.streamBytes = streamBytes;
}
@Override
public Class<?> serialClass() {
return clazz;
}
@Override
public long arrayLength() {
return arrayLength;
}
@Override
public long references() {
return totalObjectRefs;
}
@Override
public long depth() {
return depth;
}
@Override
public long streamBytes() {
return streamBytes;
}
}
/** /**
* Input stream supporting single-byte peek operations. * Input stream supporting single-byte peek operations.
*/ */
...@@ -2305,6 +2563,8 @@ public class ObjectInputStream ...@@ -2305,6 +2563,8 @@ public class ObjectInputStream
private final InputStream in; private final InputStream in;
/** peeked byte */ /** peeked byte */
private int peekb = -1; private int peekb = -1;
/** total bytes read from the stream */
private long totalBytesRead = 0;
/** /**
* Creates new PeekInputStream on top of given underlying stream. * Creates new PeekInputStream on top of given underlying stream.
...@@ -2318,7 +2578,12 @@ public class ObjectInputStream ...@@ -2318,7 +2578,12 @@ public class ObjectInputStream
* that it does not consume the read value. * that it does not consume the read value.
*/ */
int peek() throws IOException { int peek() throws IOException {
return (peekb >= 0) ? peekb : (peekb = in.read()); if (peekb >= 0) {
return peekb;
}
peekb = in.read();
totalBytesRead += peekb >= 0 ? 1 : 0;
return peekb;
} }
public int read() throws IOException { public int read() throws IOException {
...@@ -2327,21 +2592,27 @@ public class ObjectInputStream ...@@ -2327,21 +2592,27 @@ public class ObjectInputStream
peekb = -1; peekb = -1;
return v; return v;
} else { } else {
return in.read(); int nbytes = in.read();
totalBytesRead += nbytes >= 0 ? 1 : 0;
return nbytes;
} }
} }
public int read(byte[] b, int off, int len) throws IOException { public int read(byte[] b, int off, int len) throws IOException {
int nbytes;
if (len == 0) { if (len == 0) {
return 0; return 0;
} else if (peekb < 0) { } else if (peekb < 0) {
return in.read(b, off, len); nbytes = in.read(b, off, len);
totalBytesRead += nbytes >= 0 ? nbytes : 0;
return nbytes;
} else { } else {
b[off++] = (byte) peekb; b[off++] = (byte) peekb;
len--; len--;
peekb = -1; peekb = -1;
int n = in.read(b, off, len); nbytes = in.read(b, off, len);
return (n >= 0) ? (n + 1) : 1; totalBytesRead += nbytes >= 0 ? nbytes : 0;
return (nbytes >= 0) ? (nbytes + 1) : 1;
} }
} }
...@@ -2366,7 +2637,9 @@ public class ObjectInputStream ...@@ -2366,7 +2637,9 @@ public class ObjectInputStream
skipped++; skipped++;
n--; n--;
} }
return skipped + skip(n); n = skipped + in.skip(n);
totalBytesRead += n;
return n;
} }
public int available() throws IOException { public int available() throws IOException {
...@@ -2376,6 +2649,10 @@ public class ObjectInputStream ...@@ -2376,6 +2649,10 @@ public class ObjectInputStream
public void close() throws IOException { public void close() throws IOException {
in.close(); in.close();
} }
public long getBytesRead() {
return totalBytesRead;
}
} }
/** /**
...@@ -3231,6 +3508,14 @@ public class ObjectInputStream ...@@ -3231,6 +3508,14 @@ public class ObjectInputStream
throw new UTFDataFormatException(); throw new UTFDataFormatException();
} }
} }
/**
* Returns the number of bytes read from the input stream.
* @return the number of bytes read from the input stream
*/
long getBytesRead() {
return in.getBytesRead();
}
} }
/** /**
......
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.misc;
import java.io.ObjectInputStream;
public interface JavaOISAccess {
void setObjectInputFilter(ObjectInputStream stream, ObjectInputFilter filter);
ObjectInputFilter getObjectInputFilter(ObjectInputStream stream);
}
此差异已折叠。
...@@ -25,6 +25,7 @@ ...@@ -25,6 +25,7 @@
package sun.misc; package sun.misc;
import java.io.ObjectInputStream;
import java.util.jar.JarFile; import java.util.jar.JarFile;
import java.io.Console; import java.io.Console;
import java.io.FileDescriptor; import java.io.FileDescriptor;
...@@ -56,6 +57,7 @@ public class SharedSecrets { ...@@ -56,6 +57,7 @@ public class SharedSecrets {
private static JavaSecurityAccess javaSecurityAccess; private static JavaSecurityAccess javaSecurityAccess;
private static JavaUtilZipFileAccess javaUtilZipFileAccess; private static JavaUtilZipFileAccess javaUtilZipFileAccess;
private static JavaAWTAccess javaAWTAccess; private static JavaAWTAccess javaAWTAccess;
private static JavaOISAccess javaOISAccess;
private static JavaObjectInputStreamAccess javaObjectInputStreamAccess; private static JavaObjectInputStreamAccess javaObjectInputStreamAccess;
public static JavaUtilJarAccess javaUtilJarAccess() { public static JavaUtilJarAccess javaUtilJarAccess() {
...@@ -141,6 +143,18 @@ public class SharedSecrets { ...@@ -141,6 +143,18 @@ public class SharedSecrets {
return javaIOFileDescriptorAccess; return javaIOFileDescriptorAccess;
} }
public static void setJavaOISAccess(JavaOISAccess access) {
javaOISAccess = access;
}
public static JavaOISAccess getJavaOISAccess() {
if (javaOISAccess == null)
unsafe.ensureClassInitialized(ObjectInputStream.class);
return javaOISAccess;
}
public static void setJavaSecurityProtectionDomainAccess public static void setJavaSecurityProtectionDomainAccess
(JavaSecurityProtectionDomainAccess jspda) { (JavaSecurityProtectionDomainAccess jspda) {
javaSecurityProtectionDomainAccess = jspda; javaSecurityProtectionDomainAccess = jspda;
......
...@@ -700,3 +700,40 @@ jdk.tls.legacyAlgorithms= \ ...@@ -700,3 +700,40 @@ jdk.tls.legacyAlgorithms= \
# implementations. # implementations.
# #
jdk.jar.disabledAlgorithms=MD2, RSA keySize < 1024 jdk.jar.disabledAlgorithms=MD2, RSA keySize < 1024
#
# Serialization process-wide filter
#
# A filter, if configured, is used by java.io.ObjectInputStream during
# deserialization to check the contents of the stream.
# A filter is configured as a sequence of patterns, each pattern is either
# matched against the name of a class in the stream or defines a limit.
# Patterns are separated by ";" (semicolon).
# Whitespace is significant and is considered part of the pattern.
#
# If a pattern includes a "=", it sets a limit.
# If a limit appears more than once the last value is used.
# Limits are checked before classes regardless of the order in the sequence of patterns.
# If any of the limits are exceeded, the filter status is REJECTED.
#
# maxdepth=value - the maximum depth of a graph
# maxrefs=value - the maximum number of internal references
# maxbytes=value - the maximum number of bytes in the input stream
# maxarray=value - the maximum array length allowed
#
# Other patterns, from left to right, match the class or package name as
# returned from Class.getName.
# If the class is an array type, the class or package to be matched is the element type.
# Arrays of any number of dimensions are treated the same as the element type.
# For example, a pattern of "!example.Foo", rejects creation of any instance or
# array of example.Foo.
#
# If the pattern starts with "!", the status is REJECTED if the remaining pattern
# is matched; otherwise the status is ALLOWED if the pattern matches.
# If the pattern ends with ".**" it matches any class in the package and all subpackages.
# If the pattern ends with ".*" it matches any class in the package.
# If the pattern ends with "*", it matches any class with the pattern as a prefix.
# If the pattern is equal to the class name, it matches.
# Otherwise, the status is UNDECIDED.
#
#jdk.serialFilter=pattern;pattern
...@@ -700,3 +700,40 @@ jdk.tls.legacyAlgorithms= \ ...@@ -700,3 +700,40 @@ jdk.tls.legacyAlgorithms= \
# implementations. # implementations.
# #
jdk.jar.disabledAlgorithms=MD2, RSA keySize < 1024 jdk.jar.disabledAlgorithms=MD2, RSA keySize < 1024
#
# Serialization process-wide filter
#
# A filter, if configured, is used by java.io.ObjectInputStream during
# deserialization to check the contents of the stream.
# A filter is configured as a sequence of patterns, each pattern is either
# matched against the name of a class in the stream or defines a limit.
# Patterns are separated by ";" (semicolon).
# Whitespace is significant and is considered part of the pattern.
#
# If a pattern includes a "=", it sets a limit.
# If a limit appears more than once the last value is used.
# Limits are checked before classes regardless of the order in the sequence of patterns.
# If any of the limits are exceeded, the filter status is REJECTED.
#
# maxdepth=value - the maximum depth of a graph
# maxrefs=value - the maximum number of internal references
# maxbytes=value - the maximum number of bytes in the input stream
# maxarray=value - the maximum array length allowed
#
# Other patterns, from left to right, match the class or package name as
# returned from Class.getName.
# If the class is an array type, the class or package to be matched is the element type.
# Arrays of any number of dimensions are treated the same as the element type.
# For example, a pattern of "!example.Foo", rejects creation of any instance or
# array of example.Foo.
#
# If the pattern starts with "!", the status is REJECTED if the remaining pattern
# is matched; otherwise the status is ALLOWED if the pattern matches.
# If the pattern ends with ".**" it matches any class in the package and all subpackages.
# If the pattern ends with ".*" it matches any class in the package.
# If the pattern ends with "*", it matches any class with the pattern as a prefix.
# If the pattern is equal to the class name, it matches.
# Otherwise, the status is UNDECIDED.
#
#jdk.serialFilter=pattern;pattern
...@@ -703,3 +703,40 @@ jdk.tls.legacyAlgorithms= \ ...@@ -703,3 +703,40 @@ jdk.tls.legacyAlgorithms= \
# implementations. # implementations.
# #
jdk.jar.disabledAlgorithms=MD2, RSA keySize < 1024 jdk.jar.disabledAlgorithms=MD2, RSA keySize < 1024
#
# Serialization process-wide filter
#
# A filter, if configured, is used by java.io.ObjectInputStream during
# deserialization to check the contents of the stream.
# A filter is configured as a sequence of patterns, each pattern is either
# matched against the name of a class in the stream or defines a limit.
# Patterns are separated by ";" (semicolon).
# Whitespace is significant and is considered part of the pattern.
#
# If a pattern includes a "=", it sets a limit.
# If a limit appears more than once the last value is used.
# Limits are checked before classes regardless of the order in the sequence of patterns.
# If any of the limits are exceeded, the filter status is REJECTED.
#
# maxdepth=value - the maximum depth of a graph
# maxrefs=value - the maximum number of internal references
# maxbytes=value - the maximum number of bytes in the input stream
# maxarray=value - the maximum array length allowed
#
# Other patterns, from left to right, match the class or package name as
# returned from Class.getName.
# If the class is an array type, the class or package to be matched is the element type.
# Arrays of any number of dimensions are treated the same as the element type.
# For example, a pattern of "!example.Foo", rejects creation of any instance or
# array of example.Foo.
#
# If the pattern starts with "!", the status is REJECTED if the remaining pattern
# is matched; otherwise the status is ALLOWED if the pattern matches.
# If the pattern ends with ".**" it matches any class in the package and all subpackages.
# If the pattern ends with ".*" it matches any class in the package.
# If the pattern ends with "*", it matches any class with the pattern as a prefix.
# If the pattern is equal to the class name, it matches.
# Otherwise, the status is UNDECIDED.
#
#jdk.serialFilter=pattern;pattern
...@@ -702,3 +702,40 @@ jdk.tls.legacyAlgorithms= \ ...@@ -702,3 +702,40 @@ jdk.tls.legacyAlgorithms= \
# implementations. # implementations.
# #
jdk.jar.disabledAlgorithms=MD2, RSA keySize < 1024 jdk.jar.disabledAlgorithms=MD2, RSA keySize < 1024
#
# Serialization process-wide filter
#
# A filter, if configured, is used by java.io.ObjectInputStream during
# deserialization to check the contents of the stream.
# A filter is configured as a sequence of patterns, each pattern is either
# matched against the name of a class in the stream or defines a limit.
# Patterns are separated by ";" (semicolon).
# Whitespace is significant and is considered part of the pattern.
#
# If a pattern includes a "=", it sets a limit.
# If a limit appears more than once the last value is used.
# Limits are checked before classes regardless of the order in the sequence of patterns.
# If any of the limits are exceeded, the filter status is REJECTED.
#
# maxdepth=value - the maximum depth of a graph
# maxrefs=value - the maximum number of internal references
# maxbytes=value - the maximum number of bytes in the input stream
# maxarray=value - the maximum array length allowed
#
# Other patterns, from left to right, match the class or package name as
# returned from Class.getName.
# If the class is an array type, the class or package to be matched is the element type.
# Arrays of any number of dimensions are treated the same as the element type.
# For example, a pattern of "!example.Foo", rejects creation of any instance or
# array of example.Foo.
#
# If the pattern starts with "!", the status is REJECTED if the remaining pattern
# is matched; otherwise the status is ALLOWED if the pattern matches.
# If the pattern ends with ".**" it matches any class in the package and all subpackages.
# If the pattern ends with ".*" it matches any class in the package.
# If the pattern ends with "*", it matches any class with the pattern as a prefix.
# If the pattern is equal to the class name, it matches.
# Otherwise, the status is UNDECIDED.
#
#jdk.serialFilter=pattern;pattern
...@@ -703,3 +703,40 @@ jdk.tls.legacyAlgorithms= \ ...@@ -703,3 +703,40 @@ jdk.tls.legacyAlgorithms= \
# implementations. # implementations.
# #
jdk.jar.disabledAlgorithms=MD2, RSA keySize < 1024 jdk.jar.disabledAlgorithms=MD2, RSA keySize < 1024
#
# Serialization process-wide filter
#
# A filter, if configured, is used by java.io.ObjectInputStream during
# deserialization to check the contents of the stream.
# A filter is configured as a sequence of patterns, each pattern is either
# matched against the name of a class in the stream or defines a limit.
# Patterns are separated by ";" (semicolon).
# Whitespace is significant and is considered part of the pattern.
#
# If a pattern includes a "=", it sets a limit.
# If a limit appears more than once the last value is used.
# Limits are checked before classes regardless of the order in the sequence of patterns.
# If any of the limits are exceeded, the filter status is REJECTED.
#
# maxdepth=value - the maximum depth of a graph
# maxrefs=value - the maximum number of internal references
# maxbytes=value - the maximum number of bytes in the input stream
# maxarray=value - the maximum array length allowed
#
# Other patterns, from left to right, match the class or package name as
# returned from Class.getName.
# If the class is an array type, the class or package to be matched is the element type.
# Arrays of any number of dimensions are treated the same as the element type.
# For example, a pattern of "!example.Foo", rejects creation of any instance or
# array of example.Foo.
#
# If the pattern starts with "!", the status is REJECTED if the remaining pattern
# is matched; otherwise the status is ALLOWED if the pattern matches.
# If the pattern ends with ".**" it matches any class in the package and all subpackages.
# If the pattern ends with ".*" it matches any class in the package.
# If the pattern ends with "*", it matches any class with the pattern as a prefix.
# If the pattern is equal to the class name, it matches.
# Otherwise, the status is UNDECIDED.
#
#jdk.serialFilter=pattern;pattern
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.ByteArrayInputStream;
import java.io.InvalidClassException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.security.Security;
import sun.misc.ObjectInputFilter;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.assertFalse;
/* @test
* @build CheckInputOrderTest SerialFilterTest
* @run testng/othervm CheckInputOrderTest
*
* @summary Test that when both global filter and specific filter are set,
* global filter will not affect specific filter.
*/
public class CheckInputOrderTest implements Serializable {
private static final long serialVersionUID = 12345678901L;
@DataProvider(name="Patterns")
Object[][] patterns() {
return new Object[][] {
new Object[] { SerialFilterTest.genTestObject("maxarray=1", true), "java.**;java.lang.*;java.lang.Long;maxarray=0", false },
new Object[] { SerialFilterTest.genTestObject("maxarray=1", true), "java.**;java.lang.*;java.lang.Long", true },
new Object[] { Long.MAX_VALUE, "java.**;java.lang.*;java.lang.Long;maxdepth=0", false },
new Object[] { Long.MAX_VALUE, "java.**;java.lang.*;java.lang.Long;maxbytes=0", false },
new Object[] { Long.MAX_VALUE, "java.**;java.lang.*;java.lang.Long;maxrefs=0", false },
new Object[] { Long.MAX_VALUE, "java.**;java.lang.*;java.lang.Long", true },
new Object[] { Long.MAX_VALUE, "!java.**;java.lang.*;java.lang.Long", false },
new Object[] { Long.MAX_VALUE, "java.**;!java.lang.*;java.lang.Long", true },
new Object[] { Long.MAX_VALUE, "!java.lang.*;java.**;java.lang.Long", false },
new Object[] { Long.MAX_VALUE, "java.lang.*;!java.**;java.lang.Long", true },
new Object[] { Long.MAX_VALUE, "!java.lang.Long;java.**;java.lang.*", false },
new Object[] { Long.MAX_VALUE, "java.lang.Long;java.**;!java.lang.*", true },
new Object[] { Long.MAX_VALUE, "java.lang.Long;!java.**;java.lang.*", false },
new Object[] { Long.MAX_VALUE, "java.lang.Long;java.lang.Number;!java.**;java.lang.*", true },
};
}
/**
* Test:
* "global filter reject" + "specific ObjectInputStream filter is empty" => should reject
* "global filter reject" + "specific ObjectInputStream filter allow" => should allow
*/
@Test(dataProvider="Patterns")
public void testRejectedInGlobal(Object toDeserialized, String pattern, boolean allowed) throws Exception {
byte[] bytes = SerialFilterTest.writeObjects(toDeserialized);
ObjectInputFilter filter = ObjectInputFilter.Config.createFilter(pattern);
try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais)) {
ObjectInputFilter.Config.setObjectInputFilter(ois, filter);
Object o = ois.readObject();
assertTrue(allowed, "filter should have thrown an exception");
} catch (InvalidClassException ice) {
assertFalse(allowed, "filter should have thrown an exception");
}
}
}
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.security.AccessControlException;
import sun.misc.ObjectInputFilter;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
/* @test
* @build FilterWithSecurityManagerTest SerialFilterTest
* @run testng/othervm FilterWithSecurityManagerTest
* @run testng/othervm/policy=security.policy.without.globalFilter
* -Djava.security.manager=default FilterWithSecurityManagerTest
* @run testng/othervm/policy=security.policy
* -Djava.security.manager=default
* -Djdk.serialFilter=java.lang.Integer FilterWithSecurityManagerTest
*
* @summary Test that setting specific filter is checked by security manager,
* setting process-wide filter is checked by security manager.
*/
@Test
public class FilterWithSecurityManagerTest {
byte[] bytes;
boolean setSecurityManager;
ObjectInputFilter filter;
@BeforeClass
public void setup() throws Exception {
setSecurityManager = System.getSecurityManager() != null;
Object toDeserialized = Long.MAX_VALUE;
bytes = SerialFilterTest.writeObjects(toDeserialized);
filter = ObjectInputFilter.Config.createFilter("java.lang.Long");
}
/**
* Test that setting process-wide filter is checked by security manager.
*/
@Test
public void testGlobalFilter() throws Exception {
if (ObjectInputFilter.Config.getSerialFilter() == null) {
return;
}
try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais)) {
ObjectInputFilter.Config.setSerialFilter(filter);
assertFalse(setSecurityManager,
"When SecurityManager exists, without "
+ "java.security.SerializablePermission(serialFilter) Exception should be thrown");
Object o = ois.readObject();
} catch (AccessControlException ex) {
assertTrue(setSecurityManager);
assertTrue(ex.getMessage().contains("java.io.SerializablePermission"));
assertTrue(ex.getMessage().contains("serialFilter"));
}
}
/**
* Test that setting specific filter is checked by security manager.
*/
@Test(dependsOnMethods = { "testGlobalFilter" })
public void testSpecificFilter() throws Exception {
try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais)) {
ObjectInputFilter.Config.setObjectInputFilter(ois, filter);
Object o = ois.readObject();
} catch (AccessControlException ex) {
assertTrue(setSecurityManager);
assertTrue(ex.getMessage().contains("java.io.SerializablePermission"));
assertTrue(ex.getMessage().contains("serialFilter"));
}
}
}
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertSame;
import static org.testng.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InvalidClassException;
import java.io.ObjectInputStream;
import java.io.SerializablePermission;
import java.security.Security;
import java.util.Objects;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.testng.annotations.DataProvider;
import sun.misc.ObjectInputFilter;
/* @test
* @build GlobalFilterTest SerialFilterTest
* @run testng/othervm GlobalFilterTest
* @run testng/othervm -Djdk.serialFilter=java.** GlobalFilterTest
* @run testng/othervm/policy=security.policy GlobalFilterTest
* @run testng/othervm/policy=security.policy
* -Djava.security.properties=${test.src}/java.security-extra1
* -Djava.security.debug=properties GlobalFilterTest
*
* @summary Test Global Filters
*/
@Test
public class GlobalFilterTest {
/**
* DataProvider of patterns and objects derived from the configured process-wide filter.
* @return Array of arrays of pattern, object, allowed boolean, and API factory
*/
@DataProvider(name="globalPatternElements")
Object[][] globalPatternElements() {
String globalFilter =
System.getProperty("jdk.serialFilter",
Security.getProperty("jdk.serialFilter"));
if (globalFilter == null) {
return new Object[0][];
}
String[] patterns = globalFilter.split(";");
Object[][] objects = new Object[patterns.length][];
for (int i = 0; i < patterns.length; i++) {
Object o;
boolean allowed;
String pattern = patterns[i].trim();
if (pattern.contains("=")) {
allowed = false;
o = SerialFilterTest.genTestObject(pattern, false);
} else {
allowed = !pattern.startsWith("!");
o = (allowed)
? SerialFilterTest.genTestObject(pattern, true)
: SerialFilterTest.genTestObject(pattern.substring(1), false);
Assert.assertNotNull(o, "fail generation failed");
}
objects[i] = new Object[3];
objects[i][0] = pattern;
objects[i][1] = allowed;
objects[i][2] = o;
}
return objects;
}
/**
* Test that the process-wide filter is set when the properties are set
* and has the toString matching the configured pattern.
*/
@Test()
static void globalFilter() {
String pattern =
System.getProperty("jdk.serialFilter",
Security.getProperty("jdk.serialFilter"));
ObjectInputFilter filter = ObjectInputFilter.Config.getSerialFilter();
System.out.printf("global pattern: %s, filter: %s%n", pattern, filter);
Assert.assertEquals(pattern, Objects.toString(filter, null),
"process-wide filter pattern does not match");
}
/**
* If the Global filter is already set, it should always refuse to be
* set again.
* If there is a security manager, setting the serialFilter should fail
* without the appropriate permission.
* If there is no security manager then setting it should work.
*/
@Test()
static void setGlobalFilter() {
SecurityManager sm = System.getSecurityManager();
ObjectInputFilter filter = new SerialFilterTest.Validator();
ObjectInputFilter global = ObjectInputFilter.Config.getSerialFilter();
if (global != null) {
// once set, can never be re-set
try {
ObjectInputFilter.Config.setSerialFilter(filter);
Assert.fail("set only once process-wide filter");
} catch (IllegalStateException ise) {
if (sm != null) {
Assert.fail("wrong exception when security manager is set", ise);
}
} catch (SecurityException se) {
if (sm == null) {
Assert.fail("wrong exception when security manager is not set", se);
}
}
} else {
if (sm == null) {
// no security manager
try {
ObjectInputFilter.Config.setSerialFilter(filter);
// Note once set, it can not be reset; so other tests
System.out.printf("Global Filter set to Validator%n");
} catch (SecurityException se) {
Assert.fail("setGlobalFilter should not get SecurityException", se);
}
try {
// Try to set it again, expecting it to throw
ObjectInputFilter.Config.setSerialFilter(filter);
Assert.fail("set only once process-wide filter");
} catch (IllegalStateException ise) {
// Normal case
}
} else {
// Security manager
SecurityException expectSE = null;
try {
sm.checkPermission(new SerializablePermission("serialFilter"));
} catch (SecurityException se1) {
expectSE = se1;
}
SecurityException actualSE = null;
try {
ObjectInputFilter.Config.setSerialFilter(filter);
} catch (SecurityException se2) {
actualSE = se2;
}
if (expectSE == null | actualSE == null) {
Assert.assertEquals(expectSE, actualSE, "SecurityException");
} else {
Assert.assertEquals(expectSE.getClass(), actualSE.getClass(),
"SecurityException class");
}
}
}
}
/**
* For each pattern in the process-wide filter test a generated object
* against the default process-wide filter.
*
* @param pattern a pattern extracted from the configured global pattern
*/
@Test(dataProvider = "globalPatternElements")
static void globalFilterElements(String pattern, boolean allowed,Object obj) {
testGlobalPattern(pattern, obj, allowed);
}
/**
* Serialize and deserialize an object using the default process-wide filter
* and check allowed or reject.
*
* @param pattern the pattern
* @param object the test object
* @param allowed the expected result from ObjectInputStream (exception or not)
*/
static void testGlobalPattern(String pattern, Object object, boolean allowed) {
try {
// System.out.printf("global %s pattern: %s, obj: %s%n", (allowed ? "allowed" : "not allowed"), pattern, object);
byte[] bytes = SerialFilterTest.writeObjects(object);
try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais)) {
Object o = ois.readObject();
} catch (EOFException eof) {
// normal completion
} catch (ClassNotFoundException cnf) {
Assert.fail("Deserializing", cnf);
}
Assert.assertTrue(allowed, "filter should have thrown an exception");
} catch (IllegalArgumentException iae) {
Assert.fail("bad format pattern", iae);
} catch (InvalidClassException ice) {
Assert.assertFalse(allowed, "filter should not have thrown an exception: " + ice);
} catch (IOException ioe) {
Assert.fail("Unexpected IOException", ioe);
}
}
}
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.ByteArrayInputStream;
import java.io.InvalidClassException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.security.Security;
import sun.misc.ObjectInputFilter;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
/* @test
* @build MixedFiltersTest SerialFilterTest
* @run testng/othervm -Djdk.serialFilter=!java.**;!java.lang.Long;maxdepth=5;maxarray=5;maxbytes=90;maxrefs=5 MixedFiltersTest
* @run testng/othervm -Djdk.serialFilter=java.**;java.lang.Long;maxdepth=1000;maxarray=1000;maxbytes=1000;maxrefs=1000 MixedFiltersTest
*
* @summary Test that when both global filter and specific filter are set,
* global filter will not affect specific filter.
*/
public class MixedFiltersTest implements Serializable {
private static final long serialVersionUID = 1234567890L;
boolean globalRejected;
@BeforeClass
public void setup() {
String pattern = System.getProperty("jdk.serialFilter",
Security.getProperty("jdk.serialFilter"));
globalRejected = pattern.startsWith("!");
}
@DataProvider(name="RejectedInGlobal")
Object[][] rejectedInGlobal() {
if (!globalRejected) {
return new Object[0][];
}
return new Object[][] {
new Object[] { Long.MAX_VALUE, "java.**" },
new Object[] { Long.MAX_VALUE, "java.lang.Long" },
new Object[] { SerialFilterTest.genTestObject("java.lang.**", true), "java.lang.**" },
new Object[] { SerialFilterTest.genTestObject("maxdepth=10", true), "maxdepth=100" },
new Object[] { SerialFilterTest.genTestObject("maxarray=10", true), "maxarray=100" },
new Object[] { SerialFilterTest.genTestObject("maxbytes=100", true), "maxbytes=1000" },
new Object[] { SerialFilterTest.genTestObject("maxrefs=10", true), "maxrefs=100" },
};
}
/**
* Test:
* "global filter reject" + "specific ObjectInputStream filter is empty" => should reject
* "global filter reject" + "specific ObjectInputStream filter allow" => should allow
*/
@Test(dataProvider="RejectedInGlobal")
public void testRejectedInGlobal(Object toDeserialized, String pattern) throws Exception {
byte[] bytes = SerialFilterTest.writeObjects(toDeserialized);
try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais)) {
Object o = ois.readObject();
fail("filter should have thrown an exception");
} catch (InvalidClassException expected) { }
ObjectInputFilter filter = ObjectInputFilter.Config.createFilter(pattern);
try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais)) {
ObjectInputFilter.Config.setObjectInputFilter(ois, filter);
Object o = ois.readObject();
}
}
@DataProvider(name="AllowedInGlobal")
Object[][] allowedInGlobal() {
if (globalRejected) {
return new Object[0][];
}
return new Object[][] {
new Object[] { Long.MAX_VALUE, "!java.**" },
new Object[] { Long.MAX_VALUE, "!java.lang.Long" },
new Object[] { SerialFilterTest.genTestObject("java.lang.**", true), "!java.lang.**" },
new Object[] { SerialFilterTest.genTestObject("maxdepth=10", true), "maxdepth=5" },
new Object[] { SerialFilterTest.genTestObject("maxarray=10", true), "maxarray=5" },
new Object[] { SerialFilterTest.genTestObject("maxbytes=100", true), "maxbytes=5" },
new Object[] { SerialFilterTest.genTestObject("maxrefs=10", true), "maxrefs=5" },
};
}
/**
* Test:
* "global filter allow" + "specific ObjectInputStream filter is empty" => should allow
* "global filter allow" + "specific ObjectInputStream filter reject" => should reject
*/
@Test(dataProvider="AllowedInGlobal")
public void testAllowedInGlobal(Object toDeserialized, String pattern) throws Exception {
byte[] bytes = SerialFilterTest.writeObjects(toDeserialized);
try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais)) {
Object o = ois.readObject();
}
ObjectInputFilter filter = ObjectInputFilter.Config.createFilter(pattern);
try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais)) {
ObjectInputFilter.Config.setObjectInputFilter(ois, filter);
Object o = ois.readObject();
assertTrue(false, "filter should have thrown an exception");
} catch (InvalidClassException expected) { }
}
}
# Serialization Input Process-wide Filter
# See conf/security/java.security for pattern synatx
#
jdk.serialFilter=java.**;javax.**;maxarray=34;maxdepth=7
// Individual Permissions to for GlobalFilterTest
grant {
// Specific permission under test
permission java.security.SerializablePermission "serialFilter";
// Permissions needed to run the test
permission java.util.PropertyPermission "*", "read";
permission java.io.FilePermission "<<ALL FILES>>", "read,write,delete";
permission java.lang.reflect.ReflectPermission "suppressAccessChecks";
permission java.security.SecurityPermission "*";
permission java.lang.RuntimePermission "accessDeclaredMembers";
permission java.lang.RuntimePermission "accessClassInPackage.sun.misc";
};
// Standard extensions get all permissions by default
grant codeBase "file:${{java.ext.dirs}}/*" {
permission java.security.AllPermission;
};
// Individual Permissions for FilterWithSecurityManagerTest
grant {
// Permissions needed to run the test
permission java.util.PropertyPermission "*", "read";
permission java.io.FilePermission "<<ALL FILES>>", "read,write,delete";
permission java.lang.reflect.ReflectPermission "suppressAccessChecks";
permission java.lang.RuntimePermission "accessDeclaredMembers";
permission java.lang.RuntimePermission "accessClassInPackage.sun.misc";
};
// Standard extensions get all permissions by default
grant codeBase "file:${{java.ext.dirs}}/*" {
permission java.security.AllPermission;
};
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册