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