1 /*
   2  * Copyright (c) 2008, 2018, 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 sun.invoke.util;
  27 
  28 import java.lang.reflect.Modifier;
  29 import static java.lang.reflect.Modifier.*;
  30 import java.util.Objects;
  31 import jdk.internal.reflect.Reflection;
  32 
  33 /**
  34  * This class centralizes information about the JVM's linkage access control.
  35  * @author jrose
  36  */
  37 public class VerifyAccess {
  38 
  39     private VerifyAccess() { }  // cannot instantiate
  40 
  41     private static final int UNCONDITIONAL_ALLOWED = java.lang.invoke.MethodHandles.Lookup.UNCONDITIONAL;
  42     private static final int MODULE_ALLOWED = java.lang.invoke.MethodHandles.Lookup.MODULE;
  43     private static final int PACKAGE_ONLY = 0;
  44     private static final int PACKAGE_ALLOWED = java.lang.invoke.MethodHandles.Lookup.PACKAGE;
  45     private static final int PROTECTED_OR_PACKAGE_ALLOWED = (PACKAGE_ALLOWED|PROTECTED);
  46     private static final int ALL_ACCESS_MODES = (PUBLIC|PRIVATE|PROTECTED|PACKAGE_ONLY);
  47 
  48     /**
  49      * Evaluate the JVM linkage rules for access to the given method
  50      * on behalf of a caller class which proposes to perform the access.
  51      * Return true if the caller class has privileges to invoke a method
  52      * or access a field with the given properties.
  53      * This requires an accessibility check of the referencing class,
  54      * plus an accessibility check of the member within the class,
  55      * which depends on the member's modifier flags.
  56      * <p>
  57      * The relevant properties include the defining class ({@code defc})
  58      * of the member, and its modifier flags ({@code mods}).
  59      * Also relevant is the class used to make the initial symbolic reference
  60      * to the member ({@code refc}).  If this latter class is not distinguished,
  61      * the defining class should be passed for both arguments ({@code defc == refc}).
  62      * <h3>JVM Specification, 5.4.4 "Access Control"</h3>
  63      * A field or method R is accessible to a class or interface D if
  64      * and only if any of the following is true:
  65      * <ul>
  66      * <li>R is public.</li>
  67      * <li>R is protected and is declared in a class C, and D is either
  68      *     a subclass of C or C itself. Furthermore, if R is not static,
  69      *     then the symbolic reference to R must contain a symbolic
  70      *     reference to a class T, such that T is either a subclass of D,
  71      *     a superclass of D, or D itself.
  72      *     <p>During verification, it was also required that, even if T is
  73      *     a superclass of D, the target reference of a protected instance
  74      *     field access or method invocation must be an instance of D or a
  75      *     subclass of D (4.10.1.8).</p></li>
  76      * <li>R is either protected or has default access (that is, neither
  77      *     public nor protected nor private), and is declared by a class
  78      *     in the same run-time package as D.</li>
  79      * <li>R is private and is declared in D by a class or interface
  80      *     belonging to the same nest as D.</li>
  81      * </ul>
  82      * If a referenced field or method is not accessible, access checking
  83      * throws an IllegalAccessError. If an exception is thrown while
  84      * attempting to determine the nest host of a class or interface,
  85      * access checking fails for the same reason.
  86      *
  87      * @param refc the class used in the symbolic reference to the proposed member
  88      * @param defc the class in which the proposed member is actually defined
  89      * @param mods modifier flags for the proposed member
  90      * @param lookupClass the class for which the access check is being made
  91      * @return true iff the accessing class can access such a member
  92      */
  93     public static boolean isMemberAccessible(Class<?> refc,  // symbolic ref class
  94                                              Class<?> defc,  // actual def class
  95                                              int      mods,  // actual member mods
  96                                              Class<?> lookupClass,
  97                                              int      allowedModes) {
  98         if (allowedModes == 0)  return false;
  99         assert((allowedModes & PUBLIC) != 0 &&
 100                (allowedModes & ~(ALL_ACCESS_MODES|PACKAGE_ALLOWED|MODULE_ALLOWED|UNCONDITIONAL_ALLOWED)) == 0);
 101         // The symbolic reference class (refc) must always be fully verified.
 102         if (!isClassAccessible(refc, lookupClass, allowedModes)) {
 103             return false;
 104         }
 105         // Usually refc and defc are the same, but verify defc also in case they differ.
 106         if (defc == lookupClass  &&
 107             (allowedModes & PRIVATE) != 0)
 108             return true;        // easy check; all self-access is OK with a private lookup
 109 
 110         switch (mods & ALL_ACCESS_MODES) {
 111         case PUBLIC:
 112             return true;  // already checked above
 113         case PROTECTED:
 114             assert !defc.isInterface(); // protected members aren't allowed in interfaces
 115             if ((allowedModes & PROTECTED_OR_PACKAGE_ALLOWED) != 0 &&
 116                 isSamePackage(defc, lookupClass))
 117                 return true;
 118             if ((allowedModes & PROTECTED) == 0)
 119                 return false;
 120             // Protected members are accessible by subclasses, which does not include interfaces.
 121             // Interfaces are types, not classes. They should not have access to
 122             // protected members in j.l.Object, even though it is their superclass.
 123             if ((mods & STATIC) != 0 &&
 124                 !isRelatedClass(refc, lookupClass))
 125                 return false;
 126             if ((allowedModes & PROTECTED) != 0 &&
 127                 isSubClass(lookupClass, defc))
 128                 return true;
 129             return false;
 130         case PACKAGE_ONLY:  // That is, zero.  Unmarked member is package-only access.
 131             assert !defc.isInterface(); // package-private members aren't allowed in interfaces
 132             return ((allowedModes & PACKAGE_ALLOWED) != 0 &&
 133                     isSamePackage(defc, lookupClass));
 134         case PRIVATE:
 135             // Rules for privates follows access rules for nestmates.
 136             boolean canAccess = ((allowedModes & PRIVATE) != 0 &&
 137                                  Reflection.areNestMates(defc, lookupClass));
 138             // for private methods the selected method equals the
 139             // resolved method - so refc == defc
 140             assert (canAccess && refc == defc) || !canAccess;
 141             return canAccess;
 142         default:
 143             throw new IllegalArgumentException("bad modifiers: "+Modifier.toString(mods));
 144         }
 145     }
 146 
 147     static boolean isRelatedClass(Class<?> refc, Class<?> lookupClass) {
 148         return (refc == lookupClass ||
 149                 isSubClass(refc, lookupClass) ||
 150                 isSubClass(lookupClass, refc));
 151     }
 152 
 153     static boolean isSubClass(Class<?> lookupClass, Class<?> defc) {
 154         return defc.isAssignableFrom(lookupClass) &&
 155                !lookupClass.isInterface(); // interfaces are types, not classes.
 156     }
 157 
 158     static int getClassModifiers(Class<?> c) {
 159         // This would return the mask stored by javac for the source-level modifiers.
 160         //   return c.getModifiers();
 161         // But what we need for JVM access checks are the actual bits from the class header.
 162         // ...But arrays and primitives are synthesized with their own odd flags:
 163         if (c.isArray() || c.isPrimitive())
 164             return c.getModifiers();
 165         return Reflection.getClassAccessFlags(c);
 166     }
 167 
 168     /**
 169      * Evaluate the JVM linkage rules for access to the given class on behalf of caller.
 170      * <h3>JVM Specification, 5.4.4 "Access Control"</h3>
 171      * A class or interface C is accessible to a class or interface D
 172      * if and only if any of the following conditions are true:<ul>
 173      * <li>C is public and in the same module as D.
 174      * <li>D is in a module that reads the module containing C, C is public and in a
 175      * package that is exported to the module that contains D.
 176      * <li>C and D are members of the same runtime package.
 177      * </ul>
 178      * @param refc the symbolic reference class to which access is being checked (C)
 179      * @param lookupClass the class performing the lookup (D)
 180      */
 181     public static boolean isClassAccessible(Class<?> refc, Class<?> lookupClass,
 182                                             int allowedModes) {
 183         if (allowedModes == 0)  return false;
 184         assert((allowedModes & PUBLIC) != 0 &&
 185                (allowedModes & ~(ALL_ACCESS_MODES|PACKAGE_ALLOWED|MODULE_ALLOWED|UNCONDITIONAL_ALLOWED)) == 0);
 186         int mods = getClassModifiers(refc);
 187         if (isPublic(mods)) {
 188 
 189             Module lookupModule = lookupClass.getModule();
 190             Module refModule = refc.getModule();
 191 
 192             // early VM startup case, java.base not defined
 193             if (lookupModule == null) {
 194                 assert refModule == null;
 195                 return true;
 196             }
 197 
 198             // trivially allow
 199             if ((allowedModes & MODULE_ALLOWED) != 0 &&
 200                 (lookupModule == refModule))
 201                 return true;
 202 
 203             // check readability when UNCONDITIONAL not allowed
 204             if (((allowedModes & UNCONDITIONAL_ALLOWED) != 0)
 205                 || lookupModule.canRead(refModule)) {
 206 
 207                 // check that refc is in an exported package
 208                 if ((allowedModes & MODULE_ALLOWED) != 0) {
 209                     if (refModule.isExported(refc.getPackageName(), lookupModule))
 210                         return true;
 211                 } else {
 212                     // exported unconditionally
 213                     if (refModule.isExported(refc.getPackageName()))
 214                         return true;
 215                 }
 216 
 217                 // not exported but allow access during VM initialization
 218                 // because java.base does not have its exports setup
 219                 if (!jdk.internal.misc.VM.isModuleSystemInited())
 220                     return true;
 221             }
 222 
 223             // public class not accessible to lookupClass
 224             return false;
 225         }
 226         if ((allowedModes & PACKAGE_ALLOWED) != 0 &&
 227             isSamePackage(lookupClass, refc))
 228             return true;
 229         return false;
 230     }
 231 
 232     /**
 233      * Decide if the given method type, attributed to a member or symbolic
 234      * reference of a given reference class, is really visible to that class.
 235      * @param type the supposed type of a member or symbolic reference of refc
 236      * @param refc the class attempting to make the reference
 237      */
 238     public static boolean isTypeVisible(Class<?> type, Class<?> refc) {
 239         if (type == refc) {
 240             return true;  // easy check
 241         }
 242         while (type.isArray())  type = type.getComponentType();
 243         if (type.isPrimitive() || type == Object.class) {
 244             return true;
 245         }
 246         ClassLoader typeLoader = type.getClassLoader();
 247         ClassLoader refcLoader = refc.getClassLoader();
 248         if (typeLoader == refcLoader) {
 249             return true;
 250         }
 251         if (refcLoader == null && typeLoader != null) {
 252             return false;
 253         }
 254         if (typeLoader == null && type.getName().startsWith("java.")) {
 255             // Note:  The API for actually loading classes, ClassLoader.defineClass,
 256             // guarantees that classes with names beginning "java." cannot be aliased,
 257             // because class loaders cannot load them directly.
 258             return true;
 259         }
 260 
 261         // Do it the hard way:  Look up the type name from the refc loader.
 262         //
 263         // Force the refc loader to report and commit to a particular binding for this type name (type.getName()).
 264         //
 265         // In principle, this query might force the loader to load some unrelated class,
 266         // which would cause this query to fail (and the original caller to give up).
 267         // This would be wasted effort, but it is expected to be very rare, occurring
 268         // only when an attacker is attempting to create a type alias.
 269         // In the normal case, one class loader will simply delegate to the other,
 270         // and the same type will be visible through both, with no extra loading.
 271         //
 272         // It is important to go through Class.forName instead of ClassLoader.loadClass
 273         // because Class.forName goes through the JVM system dictionary, which records
 274         // the class lookup once for all. This means that even if a not-well-behaved class loader
 275         // would "change its mind" about the meaning of the name, the Class.forName request
 276         // will use the result cached in the JVM system dictionary. Note that the JVM system dictionary
 277         // will record the first successful result. Unsuccessful results are not stored.
 278         //
 279         // We use doPrivileged in order to allow an unprivileged caller to ask an arbitrary
 280         // class loader about the binding of the proposed name (type.getName()).
 281         // The looked up type ("res") is compared for equality against the proposed
 282         // type ("type") and then is discarded.  Thus, the worst that can happen to
 283         // the "child" class loader is that it is bothered to load and report a class
 284         // that differs from "type"; this happens once due to JVM system dictionary
 285         // memoization.  And the caller never gets to look at the alternate type binding
 286         // ("res"), whether it exists or not.
 287         final String name = type.getName();
 288         Class<?> res = java.security.AccessController.doPrivileged(
 289                 new java.security.PrivilegedAction<>() {
 290                     public Class<?> run() {
 291                         try {
 292                             return Class.forName(name, false, refcLoader);
 293                         } catch (ClassNotFoundException | LinkageError e) {
 294                             return null; // Assume the class is not found
 295                         }
 296                     }
 297             });
 298         return (type == res);
 299     }
 300 
 301     /**
 302      * Decide if the given method type, attributed to a member or symbolic
 303      * reference of a given reference class, is really visible to that class.
 304      * @param type the supposed type of a member or symbolic reference of refc
 305      * @param refc the class attempting to make the reference
 306      */
 307     public static boolean isTypeVisible(java.lang.invoke.MethodType type, Class<?> refc) {
 308         if (!isTypeVisible(type.returnType(), refc)) {
 309             return false;
 310         }
 311         for (int n = 0, max = type.parameterCount(); n < max; n++) {
 312             if (!isTypeVisible(type.parameterType(n), refc)) {
 313                 return false;
 314             }
 315         }
 316         return true;
 317     }
 318 
 319     /**
 320      * Tests if two classes are in the same module.
 321      * @param class1 a class
 322      * @param class2 another class
 323      * @return whether they are in the same module
 324      */
 325     public static boolean isSameModule(Class<?> class1, Class<?> class2) {
 326         return class1.getModule() == class2.getModule();
 327     }
 328 
 329     /**
 330      * Test if two classes have the same class loader and package qualifier.
 331      * @param class1 a class
 332      * @param class2 another class
 333      * @return whether they are in the same package
 334      */
 335     public static boolean isSamePackage(Class<?> class1, Class<?> class2) {
 336         assert(!class1.isArray() && !class2.isArray());
 337         if (class1 == class2)
 338             return true;
 339         if (class1.getClassLoader() != class2.getClassLoader())
 340             return false;
 341         return Objects.equals(class1.getPackageName(), class2.getPackageName());
 342     }
 343 
 344     /**
 345      * Test if two classes are defined as part of the same package member (top-level class).
 346      * If this is true, they can share private access with each other.
 347      * @param class1 a class
 348      * @param class2 another class
 349      * @return whether they are identical or nested together
 350      */
 351     public static boolean isSamePackageMember(Class<?> class1, Class<?> class2) {
 352         if (class1 == class2)
 353             return true;
 354         if (!isSamePackage(class1, class2))
 355             return false;
 356         if (getOutermostEnclosingClass(class1) != getOutermostEnclosingClass(class2))
 357             return false;
 358         return true;
 359     }
 360 
 361     private static Class<?> getOutermostEnclosingClass(Class<?> c) {
 362         Class<?> pkgmem = c;
 363         for (Class<?> enc = c; (enc = enc.getEnclosingClass()) != null; )
 364             pkgmem = enc;
 365         return pkgmem;
 366     }
 367 
 368     private static boolean loadersAreRelated(ClassLoader loader1, ClassLoader loader2,
 369                                              boolean loader1MustBeParent) {
 370         if (loader1 == loader2 || loader1 == null
 371                 || (loader2 == null && !loader1MustBeParent)) {
 372             return true;
 373         }
 374         for (ClassLoader scan2 = loader2;
 375                 scan2 != null; scan2 = scan2.getParent()) {
 376             if (scan2 == loader1)  return true;
 377         }
 378         if (loader1MustBeParent)  return false;
 379         // see if loader2 is a parent of loader1:
 380         for (ClassLoader scan1 = loader1;
 381                 scan1 != null; scan1 = scan1.getParent()) {
 382             if (scan1 == loader2)  return true;
 383         }
 384         return false;
 385     }
 386 
 387     /**
 388      * Is the class loader of parentClass identical to, or an ancestor of,
 389      * the class loader of childClass?
 390      * @param parentClass a class
 391      * @param childClass another class, which may be a descendent of the first class
 392      * @return whether parentClass precedes or equals childClass in class loader order
 393      */
 394     public static boolean classLoaderIsAncestor(Class<?> parentClass, Class<?> childClass) {
 395         return loadersAreRelated(parentClass.getClassLoader(), childClass.getClassLoader(), true);
 396     }
 397 }