1 /*
2  * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.  Oracle designates this
8  * particular file as subject to the "Classpath" exception as provided
9  * by Oracle in the LICENSE file that accompanied this code.
10  *
11  * This code is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * version 2 for more details (a copy is included in the LICENSE file that
15  * accompanied this code).
16  *
17  * You should have received a copy of the GNU General Public License version
18  * 2 along with this work; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22  * or visit www.oracle.com if you need additional information or have any
23  * questions.
24  */

25
26 package java.security;
27
28 import java.util.Map;
29 import java.util.Objects;
30 import java.util.concurrent.ConcurrentHashMap;
31 import java.util.function.Function;
32
33 import sun.security.util.Debug;
34
35 /**
36  * This class extends ClassLoader with additional support for defining
37  * classes with an associated code source and permissions which are
38  * retrieved by the system policy by default.
39  *
40  * @author  Li Gong
41  * @author  Roland Schemers
42  * @since 1.2
43  */

44 public class SecureClassLoader extends ClassLoader {
45     /*
46      * If initialization succeed this is set to true and security checks will
47      * succeed. Otherwise the object is not initialized and the object is
48      * useless.
49      */

50     private final boolean initialized;
51
52     /*
53      * Map that maps the CodeSource to a ProtectionDomain. The key is a
54      * CodeSourceKey class that uses a String instead of a URL to avoid
55      * potential expensive name service lookups. This does mean that URLs that
56      * are equivalent after nameservice lookup will be placed in separate
57      * ProtectionDomains; however during policy enforcement these URLs will be
58      * canonicalized and resolved resulting in a consistent set of granted
59      * permissions.
60      */

61     private final Map<CodeSourceKey, ProtectionDomain> pdcache
62             = new ConcurrentHashMap<>(11);
63
64     static {
65         ClassLoader.registerAsParallelCapable();
66     }
67
68     /**
69      * Creates a new SecureClassLoader using the specified parent
70      * class loader for delegation.
71      *
72      * <p>If there is a security manager, this method first
73      * calls the security manager's {@code checkCreateClassLoader}
74      * method  to ensure creation of a class loader is allowed.
75      *
76      * @param parent the parent ClassLoader
77      * @exception  SecurityException  if a security manager exists and its
78      *             {@code checkCreateClassLoader} method doesn't allow
79      *             creation of a class loader.
80      * @see SecurityManager#checkCreateClassLoader
81      */

82     protected SecureClassLoader(ClassLoader parent) {
83         super(parent);
84         // this is to make the stack depth consistent with 1.1
85         SecurityManager security = System.getSecurityManager();
86         if (security != null) {
87             security.checkCreateClassLoader();
88         }
89         initialized = true;
90     }
91
92     /**
93      * Creates a new SecureClassLoader using the default parent class
94      * loader for delegation.
95      *
96      * <p>If there is a security manager, this method first
97      * calls the security manager's {@code checkCreateClassLoader}
98      * method  to ensure creation of a class loader is allowed.
99      *
100      * @exception  SecurityException  if a security manager exists and its
101      *             {@code checkCreateClassLoader} method doesn't allow
102      *             creation of a class loader.
103      * @see SecurityManager#checkCreateClassLoader
104      */

105     protected SecureClassLoader() {
106         super();
107         // this is to make the stack depth consistent with 1.1
108         SecurityManager security = System.getSecurityManager();
109         if (security != null) {
110             security.checkCreateClassLoader();
111         }
112         initialized = true;
113     }
114
115     /**
116      * Creates a new {@code SecureClassLoader} of the specified name and
117      * using the specified parent class loader for delegation.
118      *
119      * @param name class loader name; or {@code nullif not named
120      * @param parent the parent class loader
121      *
122      * @throws IllegalArgumentException if the given name is empty.
123      *
124      * @throws SecurityException  if a security manager exists and its
125      *         {@link SecurityManager#checkCreateClassLoader()} method
126      *         doesn't allow creation of a class loader.
127      *
128      * @since 9
129      * @spec JPMS
130      */

131     protected SecureClassLoader(String name, ClassLoader parent) {
132         super(name, parent);
133         SecurityManager security = System.getSecurityManager();
134         if (security != null) {
135             security.checkCreateClassLoader();
136         }
137         initialized = true;
138     }
139
140     /**
141      * Converts an array of bytes into an instance of class Class,
142      * with an optional CodeSource. Before the
143      * class can be used it must be resolved.
144      * <p>
145      * If a non-null CodeSource is supplied a ProtectionDomain is
146      * constructed and associated with the class being defined.
147      *
148      * @param      name the expected name of the class, or {@code null}
149      *                  if not known, using '.' and not '/' as the separator
150      *                  and without a trailing ".class" suffix.
151      * @param      b    the bytes that make up the class data. The bytes in
152      *             positions {@code off} through {@code off+len-1}
153      *             should have the format of a valid class file as defined by
154      *             <cite>The Java&trade; Virtual Machine Specification</cite>.
155      * @param      off  the start offset in {@code b} of the class data
156      * @param      len  the length of the class data
157      * @param      cs   the associated CodeSource, or {@code nullif none
158      * @return the {@code Class} object created from the data,
159      *         and optional CodeSource.
160      * @exception  ClassFormatError if the data did not contain a valid class
161      * @exception  IndexOutOfBoundsException if either {@code off} or
162      *             {@code len} is negative, or if
163      *             {@code off+len} is greater than {@code b.length}.
164      *
165      * @exception  SecurityException if an attempt is made to add this class
166      *             to a package that contains classes that were signed by
167      *             a different set of certificates than this class, or if
168      *             the class name begins with "java.".
169      */

170     protected final Class<?> defineClass(String name,
171                                          byte[] b, int off, int len,
172                                          CodeSource cs)
173     {
174         return defineClass(name, b, off, len, getProtectionDomain(cs));
175     }
176
177     /**
178      * Converts a {@link java.nio.ByteBuffer ByteBuffer}
179      * into an instance of class {@code Class}, with an optional CodeSource.
180      * Before the class can be used it must be resolved.
181      * <p>
182      * If a non-null CodeSource is supplied a ProtectionDomain is
183      * constructed and associated with the class being defined.
184      *
185      * @param      name the expected name of the class, or {@code null}
186      *                  if not known, using '.' and not '/' as the separator
187      *                  and without a trailing ".class" suffix.
188      * @param      b    the bytes that make up the class data.  The bytes from positions
189      *                  {@code b.position()} through {@code b.position() + b.limit() -1}
190      *                  should have the format of a valid class file as defined by
191      *                  <cite>The Java&trade; Virtual Machine Specification</cite>.
192      * @param      cs   the associated CodeSource, or {@code nullif none
193      * @return the {@code Class} object created from the data,
194      *         and optional CodeSource.
195      * @exception  ClassFormatError if the data did not contain a valid class
196      * @exception  SecurityException if an attempt is made to add this class
197      *             to a package that contains classes that were signed by
198      *             a different set of certificates than this class, or if
199      *             the class name begins with "java.".
200      *
201      * @since  1.5
202      */

203     protected final Class<?> defineClass(String name, java.nio.ByteBuffer b,
204                                          CodeSource cs)
205     {
206         return defineClass(name, b, getProtectionDomain(cs));
207     }
208
209     /**
210      * Returns the permissions for the given CodeSource object.
211      * <p>
212      * This method is invoked by the defineClass method which takes
213      * a CodeSource as an argument when it is constructing the
214      * ProtectionDomain for the class being defined.
215      *
216      * @param codesource the codesource.
217      *
218      * @return the permissions granted to the codesource.
219      *
220      */

221     protected PermissionCollection getPermissions(CodeSource codesource)
222     {
223         check();
224         return new Permissions(); // ProtectionDomain defers the binding
225     }
226
227     /*
228      * holder class for the static field "debug" to delay its initialization
229      */

230     private static class DebugHolder {
231         private static final Debug debug = Debug.getInstance("scl");
232     }
233
234     /*
235      * Returned cached ProtectionDomain for the specified CodeSource.
236      */

237     private ProtectionDomain getProtectionDomain(CodeSource cs) {
238         if (cs == null) {
239             return null;
240         }
241
242         // Use a CodeSourceKey object key. It should behave in the
243         // same manner as the CodeSource when compared for equality except
244         // that no nameservice lookup is done on the hostname (String comparison
245         // only), and the fragment is not considered.
246         CodeSourceKey key = new CodeSourceKey(cs);
247         return pdcache.computeIfAbsent(key, new Function<>() {
248             @Override
249             public ProtectionDomain apply(CodeSourceKey key /* not used */) {
250                 PermissionCollection perms
251                         = SecureClassLoader.this.getPermissions(cs);
252                 ProtectionDomain pd = new ProtectionDomain(
253                         cs, perms, SecureClassLoader.thisnull);
254                 if (DebugHolder.debug != null) {
255                     DebugHolder.debug.println(" getPermissions " + pd);
256                     DebugHolder.debug.println("");
257                 }
258                 return pd;
259             }
260         });
261     }
262
263     /*
264      * Check to make sure the class loader has been initialized.
265      */

266     private void check() {
267         if (!initialized) {
268             throw new SecurityException("ClassLoader object not initialized");
269         }
270     }
271
272     private static class CodeSourceKey {
273         private final CodeSource cs;
274
275         CodeSourceKey(CodeSource cs) {
276             this.cs = cs;
277         }
278
279         @Override
280         public int hashCode() {
281             String locationNoFrag = cs.getLocationNoFragString();
282             return locationNoFrag != null ? locationNoFrag.hashCode() : 0;
283         }
284
285         @Override
286         public boolean equals(Object obj) {
287             if (obj == this) {
288                 return true;
289             }
290
291             if (!(obj instanceof CodeSourceKey)) {
292                 return false;
293             }
294
295             CodeSourceKey csk = (CodeSourceKey) obj;
296
297             if (!Objects.equals(cs.getLocationNoFragString(),
298                                 csk.cs.getLocationNoFragString())) {
299                 return false;
300             }
301
302             return cs.matchCerts(csk.cs, true);
303         }
304     }
305 }
306