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