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