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