This is an automated email from the ASF dual-hosted git repository.

SteNicholas pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/celeborn.git


The following commit(s) were added to refs/heads/main by this push:
     new 59fd7a840 [CELEBORN-2309] Introduce JavaDeserializerFilter to support 
deserialization filter
59fd7a840 is described below

commit 59fd7a8402364a1b82a8480dc33e7a5722ec6d2f
Author: SteNicholas <[email protected]>
AuthorDate: Wed Apr 22 10:44:24 2026 +0800

    [CELEBORN-2309] Introduce JavaDeserializerFilter to support deserialization 
filter
    
    ### What changes were proposed in this pull request?
    
    Introduce `JavaDeserializerFilter` — an allowlist-only deserialization 
filter that prevents CWE-502 (Deserialization of Untrusted Data) attacks on 
Celeborn's internal RPC channel.
    
    Key design points:
    - **Dual-layer defense:** On JDK 9+, both a `resolveClass`-based class 
allowlist and JVM-level `ObjectInputFilter` (resource limits: maxdepth, 
maxarray, maxrefs, maxbytes) are enforced. On JDK 8, only the `resolveClass` 
allowlist is active.
    - **Reflection-based JDK compatibility:** Uses reflection to access 
`java.io.ObjectInputFilter` APIs, gracefully degrading on JDK 8 where the API 
does not exist.
    - **Minimal overhead:** Filter pattern and logging proxy are built once at 
construction time; hot-path `isClassAllowed` is a simple `String.startsWith` 
loop over a `String[]` — no streams, no allocation.
    - **Configurable via CelebornConf:** Enabled by default with sensible 
defaults; operators can customize allowed packages and resource limits without 
code changes.
    
    Default allowed package prefixes: `java.`, `scala.`, 
`org.apache.celeborn.`, `com.google.protobuf.`, `[` (arrays).
    
    ### Why are the changes needed?
    
    Celeborn's internal RPC between Master, Workers, and clients uses Java 
serialization (`JavaSerializer`). Without a deserialization filter, an attacker 
with network access to RPC ports can craft a malicious serialized payload 
containing gadget-chain classes (e.g., from commons-collections, Spring, etc.) 
to achieve Remote Code Execution.
    
    This is a well-known attack vector (CWE-502 / OWASP A8:2017). Adding an 
allowlist-only filter ensures that only classes from trusted packages can be 
deserialized, blocking arbitrary gadget-chain exploitation regardless of which 
libraries are on the classpath.
    
    ### Does this PR resolve a correctness bug?
    
    No.
    
    ### Does this PR introduce any user-facing change?
    
    No. The filter is transparent to existing functionality — all legitimate 
Celeborn RPC classes are under `org.apache.celeborn.` which is allowed by 
default. Operators gain new configuration knobs if they need to extend the 
allowlist:
    
    | Config Key | Default |
    |-----------|---------|
    | `celeborn.serializer.deserialization.filter.enabled` | `true` |
    | `celeborn.serializer.deserialization.filter.allowedPackages` | 
`java.,jdk.,sun.,scala.,org.apache.celeborn.,com.google.protobuf.,[` |
    | `celeborn.serializer.deserialization.filter.maxDepth` | `100` |
    | `celeborn.serializer.deserialization.filter.maxArrayLength` | `10000` |
    | `celeborn.serializer.deserialization.filter.maxReferences` | `100000` |
    | `celeborn.serializer.deserialization.filter.maxStreamBytes` | `100000000` 
|
    
    ### How was this patch tested?
    
    - `JavaDeserializerFilterSuiteJ`: unit tests covering default allowlist, 
custom allowlist, valid deserialization round-trip, and rejection of blocked 
classes via crafted serialization payload.
    - Manual integration testing on JDK 8 (graceful degradation) and JDK 11/17 
(full ObjectInputFilter enforcement).
    
    Closes #3664 from SteNicholas/CELEBORN-2309.
    
    Authored-by: SteNicholas <[email protected]>
    Signed-off-by: SteNicholas <[email protected]>
---
 .../common/serializer/JavaDeserializerFilter.java  | 316 +++++++++++++++++++++
 .../org/apache/celeborn/common/CelebornConf.scala  |  80 ++++++
 .../common/serializer/JavaSerializer.scala         |  53 +++-
 .../serializer/JavaDeserializerFilterSuiteJ.java   | 110 +++++++
 4 files changed, 545 insertions(+), 14 deletions(-)

diff --git 
a/common/src/main/java/org/apache/celeborn/common/serializer/JavaDeserializerFilter.java
 
b/common/src/main/java/org/apache/celeborn/common/serializer/JavaDeserializerFilter.java
new file mode 100644
index 000000000..958a89060
--- /dev/null
+++ 
b/common/src/main/java/org/apache/celeborn/common/serializer/JavaDeserializerFilter.java
@@ -0,0 +1,316 @@
+/*
+ * 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.celeborn.common.serializer;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InvalidClassException;
+import java.io.ObjectInputStream;
+import java.io.ObjectStreamClass;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Allowlist-based deserialization filter to prevent CWE-502 (Deserialization 
of Untrusted Data)
+ * attacks on Celeborn's internal RPC channel.
+ *
+ * <p>Provides dual-layer defense:
+ *
+ * <ul>
+ *   <li><b>resolveClass allowlist</b> — enforced on all JDK versions via 
{@link
+ *       #createValidatingInputStream}. Blocks any class whose name does not 
match an allowed
+ *       package prefix.
+ *   <li><b>JVM-level ObjectInputFilter</b> — enforced on JDK 9+ via {@link 
#apply}. Adds resource
+ *       limits (maxdepth, maxarray, maxrefs, maxbytes) and logs rejected 
classes. Accessed through
+ *       reflection to maintain JDK 8 compatibility; gracefully degrades to 
no-op on older JDKs.
+ * </ul>
+ *
+ * @see <a href="https://cwe.mitre.org/data/definitions/502.html";>CWE-502</a>
+ */
+public class JavaDeserializerFilter {
+  private static final Logger LOG = 
LoggerFactory.getLogger(JavaDeserializerFilter.class);
+
+  private static final String[] DEFAULT_ALLOWED_PACKAGES = {
+    "java.", "scala.", "org.apache.celeborn.", "com.google.protobuf.", "["
+  };
+
+  // JDK 9+ ObjectInputFilter API handles, resolved via reflection for JDK 8 
compatibility.
+  // All fields are null when running on JDK 8.
+  private static final Method SET_FILTER_METHOD; // 
ObjectInputStream.setObjectInputFilter
+  private static final Method CREATE_FILTER_METHOD; // 
ObjectInputFilter.Config.createFilter
+  private static final Object STATUS_REJECTED; // 
ObjectInputFilter.Status.REJECTED
+  private static final Object STATUS_ALLOWED; // 
ObjectInputFilter.Status.ALLOWED
+  private static final Method CHECK_METHOD; // ObjectInputFilter.checkInput
+  private static final Method SERIAL_CLASS_METHOD; // 
ObjectInputFilter.FilterInfo.serialClass
+  private static final Class<?>[] FILTER_CLASSES; // [ObjectInputFilter.class] 
for Proxy
+  private static final ClassLoader FILTER_CLASS_LOADER;
+
+  // All-or-nothing initialization: if any lookup fails, all handles remain 
null (JDK 8 path).
+  static {
+    Method setMethod;
+    Method createMethod;
+    Object rejected;
+    Object allowed;
+    Method checkMtd;
+    Method serialClassMtd;
+    Class<?>[] filterClasses;
+    ClassLoader filterCl;
+    try {
+      Class<?> filterCls = Class.forName("java.io.ObjectInputFilter");
+      Class<?> filterInfoCls = 
Class.forName("java.io.ObjectInputFilter$FilterInfo");
+      setMethod = ObjectInputStream.class.getMethod("setObjectInputFilter", 
filterCls);
+      createMethod =
+          
Class.forName("java.io.ObjectInputFilter$Config").getMethod("createFilter", 
String.class);
+      Class<?> statusCls = Class.forName("java.io.ObjectInputFilter$Status");
+      rejected = statusCls.getField("REJECTED").get(null);
+      allowed = statusCls.getField("ALLOWED").get(null);
+      checkMtd = filterCls.getMethod("checkInput", filterInfoCls);
+      serialClassMtd = filterInfoCls.getMethod("serialClass");
+      filterClasses = new Class<?>[] {filterCls};
+      filterCl = filterCls.getClassLoader();
+      if (filterCl == null) {
+        filterCl = JavaDeserializerFilter.class.getClassLoader();
+      }
+    } catch (Exception ignored) {
+      // JDK 8: ObjectInputFilter does not exist — force all handles to null.
+      setMethod = null;
+      createMethod = null;
+      rejected = null;
+      allowed = null;
+      checkMtd = null;
+      serialClassMtd = null;
+      filterClasses = null;
+      filterCl = null;
+    }
+    SET_FILTER_METHOD = setMethod;
+    CREATE_FILTER_METHOD = createMethod;
+    STATUS_REJECTED = rejected;
+    STATUS_ALLOWED = allowed;
+    CHECK_METHOD = checkMtd;
+    SERIAL_CLASS_METHOD = serialClassMtd;
+    FILTER_CLASSES = filterClasses;
+    FILTER_CLASS_LOADER = filterCl;
+  }
+
+  private final String[] allowedPackages;
+  /**
+   * Cached JDK 9+ ObjectInputFilter proxy that delegates to the base filter 
and logs rejections.
+   */
+  private final Object loggingFilter;
+
+  private JavaDeserializerFilter(
+      String[] allowedPackages,
+      int maxDepth,
+      int maxArrayLength,
+      long maxReferences,
+      long maxStreamBytes) {
+    if (allowedPackages == null || allowedPackages.length == 0) {
+      throw new IllegalArgumentException("allowedPackages must not be null or 
empty");
+    }
+    for (String allowedPackage : allowedPackages) {
+      if (allowedPackage == null || allowedPackage.isEmpty()) {
+        throw new IllegalArgumentException("allowedPackages entry must not be 
null or empty");
+      }
+    }
+    this.allowedPackages = allowedPackages.clone();
+    this.loggingFilter =
+        CREATE_FILTER_METHOD != null
+            ? createLoggingFilter(
+                buildFilterPattern(
+                    allowedPackages, maxDepth, maxArrayLength, maxReferences, 
maxStreamBytes))
+            : null;
+  }
+
+  /** Wraps the JDK base filter in a Proxy that logs REJECTED classes at WARN 
level. */
+  private Object createLoggingFilter(String filterPattern) {
+    try {
+      Object baseFilter = CREATE_FILTER_METHOD.invoke(null, filterPattern);
+      Object proxy =
+          Proxy.newProxyInstance(
+              FILTER_CLASS_LOADER,
+              FILTER_CLASSES,
+              (Object p, Method method, Object[] args) -> {
+                Object result = CHECK_METHOD.invoke(baseFilter, args);
+                if (STATUS_REJECTED.equals(result)) {
+                  try {
+                    Class<?> serialClass = (Class<?>) 
SERIAL_CLASS_METHOD.invoke(args[0]);
+                    if (serialClass != null) {
+                      // JDK ObjectInputFilter unwraps arrays to their 
primitive component type,
+                      // which then gets rejected by "!*" since primitives 
match no pattern.
+                      // Override REJECTED for arrays whose base component 
type is primitive
+                      // or whose component class name is in the allowlist.
+                      if (serialClass.isArray()) {
+                        Class<?> component = serialClass;
+                        while (component.isArray()) {
+                          component = component.getComponentType();
+                        }
+                        if (component.isPrimitive() || 
isClassAllowed(component.getName())) {
+                          return STATUS_ALLOWED;
+                        }
+                      }
+                      LOG.error("ObjectInputFilter REJECTED class: {}.", 
serialClass.getName());
+                    }
+                  } catch (Exception exception) {
+                    LOG.error("Error logging rejected class.", exception);
+                  }
+                }
+                return result;
+              });
+      LOG.debug("Created deserialization filter with pattern: {}.", 
filterPattern);
+      return proxy;
+    } catch (Exception exception) {
+      LOG.error("Failed to create deserialization filter.", exception);
+      return null;
+    }
+  }
+
+  /**
+   * Builds a JDK ObjectInputFilter pattern string. Uses "**" for package 
prefixes to match
+   * subpackages at any depth, and ends with "!*" to reject everything not 
explicitly allowed. A
+   * limit value of 0 means "no limit" per the JDK ObjectInputFilter 
specification.
+   */
+  private static String buildFilterPattern(
+      String[] allowedPackages,
+      int maxDepth,
+      int maxArrayLength,
+      long maxReferences,
+      long maxStreamBytes) {
+    StringBuilder pattern = new StringBuilder();
+    pattern.append("maxdepth=").append(maxDepth);
+    pattern.append(";maxarray=").append(maxArrayLength);
+    pattern.append(";maxrefs=").append(maxReferences);
+    pattern.append(";maxbytes=").append(maxStreamBytes).append(';');
+    for (String allowedPackage : allowedPackages) {
+      // Skip "[" — array types are handled by the logging filter proxy which
+      // checks component types. The JDK filter unwraps arrays to their 
primitive
+      // component type, making pattern-based matching ineffective for arrays.
+      if (allowedPackage.equals("[")) {
+        continue;
+      }
+      pattern.append(allowedPackage).append("**;");
+    }
+    pattern.append("!*");
+    return pattern.toString();
+  }
+
+  /** Creates a filter with custom allowed packages and resource limits. */
+  public static JavaDeserializerFilter create(
+      String[] allowedPackages,
+      int maxDepth,
+      int maxArrayLength,
+      long maxReferences,
+      long maxStreamBytes) {
+    return new JavaDeserializerFilter(
+        allowedPackages, maxDepth, maxArrayLength, maxReferences, 
maxStreamBytes);
+  }
+
+  /** Creates a filter with default allowed packages and no resource limits. */
+  public static JavaDeserializerFilter create() {
+    return new JavaDeserializerFilter(DEFAULT_ALLOWED_PACKAGES, 0, 0, 0, 0);
+  }
+
+  /** Applies the JDK 9+ ObjectInputFilter to the stream. No-op on JDK 8. */
+  public void apply(ObjectInputStream inputStream) {
+    if (loggingFilter == null) {
+      return;
+    }
+    try {
+      SET_FILTER_METHOD.invoke(inputStream, loggingFilter);
+    } catch (Exception exception) {
+      LOG.error("Failed to apply logging filter.", exception);
+    }
+  }
+
+  /**
+   * Creates an ObjectInputStream that checks each class against the allowlist 
before resolving.
+   *
+   * @param classLoader the class loader for resolving classes; null uses the 
bootstrap loader.
+   */
+  public ObjectInputStream createValidatingInputStream(
+      InputStream inputStream, ClassLoader classLoader) throws IOException {
+    return new ObjectInputStream(inputStream) {
+      @Override
+      protected Class<?> resolveClass(ObjectStreamClass desc)
+          throws IOException, ClassNotFoundException {
+        String className = desc.getName();
+        Class<?> primitive = resolvePrimitiveClass(className);
+        if (primitive != null) {
+          return primitive;
+        }
+        if (!isClassAllowed(className)) {
+          LOG.error("REJECTED class during deserialization: {}.", className);
+          throw new InvalidClassException(className, "Blocked");
+        }
+        return Class.forName(className, false, classLoader);
+      }
+
+      @Override
+      protected Class<?> resolveProxyClass(String[] interfaces)
+          throws IOException, ClassNotFoundException {
+        ClassLoader cl =
+            classLoader != null ? classLoader : 
Thread.currentThread().getContextClassLoader();
+        Class<?>[] ifaceClasses = new Class<?>[interfaces.length];
+        for (int i = 0; i < interfaces.length; i++) {
+          if (!isClassAllowed(interfaces[i])) {
+            LOG.error("REJECTED proxy interface during deserialization: {}.", 
interfaces[i]);
+            throw new InvalidClassException(interfaces[i], "Blocked proxy 
interface");
+          }
+          ifaceClasses[i] = Class.forName(interfaces[i], false, cl);
+        }
+        return Proxy.getProxyClass(cl, ifaceClasses);
+      }
+    };
+  }
+
+  protected boolean isClassAllowed(String className) {
+    for (String allowedPackage : allowedPackages) {
+      if (className.startsWith(allowedPackage)) {
+        return true;
+      }
+    }
+    return false;
+  }
+
+  private static Class<?> resolvePrimitiveClass(String name) {
+    switch (name) {
+      case "boolean":
+        return boolean.class;
+      case "byte":
+        return byte.class;
+      case "char":
+        return char.class;
+      case "short":
+        return short.class;
+      case "int":
+        return int.class;
+      case "long":
+        return long.class;
+      case "float":
+        return float.class;
+      case "double":
+        return double.class;
+      case "void":
+        return void.class;
+      default:
+        return null;
+    }
+  }
+}
diff --git 
a/common/src/main/scala/org/apache/celeborn/common/CelebornConf.scala 
b/common/src/main/scala/org/apache/celeborn/common/CelebornConf.scala
index 798099bcb..0b35f9ed2 100644
--- a/common/src/main/scala/org/apache/celeborn/common/CelebornConf.scala
+++ b/common/src/main/scala/org/apache/celeborn/common/CelebornConf.scala
@@ -1674,6 +1674,20 @@ class CelebornConf(loadDefaults: Boolean) extends 
Cloneable with Logging with Se
   def secretRedactionPattern = get(SECRET_REDACTION_PATTERN)
 
   def containerInfoProviderClass = get(CONTAINER_INFO_PROVIDER)
+
+  // //////////////////////////////////////////////////////
+  //                     Serializer                       //
+  // //////////////////////////////////////////////////////
+  def serializerDeserializationFilterEnabled = 
get(SERIALIZER_DESERIALIZATION_FILTER_ENABLED)
+  def serializerDeserializationFilterAllowedPackages =
+    get(SERIALIZER_DESERIALIZATION_FILTER_ALLOWED_PACKAGES)
+  def serializerDeserializationFilterMaxDepth = 
get(SERIALIZER_DESERIALIZATION_FILTER_MAX_DEPTH)
+  def serializerDeserializationFilterMaxArrayLength =
+    get(SERIALIZER_DESERIALIZATION_FILTER_MAX_ARRAY_LENGTH)
+  def serializerDeserializationFilterMaxReferences =
+    get(SERIALIZER_DESERIALIZATION_FILTER_MAX_REFERENCES)
+  def serializerDeserializationFilterMaxStreamBytes =
+    get(SERIALIZER_DESERIALIZATION_FILTER_MAX_STREAM_BYTES)
 }
 
 object CelebornConf extends Logging {
@@ -6485,6 +6499,72 @@ object CelebornConf extends Logging {
       .booleanConf
       .createWithDefault(false)
 
+  val SERIALIZER_DESERIALIZATION_FILTER_ENABLED: ConfigEntry[Boolean] =
+    buildConf("celeborn.serializer.deserialization.filter.enabled")
+      .categories("security")
+      .version("0.7.0")
+      .doc("Whether to enable deserialization filter to prevent 
deserialization attacks. " +
+        "When enabled, only classes from allowed packages can be deserialized. 
" +
+        "This is a critical security feature to prevent Remote Code Execution 
(RCE) attacks.")
+      .booleanConf
+      .createWithDefault(true)
+
+  val SERIALIZER_DESERIALIZATION_FILTER_ALLOWED_PACKAGES: ConfigEntry[String] =
+    buildConf("celeborn.serializer.deserialization.filter.allowedPackages")
+      .categories("security")
+      .version("0.7.0")
+      .doc("Comma-separated list of package prefixes allowed for 
deserialization. " +
+        "Classes from these packages will be allowed to be deserialized. " +
+        "Use with caution - adding packages may expose the system to 
deserialization attacks. " +
+        "Must match DEFAULT_ALLOWED_PACKAGES in JavaDeserializerFilter.")
+      .stringConf
+      .createWithDefault(
+        "java.," +
+          "scala.," +
+          "org.apache.celeborn.," +
+          "com.google.protobuf.," +
+          "[")
+
+  val SERIALIZER_DESERIALIZATION_FILTER_MAX_DEPTH: ConfigEntry[Int] =
+    buildConf("celeborn.serializer.deserialization.filter.maxDepth")
+      .categories("security")
+      .version("0.7.0")
+      .doc("Maximum depth of object graph allowed during deserialization. " +
+        "Helps prevent deep object graph attacks.")
+      .intConf
+      .checkValue(_ > 0, "maxDepth must be positive")
+      .createWithDefault(100)
+
+  val SERIALIZER_DESERIALIZATION_FILTER_MAX_ARRAY_LENGTH: ConfigEntry[Int] =
+    buildConf("celeborn.serializer.deserialization.filter.maxArrayLength")
+      .categories("security")
+      .version("0.7.0")
+      .doc("Maximum array length allowed during deserialization. " +
+        "Helps prevent memory exhaustion attacks.")
+      .intConf
+      .checkValue(_ > 0, "maxArrayLength must be positive")
+      .createWithDefault(10000)
+
+  val SERIALIZER_DESERIALIZATION_FILTER_MAX_REFERENCES: ConfigEntry[Long] =
+    buildConf("celeborn.serializer.deserialization.filter.maxReferences")
+      .categories("security")
+      .version("0.7.0")
+      .doc("Maximum number of object references allowed during 
deserialization. " +
+        "Helps prevent memory exhaustion attacks.")
+      .longConf
+      .checkValue(_ > 0, "maxReferences must be positive")
+      .createWithDefault(100000)
+
+  val SERIALIZER_DESERIALIZATION_FILTER_MAX_STREAM_BYTES: ConfigEntry[Long] =
+    buildConf("celeborn.serializer.deserialization.filter.maxStreamBytes")
+      .categories("security")
+      .version("0.7.0")
+      .doc("Maximum number of bytes allowed in the deserialization stream. " +
+        "Helps prevent memory exhaustion attacks from large payloads.")
+      .longConf
+      .checkValue(_ > 0, "maxStreamBytes must be positive")
+      .createWithDefault(100000000L)
+
   val MASTER_INTERNAL_PORT: ConfigEntry[Int] =
     buildConf("celeborn.master.internal.port")
       .categories("master")
diff --git 
a/common/src/main/scala/org/apache/celeborn/common/serializer/JavaSerializer.scala
 
b/common/src/main/scala/org/apache/celeborn/common/serializer/JavaSerializer.scala
index 3a813ef9c..68b5afc3d 100644
--- 
a/common/src/main/scala/org/apache/celeborn/common/serializer/JavaSerializer.scala
+++ 
b/common/src/main/scala/org/apache/celeborn/common/serializer/JavaSerializer.scala
@@ -59,19 +59,30 @@ private[celeborn] class JavaSerializationStream(
   def close() { objOut.close() }
 }
 
-private[celeborn] class JavaDeserializationStream(in: InputStream, loader: 
ClassLoader)
+private[celeborn] class JavaDeserializationStream(
+    in: InputStream,
+    loader: ClassLoader,
+    filter: JavaDeserializerFilter)
   extends DeserializationStream {
 
-  private val objIn = new ObjectInputStream(in) {
-    override def resolveClass(desc: ObjectStreamClass): Class[_] =
-      try {
-        // scalastyle:off classforname
-        Class.forName(desc.getName, false, loader)
-        // scalastyle:on classforname
-      } catch {
-        case e: ClassNotFoundException =>
-          JavaDeserializationStream.primitiveMappings.getOrElse(desc.getName, 
throw e)
+  private val objIn: ObjectInputStream = {
+    if (filter != null) {
+      val validatingStream = filter.createValidatingInputStream(in, loader)
+      filter.apply(validatingStream)
+      validatingStream
+    } else {
+      new ObjectInputStream(in) {
+        override def resolveClass(desc: ObjectStreamClass): Class[_] =
+          try {
+            // scalastyle:off classforname
+            Class.forName(desc.getName, false, loader)
+            // scalastyle:on classforname
+          } catch {
+            case e: ClassNotFoundException =>
+              
JavaDeserializationStream.primitiveMappings.getOrElse(desc.getName, throw e)
+          }
       }
+    }
   }
 
   def readObject[T: ClassTag](): T = objIn.readObject().asInstanceOf[T]
@@ -94,7 +105,8 @@ private object JavaDeserializationStream {
 private[celeborn] class JavaSerializerInstance(
     counterReset: Int,
     extraDebugInfo: Boolean,
-    defaultClassLoader: ClassLoader)
+    defaultClassLoader: ClassLoader,
+    deserializerFilter: JavaDeserializerFilter)
   extends SerializerInstance {
 
   override def serialize[T: ClassTag](t: T): ByteBuffer = {
@@ -152,11 +164,11 @@ private[celeborn] class JavaSerializerInstance(
   }
 
   override def deserializeStream(s: InputStream): DeserializationStream = {
-    new JavaDeserializationStream(s, defaultClassLoader)
+    new JavaDeserializationStream(s, defaultClassLoader, deserializerFilter)
   }
 
   def deserializeStream(s: InputStream, loader: ClassLoader): 
DeserializationStream = {
-    new JavaDeserializationStream(s, loader)
+    new JavaDeserializationStream(s, loader, deserializerFilter)
   }
 }
 
@@ -175,11 +187,24 @@ class JavaSerializer(conf: CelebornConf) extends 
Serializer with Externalizable
   private var counterReset = conf.getInt("spark.serializer.objectStreamReset", 
100)
   private var extraDebugInfo = 
conf.getBoolean("spark.serializer.extraDebugInfo", true)
 
+  @transient private val deserializerFilter: JavaDeserializerFilter = {
+    if (!conf.serializerDeserializationFilterEnabled) null
+    else {
+      JavaDeserializerFilter.create(
+        conf.serializerDeserializationFilterAllowedPackages
+          .split(",").map(_.trim).filter(_.nonEmpty),
+        conf.serializerDeserializationFilterMaxDepth,
+        conf.serializerDeserializationFilterMaxArrayLength,
+        conf.serializerDeserializationFilterMaxReferences,
+        conf.serializerDeserializationFilterMaxStreamBytes)
+    }
+  }
+
   protected def this() = this(new CelebornConf()) // For deserialization only
 
   override def newInstance(): SerializerInstance = {
     val classLoader = 
defaultClassLoader.getOrElse(Thread.currentThread.getContextClassLoader)
-    new JavaSerializerInstance(counterReset, extraDebugInfo, classLoader)
+    new JavaSerializerInstance(counterReset, extraDebugInfo, classLoader, 
deserializerFilter)
   }
 
   override def writeExternal(out: ObjectOutput): Unit = Utils.tryOrIOException 
{
diff --git 
a/common/src/test/java/org/apache/celeborn/common/serializer/JavaDeserializerFilterSuiteJ.java
 
b/common/src/test/java/org/apache/celeborn/common/serializer/JavaDeserializerFilterSuiteJ.java
new file mode 100644
index 000000000..1539c50c9
--- /dev/null
+++ 
b/common/src/test/java/org/apache/celeborn/common/serializer/JavaDeserializerFilterSuiteJ.java
@@ -0,0 +1,110 @@
+/*
+ * 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.celeborn.common.serializer;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.InvalidClassException;
+import java.io.ObjectOutputStream;
+
+import org.junit.Test;
+
+/** Tests for {@link JavaDeserializerFilter}. */
+public class JavaDeserializerFilterSuiteJ {
+
+  @Test
+  public void testDefaultAllowedPackages() {
+    JavaDeserializerFilter filter = JavaDeserializerFilter.create();
+    assertTrue(filter.isClassAllowed("java.lang.String"));
+    assertTrue(filter.isClassAllowed("scala.Option"));
+    assertTrue(filter.isClassAllowed("org.apache.celeborn.Worker"));
+    assertTrue(filter.isClassAllowed("com.google.protobuf.Message"));
+    assertTrue(filter.isClassAllowed("[B"));
+    assertTrue(filter.isClassAllowed("[Ljava.lang.String;"));
+    assertFalse(filter.isClassAllowed("jdk.internal.misc.Unsafe"));
+    assertFalse(filter.isClassAllowed("sun.misc.Unsafe"));
+    assertFalse(filter.isClassAllowed("com.malicious.Payload"));
+  }
+
+  @Test
+  public void testCustomAllowedPackages() {
+    JavaDeserializerFilter filter =
+        JavaDeserializerFilter.create(
+            new String[] {"java.", "com.x."}, 50, 5000, 50000L, 50000000L);
+    assertTrue(filter.isClassAllowed("java.lang.String"));
+    assertFalse(filter.isClassAllowed("scala.Option"));
+  }
+
+  @Test
+  public void testValidDeserialization() throws Exception {
+    JavaDeserializerFilter filter = JavaDeserializerFilter.create();
+    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
+    ObjectOutputStream objectStream = new ObjectOutputStream(byteStream);
+    objectStream.writeObject("test");
+    objectStream.close();
+    Object result =
+        filter
+            .createValidatingInputStream(new 
ByteArrayInputStream(byteStream.toByteArray()), null)
+            .readObject();
+    assertEquals("test", result);
+  }
+
+  @Test
+  public void testPrimitiveClassDeserialization() throws Exception {
+    JavaDeserializerFilter filter = JavaDeserializerFilter.create();
+    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
+    ObjectOutputStream objectStream = new ObjectOutputStream(byteStream);
+    objectStream.writeObject(int.class);
+    objectStream.close();
+    Object result =
+        filter
+            .createValidatingInputStream(new 
ByteArrayInputStream(byteStream.toByteArray()), null)
+            .readObject();
+    assertEquals(int.class, result);
+  }
+
+  @Test(expected = InvalidClassException.class)
+  public void testRejectBlockedClass() throws Exception {
+    JavaDeserializerFilter.create()
+        .createValidatingInputStream(new 
ByteArrayInputStream(createFakePayload("com.x.A")), null)
+        .readObject();
+  }
+
+  private static byte[] createFakePayload(String className) throws IOException 
{
+    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
+    DataOutputStream dataStream = new DataOutputStream(byteStream);
+    dataStream.writeShort(0xACED);
+    dataStream.writeShort(5);
+    dataStream.writeByte(0x73);
+    dataStream.writeByte(0x72);
+    dataStream.writeShort(className.length());
+    dataStream.writeBytes(className);
+    dataStream.writeLong(1);
+    dataStream.writeByte(2);
+    dataStream.writeShort(0);
+    dataStream.writeByte(0x78);
+    dataStream.writeByte(0x70);
+    return byteStream.toByteArray();
+  }
+}

Reply via email to