1 /* 2 * Copyright (c) 2008, 2021, 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 jdk.internal.reflect.Reflection; 31 32 /** 33 * This class centralizes information about the JVM's linkage access control. 34 * @author jrose 35 */ 36 public class VerifyAccess { 37 38 private VerifyAccess() { } // cannot instantiate 39 40 private static final int UNCONDITIONAL_ALLOWED = java.lang.invoke.MethodHandles.Lookup.UNCONDITIONAL; 41 private static final int ORIGINAL_ALLOWED = java.lang.invoke.MethodHandles.Lookup.ORIGINAL; 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 * @param prevLookupClass the class for which the access check is being made 92 * @param allowedModes allowed modes 93 * @return true iff the accessing class can access such a member 94 */ 95 public static boolean isMemberAccessible(Class<?> refc, // symbolic ref class 96 Class<?> defc, // actual def class 97 int mods, // actual member mods 98 Class<?> lookupClass, 99 Class<?> prevLookupClass, 100 int allowedModes) { 101 if (allowedModes == 0) return false; 102 assert((allowedModes & ~(ALL_ACCESS_MODES|PACKAGE_ALLOWED|MODULE_ALLOWED|UNCONDITIONAL_ALLOWED|ORIGINAL_ALLOWED)) == 0); 103 // The symbolic reference class (refc) must always be fully verified. 104 if (!isClassAccessible(refc, lookupClass, prevLookupClass, allowedModes)) { 105 return false; 106 } 107 // Usually refc and defc are the same, but verify defc also in case they differ. 108 if (defc == lookupClass && 109 (allowedModes & PRIVATE) != 0) 110 return true; // easy check; all self-access is OK with a private lookup 111 112 switch (mods & ALL_ACCESS_MODES) { 113 case PUBLIC: 114 assert (allowedModes & PUBLIC) != 0 || (allowedModes & UNCONDITIONAL_ALLOWED) != 0; 115 return true; // already checked above 116 case PROTECTED: 117 assert !defc.isInterface(); // protected members aren't allowed in interfaces 118 if ((allowedModes & PROTECTED_OR_PACKAGE_ALLOWED) != 0 && 119 isSamePackage(defc, lookupClass)) 120 return true; 121 if ((allowedModes & PROTECTED) == 0) 122 return false; 123 // Protected members are accessible by subclasses, which does not include interfaces. 124 // Interfaces are types, not classes. They should not have access to 125 // protected members in j.l.Object, even though it is their superclass. 126 if ((mods & STATIC) != 0 && 127 !isRelatedClass(refc, lookupClass)) 128 return false; 129 if ((allowedModes & PROTECTED) != 0 && 130 isSubClass(lookupClass, defc)) 131 return true; 132 return false; 133 case PACKAGE_ONLY: // That is, zero. Unmarked member is package-only access. 134 assert !defc.isInterface(); // package-private members aren't allowed in interfaces 135 return ((allowedModes & PACKAGE_ALLOWED) != 0 && 136 isSamePackage(defc, lookupClass)); 137 case PRIVATE: 138 // Rules for privates follows access rules for nestmates. 139 boolean canAccess = ((allowedModes & PRIVATE) != 0 && 140 Reflection.areNestMates(defc, lookupClass)); 141 // for private methods the selected method equals the 142 // resolved method - so refc == defc 143 assert (canAccess && refc == defc) || !canAccess; 144 return canAccess; 145 default: 146 throw new IllegalArgumentException("bad modifiers: "+Modifier.toString(mods)); 147 } 148 } 149 150 static boolean isRelatedClass(Class<?> refc, Class<?> lookupClass) { 151 return (refc == lookupClass || 152 isSubClass(refc, lookupClass) || 153 isSubClass(lookupClass, refc)); 154 } 155 156 static boolean isSubClass(Class<?> lookupClass, Class<?> defc) { 157 return defc.isAssignableFrom(lookupClass) && 158 !lookupClass.isInterface(); // interfaces are types, not classes. 159 } 160 161 static int getClassModifiers(Class<?> c) { 162 // This would return the mask stored by javac for the source-level modifiers. 163 // return c.getModifiers(); 164 // But what we need for JVM access checks are the actual bits from the class header. 165 // ...But arrays and primitives are synthesized with their own odd flags: 166 if (c.isArray() || c.isPrimitive()) 167 return c.getModifiers(); 168 return Reflection.getClassAccessFlags(c); 169 } 170 171 /** 172 * Evaluate the JVM linkage rules for access to the given class on behalf of caller. 173 * <h3>JVM Specification, 5.4.4 "Access Control"</h3> 174 * A class or interface C is accessible to a class or interface D 175 * if and only if any of the following conditions are true:<ul> 176 * <li>C is public and in the same module as D. 177 * <li>D is in a module that reads the module containing C, C is public and in a 178 * package that is exported to the module that contains D. 179 * <li>C and D are members of the same runtime package. 180 * </ul> 181 * 182 * @param refc the symbolic reference class to which access is being checked (C) 183 * @param lookupClass the class performing the lookup (D) 184 * @param prevLookupClass the class from which the lookup was teleported or null 185 * @param allowedModes allowed modes 186 */ 187 public static boolean isClassAccessible(Class<?> refc, 188 Class<?> lookupClass, 189 Class<?> prevLookupClass, 190 int allowedModes) { 191 if (allowedModes == 0) return false; 192 assert((allowedModes & ~(ALL_ACCESS_MODES|PACKAGE_ALLOWED|MODULE_ALLOWED|UNCONDITIONAL_ALLOWED|ORIGINAL_ALLOWED)) == 0); 193 194 if ((allowedModes & PACKAGE_ALLOWED) != 0 && 195 isSamePackage(lookupClass, refc)) 196 return true; 197 198 int mods = getClassModifiers(refc); 199 if (isPublic(mods)) { 200 201 Module lookupModule = lookupClass.getModule(); 202 Module refModule = refc.getModule(); 203 204 // early VM startup case, java.base not defined or 205 // module system is not fully initialized and exports are not set up 206 if (lookupModule == null || !jdk.internal.misc.VM.isModuleSystemInited()) { 207 assert lookupModule == refModule; 208 return true; 209 } 210 211 // allow access to public types in all unconditionally exported packages 212 if ((allowedModes & UNCONDITIONAL_ALLOWED) != 0) { 213 return refModule.isExported(refc.getPackageName()); 214 } 215 216 if (lookupModule == refModule && prevLookupClass == null) { 217 // allow access to all public types in lookupModule 218 if ((allowedModes & MODULE_ALLOWED) != 0) 219 return true; 220 221 assert (allowedModes & PUBLIC) != 0; 222 return refModule.isExported(refc.getPackageName()); 223 } 224 225 // cross-module access 226 // 1. refc is in different module from lookupModule, or 227 // 2. refc is in lookupModule and a different module from prevLookupModule 228 Module prevLookupModule = prevLookupClass != null ? prevLookupClass.getModule() 229 : null; 230 assert refModule != lookupModule || refModule != prevLookupModule; 231 232 if (isModuleAccessible(refc, lookupModule, prevLookupModule)) 233 return true; 234 235 // public class not accessible to lookupClass 236 return false; 237 } 238 239 return false; 240 } 241 242 /* 243 * Tests if a class or interface REFC is accessible to m1 and m2 where m2 244 * may be null. 245 * 246 * A class or interface REFC in m is accessible to m1 and m2 if and only if 247 * both m1 and m2 read m and m exports the package of REFC at least to 248 * both m1 and m2. 249 */ 250 public static boolean isModuleAccessible(Class<?> refc, Module m1, Module m2) { 251 Module refModule = refc.getModule(); 252 assert refModule != m1 || refModule != m2; 253 int mods = getClassModifiers(refc); 254 if (isPublic(mods)) { 255 if (m1.canRead(refModule) && (m2 == null || m2.canRead(refModule))) { 256 String pn = refc.getPackageName(); 257 258 // refc is exported package to at least both m1 and m2 259 if (refModule.isExported(pn, m1) && (m2 == null || refModule.isExported(pn, m2))) 260 return true; 261 } 262 } 263 return false; 264 } 265 266 /** 267 * Decide if the given method type, attributed to a member or symbolic 268 * reference of a given reference class, is really visible to that class. 269 * @param type the supposed type of a member or symbolic reference of refc 270 * @param refc the class attempting to make the reference 271 */ 272 public static boolean ensureTypeVisible(Class<?> type, Class<?> refc) { 273 if (type == refc) { 274 return true; // easy check 275 } 276 while (type.isArray()) type = type.getComponentType(); 277 if (type.isPrimitive() || type == Object.class) { 278 return true; 279 } 280 ClassLoader typeLoader = type.getClassLoader(); 281 ClassLoader refcLoader = refc.getClassLoader(); 282 if (typeLoader == refcLoader) { 283 return true; 284 } 285 if (refcLoader == null && typeLoader != null) { 286 return false; 287 } 288 289 // The API for actually loading classes, ClassLoader.defineClass, 290 // guarantees that classes with names beginning "java." cannot be aliased, 291 // because class loaders cannot load them directly. However, it is beneficial 292 // for JIT-compilers to ensure all signature classes are loaded. 293 // JVM doesn't install any loader contraints when performing MemberName resolution, 294 // so eagerly resolving signature classes is a way to match what JVM achieves 295 // with loader constraints during method resolution for invoke bytecodes. 296 297 // Do it the hard way: Look up the type name from the refc loader. 298 // 299 // Force the refc loader to report and commit to a particular binding for this type name (type.getName()). 300 // 301 // In principle, this query might force the loader to load some unrelated class, 302 // which would cause this query to fail (and the original caller to give up). 303 // This would be wasted effort, but it is expected to be very rare, occurring 304 // only when an attacker is attempting to create a type alias. 305 // In the normal case, one class loader will simply delegate to the other, 306 // and the same type will be visible through both, with no extra loading. 307 // 308 // It is important to go through Class.forName instead of ClassLoader.loadClass 309 // because Class.forName goes through the JVM system dictionary, which records 310 // the class lookup once for all. This means that even if a not-well-behaved class loader 311 // would "change its mind" about the meaning of the name, the Class.forName request 312 // will use the result cached in the JVM system dictionary. Note that the JVM system dictionary 313 // will record the first successful result. Unsuccessful results are not stored. 314 // 315 // We use doPrivileged in order to allow an unprivileged caller to ask an arbitrary 316 // class loader about the binding of the proposed name (type.getName()). 317 // The looked up type ("res") is compared for equality against the proposed 318 // type ("type") and then is discarded. Thus, the worst that can happen to 319 // the "child" class loader is that it is bothered to load and report a class 320 // that differs from "type"; this happens once due to JVM system dictionary 321 // memoization. And the caller never gets to look at the alternate type binding 322 // ("res"), whether it exists or not. 323 final String name = type.getName(); 324 @SuppressWarnings("removal") 325 Class<?> res = java.security.AccessController.doPrivileged( 326 new java.security.PrivilegedAction<>() { 327 public Class<?> run() { 328 try { 329 return Class.forName(name, false, refcLoader); 330 } catch (ClassNotFoundException | LinkageError e) { 331 return null; // Assume the class is not found 332 } 333 } 334 }); 335 return (type == res); 336 } 337 338 /** 339 * Decide if the given method type, attributed to a member or symbolic 340 * reference of a given reference class, is really visible to that class. 341 * @param type the supposed type of a member or symbolic reference of refc 342 * @param refc the class attempting to make the reference 343 */ 344 public static boolean ensureTypeVisible(java.lang.invoke.MethodType type, Class<?> refc) { 345 if (!ensureTypeVisible(type.returnType(), refc)) { 346 return false; 347 } 348 for (int n = 0, max = type.parameterCount(); n < max; n++) { 349 if (!ensureTypeVisible(type.parameterType(n), refc)) { 350 return false; 351 } 352 } 353 return true; 354 } 355 356 /** 357 * Tests if two classes are in the same module. 358 * @param class1 a class 359 * @param class2 another class 360 * @return whether they are in the same module 361 */ 362 public static boolean isSameModule(Class<?> class1, Class<?> class2) { 363 return class1.getModule() == class2.getModule(); 364 } 365 366 /** 367 * Test if two classes have the same class loader and package qualifier. 368 * @param class1 a class 369 * @param class2 another class 370 * @return whether they are in the same package 371 */ 372 public static boolean isSamePackage(Class<?> class1, Class<?> class2) { 373 if (class1 == class2) 374 return true; 375 if (class1.getClassLoader() != class2.getClassLoader()) 376 return false; 377 return class1.getPackageName() == class2.getPackageName(); 378 } 379 380 /** 381 * Test if two classes are defined as part of the same package member (top-level class). 382 * If this is true, they can share private access with each other. 383 * @param class1 a class 384 * @param class2 another class 385 * @return whether they are identical or nested together 386 */ 387 public static boolean isSamePackageMember(Class<?> class1, Class<?> class2) { 388 if (class1 == class2) 389 return true; 390 if (!isSamePackage(class1, class2)) 391 return false; 392 if (getOutermostEnclosingClass(class1) != getOutermostEnclosingClass(class2)) 393 return false; 394 return true; 395 } 396 397 private static Class<?> getOutermostEnclosingClass(Class<?> c) { 398 Class<?> pkgmem = c; 399 for (Class<?> enc = c; (enc = enc.getEnclosingClass()) != null; ) 400 pkgmem = enc; 401 return pkgmem; 402 } 403 404 private static boolean loadersAreRelated(ClassLoader loader1, ClassLoader loader2, 405 boolean loader1MustBeParent) { 406 if (loader1 == loader2 || loader1 == null 407 || (loader2 == null && !loader1MustBeParent)) { 408 return true; 409 } 410 for (ClassLoader scan2 = loader2; 411 scan2 != null; scan2 = scan2.getParent()) { 412 if (scan2 == loader1) return true; 413 } 414 if (loader1MustBeParent) return false; 415 // see if loader2 is a parent of loader1: 416 for (ClassLoader scan1 = loader1; 417 scan1 != null; scan1 = scan1.getParent()) { 418 if (scan1 == loader2) return true; 419 } 420 return false; 421 } 422 423 /** 424 * Is the class loader of parentClass identical to, or an ancestor of, 425 * the class loader of childClass? 426 * @param parentClass a class 427 * @param childClass another class, which may be a descendent of the first class 428 * @return whether parentClass precedes or equals childClass in class loader order 429 */ 430 public static boolean classLoaderIsAncestor(Class<?> parentClass, Class<?> childClass) { 431 return loadersAreRelated(parentClass.getClassLoader(), childClass.getClassLoader(), true); 432 } 433 }