1 /* 2 * Copyright (c) 2008, 2013, 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 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)) == 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)) == 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 195 if (lookupModule.canRead(refModule)) { 196 197 // check that refc is in an exported package 198 Class<?> c = refc; 199 while (c.isArray()) { 200 c = c.getComponentType(); 201 } 202 if (c.isPrimitive()) 203 return true; 204 if ((allowedModes & MODULE_ALLOWED) != 0) { 205 if (refModule.isExported(c.getPackageName(), lookupModule)) 206 return true; 207 } else { 208 // exported unconditionally 209 if (refModule.isExported(c.getPackageName())) 210 return true; 211 } 212 213 // not exported but allow access during VM initialization 214 // because java.base does not have its exports setup 215 if (!jdk.internal.misc.VM.isModuleSystemInited()) 216 return true; 217 } 218 219 // public class not accessible to lookupClass 220 return false; 221 } 222 if ((allowedModes & PACKAGE_ALLOWED) != 0 && 223 isSamePackage(lookupClass, refc)) 224 return true; 225 return false; 226 } 227 228 /** 229 * Decide if the given method type, attributed to a member or symbolic 230 * reference of a given reference class, is really visible to that class. 231 * @param type the supposed type of a member or symbolic reference of refc 232 * @param refc the class attempting to make the reference 233 */ 234 public static boolean isTypeVisible(Class<?> type, Class<?> refc) { 235 if (type == refc) { 236 return true; // easy check 237 } 238 while (type.isArray()) type = type.getComponentType(); 239 if (type.isPrimitive() || type == Object.class) { 240 return true; 241 } 242 ClassLoader typeLoader = type.getClassLoader(); 243 ClassLoader refcLoader = refc.getClassLoader(); 244 if (typeLoader == refcLoader) { 245 return true; 246 } 247 if (refcLoader == null && typeLoader != null) { 248 return false; 249 } 250 if (typeLoader == null && type.getName().startsWith("java.")) { 251 // Note: The API for actually loading classes, ClassLoader.defineClass, 252 // guarantees that classes with names beginning "java." cannot be aliased, 253 // because class loaders cannot load them directly. 254 return true; 255 } 256 257 // Do it the hard way: Look up the type name from the refc loader. 258 // 259 // Force the refc loader to report and commit to a particular binding for this type name (type.getName()). 260 // 261 // In principle, this query might force the loader to load some unrelated class, 262 // which would cause this query to fail (and the original caller to give up). 263 // This would be wasted effort, but it is expected to be very rare, occurring 264 // only when an attacker is attempting to create a type alias. 265 // In the normal case, one class loader will simply delegate to the other, 266 // and the same type will be visible through both, with no extra loading. 267 // 268 // It is important to go through Class.forName instead of ClassLoader.loadClass 269 // because Class.forName goes through the JVM system dictionary, which records 270 // the class lookup once for all. This means that even if a not-well-behaved class loader 271 // would "change its mind" about the meaning of the name, the Class.forName request 272 // will use the result cached in the JVM system dictionary. Note that the JVM system dictionary 273 // will record the first successful result. Unsuccessful results are not stored. 274 // 275 // We use doPrivileged in order to allow an unprivileged caller to ask an arbitrary 276 // class loader about the binding of the proposed name (type.getName()). 277 // The looked up type ("res") is compared for equality against the proposed 278 // type ("type") and then is discarded. Thus, the worst that can happen to 279 // the "child" class loader is that it is bothered to load and report a class 280 // that differs from "type"; this happens once due to JVM system dictionary 281 // memoization. And the caller never gets to look at the alternate type binding 282 // ("res"), whether it exists or not. 283 final String name = type.getName(); 284 Class<?> res = java.security.AccessController.doPrivileged( 285 new java.security.PrivilegedAction<>() { 286 public Class<?> run() { 287 try { 288 return Class.forName(name, false, refcLoader); 289 } catch (ClassNotFoundException | LinkageError e) { 290 return null; // Assume the class is not found 291 } 292 } 293 }); 294 return (type == res); 295 } 296 297 /** 298 * Decide if the given method type, attributed to a member or symbolic 299 * reference of a given reference class, is really visible to that class. 300 * @param type the supposed type of a member or symbolic reference of refc 301 * @param refc the class attempting to make the reference 302 */ 303 public static boolean isTypeVisible(java.lang.invoke.MethodType type, Class<?> refc) { 304 for (int n = -1, max = type.parameterCount(); n < max; n++) { 305 Class<?> ptype = (n < 0 ? type.returnType() : type.parameterType(n)); 306 if (!isTypeVisible(ptype, refc)) 307 return false; 308 } 309 return true; 310 } 311 312 /** 313 * Tests if two classes are in the same module. 314 * @param class1 a class 315 * @param class2 another class 316 * @return whether they are in the same module 317 */ 318 public static boolean isSameModule(Class<?> class1, Class<?> class2) { 319 return class1.getModule() == class2.getModule(); 320 } 321 322 /** 323 * Test if two classes have the same class loader and package qualifier. 324 * @param class1 a class 325 * @param class2 another class 326 * @return whether they are in the same package 327 */ 328 public static boolean isSamePackage(Class<?> class1, Class<?> class2) { 329 assert(!class1.isArray() && !class2.isArray()); 330 if (class1 == class2) 331 return true; 332 if (class1.getClassLoader() != class2.getClassLoader()) 333 return false; 334 return Objects.equals(class1.getPackageName(), class2.getPackageName()); 335 } 336 337 /** Return the package name for this class. 338 */ 339 public static String getPackageName(Class<?> cls) { 340 assert (!cls.isArray()); 341 String name = cls.getName(); 342 int dot = name.lastIndexOf('.'); 343 if (dot < 0) return ""; 344 return name.substring(0, dot); 345 } 346 347 /** 348 * Test if two classes are defined as part of the same package member (top-level class). 349 * If this is true, they can share private access with each other. 350 * @param class1 a class 351 * @param class2 another class 352 * @return whether they are identical or nested together 353 */ 354 public static boolean isSamePackageMember(Class<?> class1, Class<?> class2) { 355 if (class1 == class2) 356 return true; 357 if (!isSamePackage(class1, class2)) 358 return false; 359 if (getOutermostEnclosingClass(class1) != getOutermostEnclosingClass(class2)) 360 return false; 361 return true; 362 } 363 364 private static Class<?> getOutermostEnclosingClass(Class<?> c) { 365 Class<?> pkgmem = c; 366 for (Class<?> enc = c; (enc = enc.getEnclosingClass()) != null; ) 367 pkgmem = enc; 368 return pkgmem; 369 } 370 371 private static boolean loadersAreRelated(ClassLoader loader1, ClassLoader loader2, 372 boolean loader1MustBeParent) { 373 if (loader1 == loader2 || loader1 == null 374 || (loader2 == null && !loader1MustBeParent)) { 375 return true; 376 } 377 for (ClassLoader scan2 = loader2; 378 scan2 != null; scan2 = scan2.getParent()) { 379 if (scan2 == loader1) return true; 380 } 381 if (loader1MustBeParent) return false; 382 // see if loader2 is a parent of loader1: 383 for (ClassLoader scan1 = loader1; 384 scan1 != null; scan1 = scan1.getParent()) { 385 if (scan1 == loader2) return true; 386 } 387 return false; 388 } 389 390 /** 391 * Is the class loader of parentClass identical to, or an ancestor of, 392 * the class loader of childClass? 393 * @param parentClass a class 394 * @param childClass another class, which may be a descendent of the first class 395 * @return whether parentClass precedes or equals childClass in class loader order 396 */ 397 public static boolean classLoaderIsAncestor(Class<?> parentClass, Class<?> childClass) { 398 return loadersAreRelated(parentClass.getClassLoader(), childClass.getClassLoader(), true); 399 } 400 }