1 /*
  2  * Copyright (c) 1997, 2023, 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 sun.security.util.Debug;
 29 
 30 import java.util.Map;
 31 import java.util.Objects;
 32 import java.util.concurrent.ConcurrentHashMap;
 33 import java.util.function.Function;
 34 
 35 /**
 36  * This class extends {@code 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     /*
 47      * Map that maps the CodeSource to a ProtectionDomain. The key is a
 48      * CodeSourceKey class that uses a {@code String} instead of a URL to avoid
 49      * potential expensive name service lookups. This does mean that URLs that
 50      * are equivalent after nameservice lookup will be placed in separate
 51      * ProtectionDomains; however during policy enforcement these URLs will be
 52      * canonicalized and resolved resulting in a consistent set of granted
 53      * permissions.
 54      */
 55     private final Map<CodeSourceKey, ProtectionDomain> pdcache
 56             = new ConcurrentHashMap<>(11);
 57 
 58     static {
 59         ClassLoader.registerAsParallelCapable();
 60     }
 61 
 62     /**
 63      * Creates a new {@code SecureClassLoader} using the specified parent
 64      * class loader for delegation.
 65      *
 66      * <p>If there is a security manager, this method first
 67      * calls the security manager's {@code checkCreateClassLoader}
 68      * method  to ensure creation of a class loader is allowed.
 69      *
 70      * @param parent the parent ClassLoader
 71      * @throws     SecurityException  if a security manager exists and its
 72      *             {@code checkCreateClassLoader} method doesn't allow
 73      *             creation of a class loader.
 74      * @see SecurityManager#checkCreateClassLoader
 75      */
 76     protected SecureClassLoader(ClassLoader parent) {
 77         super(parent);
 78     }
 79 
 80     /**
 81      * Creates a new {@code SecureClassLoader} using the default parent class
 82      * loader for delegation.
 83      *
 84      * <p>If there is a security manager, this method first
 85      * calls the security manager's {@code checkCreateClassLoader}
 86      * method  to ensure creation of a class loader is allowed.
 87      *
 88      * @throws     SecurityException  if a security manager exists and its
 89      *             {@code checkCreateClassLoader} method doesn't allow
 90      *             creation of a class loader.
 91      * @see SecurityManager#checkCreateClassLoader
 92      */
 93     protected SecureClassLoader() {
 94         super();
 95     }
 96 
 97     /**
 98      * Creates a new {@code SecureClassLoader} of the specified name and
 99      * using the specified parent class loader for delegation.
100      *
101      * @param name class loader name; or {@code null} if not named
102      * @param parent the parent class loader
103      *
104      * @throws IllegalArgumentException if the given name is empty.
105      *
106      * @throws SecurityException  if a security manager exists and its
107      *         {@link SecurityManager#checkCreateClassLoader()} method
108      *         doesn't allow creation of a class loader.
109      *
110      * @since 9
111      */
112     protected SecureClassLoader(String name, ClassLoader parent) {
113         super(name, parent);
114     }
115 
116     /**
117      * Converts an array of bytes into an instance of class {@code Class},
118      * with an optional CodeSource. Before the
119      * class can be used it must be resolved.
120      * <p>
121      * If a non-null CodeSource is supplied a ProtectionDomain is
122      * constructed and associated with the class being defined.
123      *
124      * @param      name the expected name of the class, or {@code null}
125      *                  if not known, using '.' and not '/' as the separator
126      *                  and without a trailing ".class" suffix.
127      * @param      b    the bytes that make up the class data. The bytes in
128      *             positions {@code off} through {@code off+len-1}
129      *             should have the format of a valid class file as defined by
130      *             <cite>The Java Virtual Machine Specification</cite>.
131      * @param      off  the start offset in {@code b} of the class data
132      * @param      len  the length of the class data
133      * @param      cs   the associated CodeSource, or {@code null} if none
134      * @return the {@code Class} object created from the data,
135      *         and optional CodeSource.
136      * @throws     ClassFormatError if the data did not contain a valid class
137      * @throws     IndexOutOfBoundsException if either {@code off} or
138      *             {@code len} is negative, or if
139      *             {@code off+len} is greater than {@code b.length}.
140      *
141      * @throws     SecurityException if an attempt is made to add this class
142      *             to a package that contains classes that were signed by
143      *             a different set of certificates than this class, or if
144      *             the class name begins with "java.".
145      */
146     protected final Class<?> defineClass(String name,
147                                          byte[] b, int off, int len,
148                                          CodeSource cs)
149     {
150         return defineClass(name, b, off, len, getProtectionDomain(cs));
151     }
152 
153     /**
154      * Converts a {@link java.nio.ByteBuffer ByteBuffer}
155      * into an instance of class {@code Class}, with an optional CodeSource.
156      * Before the class can be used it must be resolved.
157      * <p>
158      * If a non-null CodeSource is supplied a ProtectionDomain is
159      * constructed and associated with the class being defined.
160      *
161      * @param      name the expected name of the class, or {@code null}
162      *                  if not known, using '.' and not '/' as the separator
163      *                  and without a trailing ".class" suffix.
164      * @param      b    the bytes that make up the class data.  The bytes from positions
165      *                  {@code b.position()} through {@code b.position() + b.limit() -1}
166      *                  should have the format of a valid class file as defined by
167      *                  <cite>The Java Virtual Machine Specification</cite>.
168      * @param      cs   the associated CodeSource, or {@code null} if none
169      * @return the {@code Class} object created from the data,
170      *         and optional CodeSource.
171      * @throws     ClassFormatError if the data did not contain a valid class
172      * @throws     SecurityException if an attempt is made to add this class
173      *             to a package that contains classes that were signed by
174      *             a different set of certificates than this class, or if
175      *             the class name begins with "java.".
176      *
177      * @since  1.5
178      */
179     protected final Class<?> defineClass(String name, java.nio.ByteBuffer b,
180                                          CodeSource cs)
181     {
182         return defineClass(name, b, getProtectionDomain(cs));
183     }
184 
185     /**
186      * Returns the permissions for the given CodeSource object.
187      * <p>
188      * This method is invoked by the defineClass method which takes
189      * a CodeSource as an argument when it is constructing the
190      * ProtectionDomain for the class being defined.
191      *
192      * @param codesource the codesource.
193      *
194      * @return the permissions granted to the codesource.
195      *
196      */
197     protected PermissionCollection getPermissions(CodeSource codesource)
198     {
199         return new Permissions(); // ProtectionDomain defers the binding
200     }
201 
202     /*
203      * holder class for the static field "debug" to delay its initialization
204      */
205     private static class DebugHolder {
206         private static final Debug debug = Debug.getInstance("scl");
207     }
208 
209     /*
210      * Returned cached ProtectionDomain for the specified CodeSource.
211      */
212     private ProtectionDomain getProtectionDomain(CodeSource cs) {
213         if (cs == null) {
214             return null;
215         }
216 
217         // Use a CodeSourceKey object key. It should behave in the
218         // same manner as the CodeSource when compared for equality except
219         // that no nameservice lookup is done on the hostname (String comparison
220         // only), and the fragment is not considered.
221         CodeSourceKey key = new CodeSourceKey(cs);
222         return pdcache.computeIfAbsent(key, new Function<>() {
223             // Do not turn this into a lambda since it is executed during bootstrap
224             @Override
225             public ProtectionDomain apply(CodeSourceKey key) {
226                 PermissionCollection perms
227                         = SecureClassLoader.this.getPermissions(key.cs);
228                 ProtectionDomain pd = new ProtectionDomain(
229                         key.cs, perms, SecureClassLoader.this, null);
230                 if (DebugHolder.debug != null) {
231                     DebugHolder.debug.println(" getPermissions " + pd);
232                     DebugHolder.debug.println("");
233                 }
234                 return pd;
235             }
236         });
237     }
238 
239     private record CodeSourceKey(CodeSource cs) {
240 
241         @Override
242         public int hashCode() {
243             return Objects.hashCode(cs.getLocationNoFragString());
244         }
245 
246         @Override
247         public boolean equals(Object obj) {
248             if (obj == this) {
249                 return true;
250             }
251 
252             return obj instanceof CodeSourceKey other
253                     && Objects.equals(cs.getLocationNoFragString(),
254                                 other.cs.getLocationNoFragString())
255                     && cs.matchCerts(other.cs, true);
256         }
257     }
258 
259     /**
260      * Called by the VM, during -Xshare:dump
261      */
262     private void resetArchivedStates() {
263         pdcache.clear();
264     }
265 }