001/**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.activemq.util;
018
019import java.io.IOException;
020import java.io.InputStream;
021import java.io.ObjectInputStream;
022import java.io.ObjectStreamClass;
023import java.lang.reflect.Proxy;
024import java.util.*;
025
026import org.slf4j.Logger;
027import org.slf4j.LoggerFactory;
028
029public class ClassLoadingAwareObjectInputStream extends ObjectInputStream {
030
031    private static final Logger LOG = LoggerFactory.getLogger(ClassLoadingAwareObjectInputStream.class);
032    private static final ClassLoader FALLBACK_CLASS_LOADER =
033        ClassLoadingAwareObjectInputStream.class.getClassLoader();
034
035    public static final String[] serializablePackages;
036
037    private List<String> trustedPackages = new ArrayList<String>();
038    private boolean trustAllPackages = false;
039
040    private final ClassLoader inLoader;
041
042    static {
043        serializablePackages = System.getProperty("org.apache.activemq.SERIALIZABLE_PACKAGES",
044                    "java.lang,javax.security,java.util,org.apache.activemq,org.fusesource.hawtbuf,com.thoughtworks.xstream.mapper").split(",");
045    }
046
047    public ClassLoadingAwareObjectInputStream(InputStream in) throws IOException {
048        super(in);
049        inLoader = in.getClass().getClassLoader();
050        trustedPackages.addAll(Arrays.asList(serializablePackages));
051    }
052
053    @Override
054    protected Class<?> resolveClass(ObjectStreamClass classDesc) throws IOException, ClassNotFoundException {
055        ClassLoader cl = Thread.currentThread().getContextClassLoader();
056        Class clazz = load(classDesc.getName(), cl, inLoader);
057        checkSecurity(clazz);
058        return clazz;
059    }
060
061    @Override
062    protected Class<?> resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException {
063        ClassLoader cl = Thread.currentThread().getContextClassLoader();
064        Class[] cinterfaces = new Class[interfaces.length];
065        for (int i = 0; i < interfaces.length; i++) {
066            cinterfaces[i] = load(interfaces[i], cl);
067        }
068
069        Class clazz = null;
070        try {
071            clazz = Proxy.getProxyClass(cl, cinterfaces);
072        } catch (IllegalArgumentException e) {
073            try {
074                clazz = Proxy.getProxyClass(inLoader, cinterfaces);
075            } catch (IllegalArgumentException e1) {
076                // ignore
077            }
078            try {
079                clazz = Proxy.getProxyClass(FALLBACK_CLASS_LOADER, cinterfaces);
080            } catch (IllegalArgumentException e2) {
081                // ignore
082            }
083        }
084
085        if (clazz != null) {
086            checkSecurity(clazz);
087            return clazz;
088        } else {
089            throw new ClassNotFoundException(null);
090        }
091    }
092
093    public static boolean isAllAllowed() {
094        return serializablePackages.length == 1 && serializablePackages[0].equals("*");
095    }
096
097    private boolean trustAllPackages() {
098        return trustAllPackages || (trustedPackages.size() == 1 && trustedPackages.get(0).equals("*"));
099    }
100
101    private void checkSecurity(Class clazz) throws ClassNotFoundException {
102        if (!clazz.isPrimitive()) {
103            if (clazz.getPackage() != null && !trustAllPackages()) {
104               boolean found = false;
105               for (String packageName : getTrustedPackages()) {
106                   if (clazz.getPackage().getName().equals(packageName) || clazz.getPackage().getName().startsWith(packageName + ".")) {
107                       found = true;
108                       break;
109                   }
110               }
111               if (!found) {
112                   throw new ClassNotFoundException("Forbidden " + clazz + "! This class is not trusted to be serialized as ObjectMessage payload. Please take a look at http://activemq.apache.org/objectmessage.html for more information on how to configure trusted classes.");
113               }
114            }
115        }
116    }
117
118    private Class<?> load(String className, ClassLoader... cl) throws ClassNotFoundException {
119        // check for simple types first
120        final Class<?> clazz = loadSimpleType(className);
121        if (clazz != null) {
122            LOG.trace("Loaded class: {} as simple type -> ", className, clazz);
123            return clazz;
124        }
125
126        // try the different class loaders
127        for (ClassLoader loader : cl) {
128            LOG.trace("Attempting to load class: {} using classloader: {}", className, cl);
129            try {
130                Class<?> answer = Class.forName(className, false, loader);
131                if (LOG.isTraceEnabled()) {
132                    LOG.trace("Loaded class: {} using classloader: {} -> ", new Object[]{className, cl, answer});
133                }
134                return answer;
135            } catch (ClassNotFoundException e) {
136                LOG.trace("Class not found: {} using classloader: {}", className, cl);
137                // ignore
138            }
139        }
140
141        // and then the fallback class loader
142        return Class.forName(className, false, FALLBACK_CLASS_LOADER);
143    }
144
145    /**
146     * Load a simple type
147     *
148     * @param name the name of the class to load
149     * @return the class or <tt>null</tt> if it could not be loaded
150     */
151    public static Class<?> loadSimpleType(String name) {
152        // code from ObjectHelper.loadSimpleType in Apache Camel
153
154        // special for byte[] or Object[] as its common to use
155        if ("java.lang.byte[]".equals(name) || "byte[]".equals(name)) {
156            return byte[].class;
157        } else if ("java.lang.Byte[]".equals(name) || "Byte[]".equals(name)) {
158            return Byte[].class;
159        } else if ("java.lang.Object[]".equals(name) || "Object[]".equals(name)) {
160            return Object[].class;
161        } else if ("java.lang.String[]".equals(name) || "String[]".equals(name)) {
162            return String[].class;
163            // and these is common as well
164        } else if ("java.lang.String".equals(name) || "String".equals(name)) {
165            return String.class;
166        } else if ("java.lang.Boolean".equals(name) || "Boolean".equals(name)) {
167            return Boolean.class;
168        } else if ("boolean".equals(name)) {
169            return boolean.class;
170        } else if ("java.lang.Integer".equals(name) || "Integer".equals(name)) {
171            return Integer.class;
172        } else if ("int".equals(name)) {
173            return int.class;
174        } else if ("java.lang.Long".equals(name) || "Long".equals(name)) {
175            return Long.class;
176        } else if ("long".equals(name)) {
177            return long.class;
178        } else if ("java.lang.Short".equals(name) || "Short".equals(name)) {
179            return Short.class;
180        } else if ("short".equals(name)) {
181            return short.class;
182        } else if ("java.lang.Byte".equals(name) || "Byte".equals(name)) {
183            return Byte.class;
184        } else if ("byte".equals(name)) {
185            return byte.class;
186        } else if ("java.lang.Float".equals(name) || "Float".equals(name)) {
187            return Float.class;
188        } else if ("float".equals(name)) {
189            return float.class;
190        } else if ("java.lang.Double".equals(name) || "Double".equals(name)) {
191            return Double.class;
192        } else if ("double".equals(name)) {
193            return double.class;
194        } else if ("void".equals(name)) {
195            return void.class;
196        }
197
198        return null;
199    }
200
201    public List<String> getTrustedPackages() {
202        return trustedPackages;
203    }
204
205    public void setTrustedPackages(List<String> trustedPackages) {
206        this.trustedPackages = trustedPackages;
207    }
208
209    public void addTrustedPackage(String trustedPackage) {
210        this.trustedPackages.add(trustedPackage);
211    }
212
213    public boolean isTrustAllPackages() {
214        return trustAllPackages;
215    }
216
217    public void setTrustAllPackages(boolean trustAllPackages) {
218        this.trustAllPackages = trustAllPackages;
219    }
220}