|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | + * contributor license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright ownership. |
| 5 | + * The ASF licenses this file to You under the Apache license, Version 2.0 |
| 6 | + * (the "License"); you may not use this file except in compliance with |
| 7 | + * the License. You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the license for the specific language governing permissions and |
| 15 | + * limitations under the license. |
| 16 | + */ |
| 17 | +package org.apache.logging.log4j.core.util; |
| 18 | + |
| 19 | +import java.io.IOException; |
| 20 | +import java.io.InputStream; |
| 21 | +import java.io.InvalidObjectException; |
| 22 | +import java.io.ObjectInputStream; |
| 23 | +import java.io.ObjectStreamClass; |
| 24 | +import java.util.Arrays; |
| 25 | +import java.util.Collection; |
| 26 | +import java.util.List; |
| 27 | + |
| 28 | +/** |
| 29 | + * Extended ObjectInputStream that only allows certain classes to be deserialized. |
| 30 | + * |
| 31 | + * @since 2.8.2 |
| 32 | + */ |
| 33 | +public class FilteredObjectInputStream extends ObjectInputStream { |
| 34 | + |
| 35 | + private static final List<String> REQUIRED_JAVA_CLASSES = Arrays.asList( |
| 36 | + // for StandardLevel |
| 37 | + "java.lang.Enum", |
| 38 | + // for location information |
| 39 | + "java.lang.StackTraceElement", |
| 40 | + // for Message delegate |
| 41 | + "java.rmi.MarshalledObject", |
| 42 | + "[B" |
| 43 | + ); |
| 44 | + |
| 45 | + private final Collection<String> allowedClasses; |
| 46 | + |
| 47 | + public FilteredObjectInputStream(final InputStream in, final Collection<String> allowedClasses) throws IOException { |
| 48 | + super(in); |
| 49 | + this.allowedClasses = allowedClasses; |
| 50 | + } |
| 51 | + |
| 52 | + @Override |
| 53 | + protected Class<?> resolveClass(final ObjectStreamClass desc) throws IOException, ClassNotFoundException { |
| 54 | + String name = desc.getName(); |
| 55 | + if (!(isAllowedByDefault(name) || allowedClasses.contains(name))) { |
| 56 | + throw new InvalidObjectException("Class is not allowed for deserialization: " + name); |
| 57 | + } |
| 58 | + return super.resolveClass(desc); |
| 59 | + } |
| 60 | + |
| 61 | + private static boolean isAllowedByDefault(final String name) { |
| 62 | + return name.startsWith("org.apache.logging.log4j.") || |
| 63 | + name.startsWith("[Lorg.apache.logging.log4j.") || |
| 64 | + REQUIRED_JAVA_CLASSES.contains(name); |
| 65 | + } |
| 66 | + |
| 67 | +} |
0 commit comments