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