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    protected Class<?> resolveClass(ObjectStreamClass classDesc) throws IOException, ClassNotFoundException {
054        ClassLoader cl = Thread.currentThread().getContextClassLoader();
055        Class clazz = load(classDesc.getName(), cl, inLoader);
056        checkSecurity(clazz);
057        return clazz;
058    }
059
060    protected Class<?> resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException {
061        ClassLoader cl = Thread.currentThread().getContextClassLoader();
062        Class[] cinterfaces = new Class[interfaces.length];
063        for (int i = 0; i < interfaces.length; i++) {
064            cinterfaces[i] = load(interfaces[i], cl);
065        }
066
067        Class clazz = null;
068        try {
069            clazz = Proxy.getProxyClass(cl, cinterfaces);
070        } catch (IllegalArgumentException e) {
071            try {
072                clazz = Proxy.getProxyClass(inLoader, cinterfaces);
073            } catch (IllegalArgumentException e1) {
074                // ignore
075            }
076            try {
077                clazz = Proxy.getProxyClass(FALLBACK_CLASS_LOADER, cinterfaces);
078            } catch (IllegalArgumentException e2) {
079                // ignore
080            }
081        }
082
083        if (clazz != null) {
084            checkSecurity(clazz);
085            return clazz;
086        } else {
087            throw new ClassNotFoundException(null);
088        }
089    }
090
091    public static boolean isAllAllowed() {
092        return serializablePackages.length == 1 && serializablePackages[0].equals("*");
093    }
094
095    private boolean trustAllPackages() {
096        return trustAllPackages || (trustedPackages.size() == 1 && trustedPackages.get(0).equals("*"));
097    }
098
099    private void checkSecurity(Class clazz) throws ClassNotFoundException {
100        if (!clazz.isPrimitive()) {
101            if (clazz.getPackage() != null && !trustAllPackages()) {
102               boolean found = false;
103               for (String packageName : getTrustedPackages()) {
104                   if (clazz.getPackage().getName().equals(packageName) || clazz.getPackage().getName().startsWith(packageName + ".")) {
105                       found = true;
106                       break;
107                   }
108               }
109               if (!found) {
110                   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.");
111               }
112            }
113        }
114    }
115
116    private Class<?> load(String className, ClassLoader... cl) throws ClassNotFoundException {
117        // check for simple types first
118        final Class<?> clazz = loadSimpleType(className);
119        if (clazz != null) {
120            LOG.trace("Loaded class: {} as simple type -> ", className, clazz);
121            return clazz;
122        }
123
124        // try the different class loaders
125        for (ClassLoader loader : cl) {
126            LOG.trace("Attempting to load class: {} using classloader: {}", className, cl);
127            try {
128                Class<?> answer = Class.forName(className, false, loader);
129                if (LOG.isTraceEnabled()) {
130                    LOG.trace("Loaded class: {} using classloader: {} -> ", new Object[]{className, cl, answer});
131                }
132                return answer;
133            } catch (ClassNotFoundException e) {
134                LOG.trace("Class not found: {} using classloader: {}", className, cl);
135                // ignore
136            }
137        }
138
139        // and then the fallback class loader
140        return Class.forName(className, false, FALLBACK_CLASS_LOADER);
141    }
142
143    /**
144     * Load a simple type
145     *
146     * @param name the name of the class to load
147     * @return the class or <tt>null</tt> if it could not be loaded
148     */
149    public static Class<?> loadSimpleType(String name) {
150        // code from ObjectHelper.loadSimpleType in Apache Camel
151
152        // special for byte[] or Object[] as its common to use
153        if ("java.lang.byte[]".equals(name) || "byte[]".equals(name)) {
154            return byte[].class;
155        } else if ("java.lang.Byte[]".equals(name) || "Byte[]".equals(name)) {
156            return Byte[].class;
157        } else if ("java.lang.Object[]".equals(name) || "Object[]".equals(name)) {
158            return Object[].class;
159        } else if ("java.lang.String[]".equals(name) || "String[]".equals(name)) {
160            return String[].class;
161            // and these is common as well
162        } else if ("java.lang.String".equals(name) || "String".equals(name)) {
163            return String.class;
164        } else if ("java.lang.Boolean".equals(name) || "Boolean".equals(name)) {
165            return Boolean.class;
166        } else if ("boolean".equals(name)) {
167            return boolean.class;
168        } else if ("java.lang.Integer".equals(name) || "Integer".equals(name)) {
169            return Integer.class;
170        } else if ("int".equals(name)) {
171            return int.class;
172        } else if ("java.lang.Long".equals(name) || "Long".equals(name)) {
173            return Long.class;
174        } else if ("long".equals(name)) {
175            return long.class;
176        } else if ("java.lang.Short".equals(name) || "Short".equals(name)) {
177            return Short.class;
178        } else if ("short".equals(name)) {
179            return short.class;
180        } else if ("java.lang.Byte".equals(name) || "Byte".equals(name)) {
181            return Byte.class;
182        } else if ("byte".equals(name)) {
183            return byte.class;
184        } else if ("java.lang.Float".equals(name) || "Float".equals(name)) {
185            return Float.class;
186        } else if ("float".equals(name)) {
187            return float.class;
188        } else if ("java.lang.Double".equals(name) || "Double".equals(name)) {
189            return Double.class;
190        } else if ("double".equals(name)) {
191            return double.class;
192        }
193
194        return null;
195    }
196
197    public List<String> getTrustedPackages() {
198        return trustedPackages;
199    }
200
201    public void setTrustedPackages(List<String> trustedPackages) {
202        this.trustedPackages = trustedPackages;
203    }
204
205    public void addTrustedPackage(String trustedPackage) {
206        this.trustedPackages.add(trustedPackage);
207    }
208
209    public boolean isTrustAllPackages() {
210        return trustAllPackages;
211    }
212
213    public void setTrustAllPackages(boolean trustAllPackages) {
214        this.trustAllPackages = trustAllPackages;
215    }
216}