public static File getClasspathForClass(Class<?> targetClass) { URI location; try { CodeSource codeSource = targetClass.getProtectionDomain().getCodeSource(); if (codeSource != null && codeSource.getLocation() != null) { location = codeSource.getLocation().toURI(); if (location.getScheme().equals("file")) { return new File(location); } } if (targetClass.getClassLoader() != null) { String resourceName = targetClass.getName().replace('.', '/') + ".class"; URL resource = targetClass.getClassLoader().getResource(resourceName); if (resource != null) { return getClasspathForResource(resource, resourceName); } } throw new GradleException(String.format("Cannot determine classpath for class %s.", targetClass.getName())); } catch (URISyntaxException e) { throw UncheckedException.throwAsUncheckedException(e); } }
private static ClassPath getJavacApiJarClasspath() { Reference<ClassPath> r = javacApiClasspath; ClassPath res = r.get(); if (res != null) { return res; } if (r == NONE) { return null; } CodeSource codeSource = Modifier.class.getProtectionDomain().getCodeSource(); URL javacApiJar = codeSource != null ? codeSource.getLocation() : null; if (javacApiJar != null) { Logger.getLogger(DeclarativeHintsParser.class.getName()).log(Level.FINE, "javacApiJar={0}", javacApiJar); File aj = FileUtil.archiveOrDirForURL(javacApiJar); if (aj != null) { res = ClassPathSupport.createClassPath(FileUtil.urlForArchiveOrDir(aj)); javacApiClasspath = new WeakReference<>(res); return res; } } javacApiClasspath = NONE; return null; }
/** * 得到类所在地址,可以是文件,也可以是jar包 * * @param cls * the cls * @return the code base */ public static String getCodeBase(Class<?> cls) { if (cls == null) return null; ProtectionDomain domain = cls.getProtectionDomain(); if (domain == null) return null; CodeSource source = domain.getCodeSource(); if (source == null) return null; URL location = source.getLocation(); if (location == null) return null; return location.getFile(); }
private StaticClass getInstanceAdapterClass(final ProtectionDomain protectionDomain) { CodeSource codeSource = protectionDomain.getCodeSource(); if(codeSource == null) { codeSource = MINIMAL_PERMISSION_DOMAIN.getCodeSource(); } StaticClass instanceAdapterClass = instanceAdapters.get(codeSource); if(instanceAdapterClass != null) { return instanceAdapterClass; } // Any "unknown source" code source will default to no permission domain. final ProtectionDomain effectiveDomain = codeSource.equals(MINIMAL_PERMISSION_DOMAIN.getCodeSource()) ? MINIMAL_PERMISSION_DOMAIN : protectionDomain; instanceAdapterClass = instanceAdapterGenerator.generateClass(commonLoader, effectiveDomain); final StaticClass existing = instanceAdapters.putIfAbsent(codeSource, instanceAdapterClass); return existing == null ? instanceAdapterClass : existing; }
private static AccessControlContext getContext(File[] dirs) throws IOException { PathPermissions perms = new PathPermissions(dirs); ProtectionDomain domain = new ProtectionDomain( new CodeSource(perms.getCodeBase(), (java.security.cert.Certificate[]) null), perms); AccessControlContext acc = new AccessControlContext(new ProtectionDomain[] { domain }); return acc; }
/** * Get the Permissions for a CodeSource. If this instance * of WebappClassLoaderBase is for a web application context, * add read FilePermission or JndiPermissions for the base * directory (if unpacked), * the context URL, and jar file resources. * * @param codeSource where the code was loaded from * @return PermissionCollection for CodeSource */ @Override protected PermissionCollection getPermissions(CodeSource codeSource) { String codeUrl = codeSource.getLocation().toString(); PermissionCollection pc; if ((pc = loaderPC.get(codeUrl)) == null) { pc = super.getPermissions(codeSource); if (pc != null) { Iterator<Permission> perms = permissionList.iterator(); while (perms.hasNext()) { Permission p = perms.next(); pc.add(p); } loaderPC.put(codeUrl,pc); } } return (pc); }
private void checkCerts(String name, CodeSource cs) { int i = name.lastIndexOf('.'); String pname = (i == -1) ? "" : name.substring(0, i); Certificate[] certs = null; if (cs != null) { certs = cs.getCertificates(); } Certificate[] pcerts = null; if (parallelLockMap == null) { synchronized (this) { pcerts = package2certs.get(pname); if (pcerts == null) { package2certs.put(pname, (certs == null? nocerts:certs)); } } } else { pcerts = ((ConcurrentHashMap<String, Certificate[]>)package2certs). putIfAbsent(pname, (certs == null? nocerts:certs)); } if (pcerts != null && !compareCerts(pcerts, certs)) { throw new SecurityException("class \""+ name + "\"'s signer information does not match signer information of other classes in the same package"); } }
@Override public boolean check(Permission permission) { if (!Globals.IS_SECURITY_ENABLED) { return true; } Policy currentPolicy = Policy.getPolicy(); if (currentPolicy != null) { ResourceEntry entry = findResourceInternal("/", "/", false); if (entry != null) { CodeSource cs = new CodeSource(entry.codeBase, (java.security.cert.Certificate[]) null); PermissionCollection pc = currentPolicy.getPermissions(cs); if (pc.implies(permission)) { return true; } } } return false; }
/** * Get the Permissions for a CodeSource. If this instance of * WebappClassLoaderBase is for a web application context, add read * FilePermission or JndiPermissions for the base directory (if unpacked), * the context URL, and jar file resources. * * @param codeSource * where the code was loaded from * @return PermissionCollection for CodeSource */ @Override protected PermissionCollection getPermissions(CodeSource codeSource) { String codeUrl = codeSource.getLocation().toString(); PermissionCollection pc; if ((pc = loaderPC.get(codeUrl)) == null) { pc = super.getPermissions(codeSource); if (pc != null) { Iterator<Permission> perms = permissionList.iterator(); while (perms.hasNext()) { Permission p = perms.next(); pc.add(p); } loaderPC.put(codeUrl, pc); } } return (pc); }
/** * Get the Permissions for a CodeSource. If this instance * of WebappClassLoader is for a web application context, * add read FilePermission or JndiPermissions for the base * directory (if unpacked), * the context URL, and jar file resources. * * @param codeSource where the code was loaded from * @return PermissionCollection for CodeSource */ protected PermissionCollection getPermissions(CodeSource codeSource) { String codeUrl = codeSource.getLocation().toString(); PermissionCollection pc; if ((pc = (PermissionCollection)loaderPC.get(codeUrl)) == null) { pc = super.getPermissions(codeSource); if (pc != null) { Iterator perms = permissionList.iterator(); while (perms.hasNext()) { Permission p = (Permission)perms.next(); pc.add(p); } loaderPC.put(codeUrl,pc); } } return (pc); }
public static String getApplicationDirectory() { String jarDir = null; try { CodeSource codeSource = MiscUtils.class.getProtectionDomain().getCodeSource(); File jarFile = new File(URLDecoder.decode(codeSource.getLocation().toURI().getPath(), "UTF-8")); jarDir = jarFile.getParentFile().getPath(); } catch (URISyntaxException | UnsupportedEncodingException ex) { ex.printStackTrace(); } return jarDir + "/"; }
public static URL getBaseLocatoin(Class clazz) { if (clazz == null) { return null; } CodeSource codeSource = clazz.getProtectionDomain().getCodeSource(); if (codeSource != null) { URL locationURL = codeSource.getLocation(); String location = locationURL.toString(); int i = location.indexOf("!/"); if (i == -1) { return locationURL; } else { try { return new URL(location.substring(0, i)); } catch (MalformedURLException e) { throw new RuntimeException(e); } } } else { return null; } }
/** * create a context that can read any directories (recursively) * mentioned in the class path. In the case of a jar, it has to * be the directory containing the jar, not just the jar, as jar * files might refer to other jar files. */ private static AccessControlContext getContext(File[] cp) throws java.net.MalformedURLException { PathPermissions perms = new PathPermissions(cp); ProtectionDomain domain = new ProtectionDomain(new CodeSource(perms.getCodeBase(), (java.security.cert.Certificate[]) null), perms); AccessControlContext acc = new AccessControlContext(new ProtectionDomain[] { domain }); return acc; }
/** * Get the code source file or class path of the Class passed in. * * @param clazz * Class to find. * @return Jar file name or class path. */ public static String getCodeSource(Class<?> clazz) { ProtectionDomain protectionDomain = clazz.getProtectionDomain(); if (protectionDomain == null || protectionDomain.getCodeSource() == null) { return null; } CodeSource codeSource = clazz.getProtectionDomain().getCodeSource(); URL location = codeSource.getLocation(); if (location == null) { return null; } String path = codeSource.getLocation().toExternalForm(); if (path.endsWith(".jar") && path.contains("/")) { return path.substring(path.lastIndexOf('/') + 1); } return path; }
CodeSource[] getCodeSources(URL url) { ensureInitialization(); if (jv != null) { return jv.getCodeSources(this, url); } /* * JAR file has no signed content. Is there a non-signing * code source? */ Enumeration<String> unsigned = unsignedEntryNames(); if (unsigned.hasMoreElements()) { return new CodeSource[]{JarVerifier.getUnsignedCS(url)}; } else { return null; } }
@Test public void getPluginPermissions() throws Exception { CodeSource cs = mock(CodeSource.class); ProtectionDomain domain = new ProtectionDomain(cs, null, new PluginClassLoader(new URL[0]), null); SandboxSecurityPolicy policy = new SandboxSecurityPolicy(); PermissionCollection permissions = policy.getPermissions(domain); Assert.assertFalse(permissions.elements().hasMoreElements()); }
protected AppletClassLoader(URL base) { super(new URL[0]); this.base = base; this.codesource = new CodeSource(base, (java.security.cert.Certificate[]) null); acc = AccessController.getContext(); }
@Override public PermissionCollection getPermissions(final Subject subject, final CodeSource codesource) { // 1) if code instantiates PolicyFile directly, then it will need // all the permissions required for the PolicyFile initialization // 2) if code calls Policy.getPolicy, then it simply needs // AuthPermission(getPolicy), and the javax.security.auth.Policy // implementation instantiates PolicyFile in a doPrivileged block // 3) if after instantiating a Policy (either via #1 or #2), // code calls getPermissions, PolicyFile wraps the call // in a doPrivileged block. return AccessController.doPrivileged (new PrivilegedAction<PermissionCollection>() { @Override public PermissionCollection run() { SubjectCodeSource scs = new SubjectCodeSource( subject, null, codesource == null ? null : codesource.getLocation(), codesource == null ? null : codesource.getCertificates()); if (initialized) { return getPermissions(new Permissions(), scs); } else { return new PolicyPermissions(AuthPolicyFile.this, scs); } } }); }
private String defineClassSourceLocation(ProtectionDomain pd) { CodeSource cs = pd.getCodeSource(); String source = null; if (cs != null && cs.getLocation() != null) { source = cs.getLocation().toString(); } return source; }
/** @return a protocol through which was the class loaded (file://...) or null */ static URL getClassURL(Class clazz) { java.security.CodeSource cs = clazz.getProtectionDomain().getCodeSource(); if (cs != null) { URL url = cs.getLocation(); return url; } else { // PROXY CLASS? return null; } }
private Class<?> defineClass(String name, URL url) throws IOException { byte[] b = getBytes(url); CodeSource cs = new CodeSource(null, (java.security.cert.Certificate[])null); if (!name.equals(TRAMPOLINE)) { throw new IOException("MethodUtil: bad name " + name); } return defineClass(name, b, 0, b.length, cs); }
Enumeration<String> entryNames(CodeSource[] cs) { ensureInitialization(); if (jv != null) { return jv.entryNames(this, cs); } /* * JAR file has no signed content. Is there a non-signing * code source? */ boolean includeUnsigned = false; for (int i = 0; i < cs.length; i++) { if (cs[i].getCodeSigners() == null) { includeUnsigned = true; break; } } if (includeUnsigned) { return unsignedEntryNames(); } else { return new Enumeration<String>() { public boolean hasMoreElements() { return false; } public String nextElement() { throw new NoSuchElementException(); } }; } }
/** * * @param className * @param clsByte * @return */ public Class<?> findClass(String className, byte[] clsByte, URL url) { Class<?> cls = null; try { CodeSource cs = new CodeSource(url, (java.security.cert.Certificate[]) null); ProtectionDomain pd = new ProtectionDomain(cs, null, this, null); cls = super.defineClass(className, clsByte, 0, clsByte.length, pd); resolveClass(cls); classCache.put(className, cls); } catch (Exception ex) { logger.error("define class error", ex); } return cls; }
/** * Log that a class has been loaded, and where from. * @param name classname * @param clazz class */ private void loadedClass(String name, Class clazz) { out("Loaded %s as %s", name, clazz); CodeSource source = clazz.getProtectionDomain().getCodeSource(); URL url = source.getLocation(); out("%s: %s", name, url); }
private static Path findAgentJar() { CodeSource cs = Promagent.class.getProtectionDomain().getCodeSource(); if (cs != null) { return findAgentJarFromCodeSource(cs); } else { // This happens if the Promagent class is loaded from the bootstrap class loader, // i.e. in addition to the command line argument -javaagent:/path/to/promagent.jar, // the argument -Xbootclasspath/p:/path/to/promagent.jar is used. return findAgentJarFromCmdline(ManagementFactory.getRuntimeMXBean().getInputArguments()); } }
private Class<?> defineClass(String name, byte[] b) throws IOException { CodeSource cs = new CodeSource(null, (java.security.cert.Certificate[])null); if (!name.equals(TRAMPOLINE)) { throw new IOException("MethodUtil: bad name " + name); } return defineClass(name, b, 0, b.length, cs); }
/** * Generates an AccessControlContext with minimal permissions. * The approach used here is taken from the similar method * getAccessControlContext() in the sun.applet.AppletPanel class. */ private static AccessControlContext getAccessControlContext(int port) { // begin with permissions granted to all code in current policy PermissionCollection perms = AccessController.doPrivileged( new java.security.PrivilegedAction<PermissionCollection>() { public PermissionCollection run() { CodeSource codesource = new CodeSource(null, (java.security.cert.Certificate[]) null); Policy p = java.security.Policy.getPolicy(); if (p != null) { return p.getPermissions(codesource); } else { return new Permissions(); } } }); /* * Anyone can connect to the registry and the registry can connect * to and possibly download stubs from anywhere. Downloaded stubs and * related classes themselves are more tightly limited by RMI. */ perms.add(new SocketPermission("*", "connect,accept")); perms.add(new SocketPermission("localhost:"+port, "listen,accept")); perms.add(new RuntimePermission("accessClassInPackage.sun.jvmstat.*")); perms.add(new RuntimePermission("accessClassInPackage.sun.jvm.hotspot.*")); perms.add(new FilePermission("<<ALL FILES>>", "read")); /* * Create an AccessControlContext that consists of a single * protection domain with only the permissions calculated above. */ ProtectionDomain pd = new ProtectionDomain( new CodeSource(null, (java.security.cert.Certificate[]) null), perms); return new AccessControlContext(new ProtectionDomain[] { pd }); }
private static ArrayList<Permission> getPermissions(MySecureClassLoader scl, Policy p, String url, String className, String classBytes, Certificate[] chain) throws IOException { CodeSource cs = new CodeSource(new URL(url), chain); Base64.Decoder bd = Base64.getDecoder(); byte[] bytes = bd.decode(classBytes); Class<?> c = scl.defineMyClass(className, bytes, cs); ProtectionDomain pd = c.getProtectionDomain(); return Collections.list(p.getPermissions(pd).elements()); }
public static String getCodeBase(Class<?> cls) { if (cls == null) return null; ProtectionDomain domain = cls.getProtectionDomain(); if (domain == null) return null; CodeSource source = domain.getCodeSource(); if (source == null) return null; URL location = source.getLocation(); if (location == null) return null; return location.getFile(); }
private static void testImplies(URL thisURL, URL thatURL, boolean result) throws SecurityException { CodeSource thisCs = new CodeSource(thisURL, (java.security.cert.Certificate[]) null); CodeSource thatCs = new CodeSource(thatURL, (java.security.cert.Certificate[]) null); if (thisCs.implies(thatCs) != result) { throw new SecurityException("test failed"); } }
@Test public void getApplicationPermissions() throws Exception { CodeSource cs = mock(CodeSource.class); ProtectionDomain domain = new ProtectionDomain(cs, null, new URLClassLoader(new URL[0]), null); SandboxSecurityPolicy policy = new SandboxSecurityPolicy(); PermissionCollection permissions = policy.getPermissions(domain); Assert.assertTrue(permissions.elements().hasMoreElements()); }
public static void main(String[] args) throws Exception { /* * If we delay setting the security manager until after the service * configuration file has been installed, then this test still * functions properly, but the -Djava.security.debug output is * lacking, so to ease debugging, we'll set it early-- at the cost * of having to specify the policy even when running standalone. */ TestLibrary.suggestSecurityManager(null); ServiceConfiguration.installServiceConfigurationFile(); /* * Execute use of RMIClassLoader within an AccessControlContext * that has a protection domain with no permissions, to make sure * that RMIClassLoader can still properly initialize itself. */ CodeSource codesource = new CodeSource(null, (Certificate[]) null); Permissions perms = null; ProtectionDomain pd = new ProtectionDomain(codesource, perms); AccessControlContext acc = new AccessControlContext(new ProtectionDomain[] { pd }); java.security.AccessController.doPrivileged( new java.security.PrivilegedExceptionAction() { public Object run() throws Exception { TestProvider.exerciseTestProvider( TestProvider2.loadClassReturn, TestProvider2.loadProxyClassReturn, TestProvider2.getClassLoaderReturn, TestProvider2.getClassAnnotationReturn, TestProvider2.invocations); return null; } }, acc); }
@Override protected PermissionCollection getPermissions(final CodeSource codesource) { final Permissions permCollection = new Permissions(); for (final Permission perm : SCRIPT_PERMISSIONS) { permCollection.add(perm); } return permCollection; }
/** * allow any classes loaded from classpath to exit the VM. */ protected PermissionCollection getPermissions(CodeSource codesource) { PermissionCollection perms = super.getPermissions(codesource); perms.add(new RuntimePermission("exitVM")); return perms; }