java.security.CodeSource Java Examples

The following examples show how to use java.security.CodeSource. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ClassLoader.java    From jdk8u-dev-jdk with GNU General Public License v2.0 7 votes vote down vote up
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");
    }
}
 
Example #2
Source File: SimpleLoader.java    From baratine with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Initializes the loader.
 */
@PostConstruct
@Override
public void init()
  throws ConfigException
{
  try {
    _codeSource = new CodeSource(new URL(_path.getURL()),
                                 (Certificate []) null);
  } catch (Exception e) {
    log.log(Level.FINE, e.toString(), e);
  }
  
  super.init();

  getClassLoader().addURL(_path, _isScanned);
}
 
Example #3
Source File: XsdGeneratorHelperTest.java    From jaxb2-maven-plugin with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setupSharedState()
{

    // Configure XMLUnit.
    XMLUnit.setIgnoreWhitespace( true );
    XMLUnit.setIgnoreAttributeOrder( true );

    // Configure the TransformerFactory
    try
    {

        factory = TransformerFactory.newInstance();
        final CodeSource codeSource = factory.getClass().getProtectionDomain().getCodeSource();

        System.out.println(
                "-- Found TransformerFactory of type [" + factory.getClass().getName() + "] loaded from [" + codeSource.getLocation().toString() + "]" );

    }
    catch ( Exception ex )
    {
        ex.printStackTrace();
    }
}
 
Example #4
Source File: Launcher.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #5
Source File: JarFile.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
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;
    }
}
 
Example #6
Source File: ReflectUtils.java    From brpc-java with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #7
Source File: Activation.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private static PermissionCollection getExecPermissions() {
    /*
     * The approach used here is taken from the similar method
     * getLoaderAccessControlContext() in the class
     * sun.rmi.server.LoaderHandler.
     */

    // obtain permissions granted to all code in current policy
    PermissionCollection perms = AccessController.doPrivileged(
        new PrivilegedAction<PermissionCollection>() {
            public PermissionCollection run() {
                CodeSource codesource =
                    new CodeSource(null, (Certificate[]) null);
                Policy p = Policy.getPolicy();
                if (p != null) {
                    return p.getPermissions(codesource);
                } else {
                    return new Permissions();
                }
            }
        });

    return perms;
}
 
Example #8
Source File: HeapHistogram.java    From javamelody with Apache License 2.0 6 votes vote down vote up
private static String findSource(Class<?> clazz) {
	final CodeSource codeSource = clazz.getProtectionDomain().getCodeSource();
	if (codeSource != null && codeSource.getLocation() != null) {
		String src = codeSource.getLocation().toString();
		if (src.startsWith("file:/")) {
			src = src.substring("file:/".length());
		} else if (src.startsWith("vfs:/")) {
			// "vfs:/" pour jboss 6.0
			src = src.substring("vfs:/".length());
		} else if (src.startsWith("reference:file:/")) {
			// "reference:file:/" pour les bundles osgi
			src = src.substring("reference:file:/".length());
		}
		if (src.endsWith(".jar") || src.endsWith(".war")) {
			src = src.intern();
		}
		return src;
	}
	return null;
}
 
Example #9
Source File: ClassUtils.java    From sofa-ark with Apache License 2.0 6 votes vote down vote up
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();
    }
 
Example #10
Source File: Launcher.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example #11
Source File: Activation.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private static PermissionCollection getExecPermissions() {
    /*
     * The approach used here is taken from the similar method
     * getLoaderAccessControlContext() in the class
     * sun.rmi.server.LoaderHandler.
     */

    // obtain permissions granted to all code in current policy
    PermissionCollection perms = AccessController.doPrivileged(
        new PrivilegedAction<PermissionCollection>() {
            public PermissionCollection run() {
                CodeSource codesource =
                    new CodeSource(null, (Certificate[]) null);
                Policy p = Policy.getPolicy();
                if (p != null) {
                    return p.getPermissions(codesource);
                } else {
                    return new Permissions();
                }
            }
        });

    return perms;
}
 
Example #12
Source File: AddonClassLoader.java    From Sandbox with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected PermissionCollection getPermissions(CodeSource codesource) {
    Permissions pc = new Permissions();
    pc.add(new FilePermission("data/-", "read")); // Can read everything from data dir
    pc.add(new FilePermission(String.format("data/%s/-", spec.getModid()), "read,write,delete")); // Can write everything inside addon data dir
    return pc;
}
 
Example #13
Source File: ContextInsulation.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
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);
    }
 
Example #14
Source File: ReflectUtils.java    From jsongood with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #15
Source File: MethodUtil.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example #16
Source File: JavaAdapterFactory.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private static ProtectionDomain createMinimalPermissionDomain() {
    // Generated classes need to have at least the permission to access Nashorn runtime and runtime.linker packages.
    final Permissions permissions = new Permissions();
    permissions.add(new RuntimePermission("accessClassInPackage.jdk.nashorn.internal.objects"));
    permissions.add(new RuntimePermission("accessClassInPackage.jdk.nashorn.internal.runtime"));
    permissions.add(new RuntimePermission("accessClassInPackage.jdk.nashorn.internal.runtime.linker"));
    return new ProtectionDomain(new CodeSource(null, (CodeSigner[])null), permissions);
}
 
Example #17
Source File: NullCodeSource.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    Policy policy = Policy.getPolicy();
    PermissionCollection perms = policy.getPermissions((CodeSource)null);
    if (perms.elements().hasMoreElements()) {
        System.err.println(perms);
        throw new Exception("PermissionCollection is not empty");
    }
}
 
Example #18
Source File: GroovyClassLoader.java    From groovy with Apache License 2.0 5 votes vote down vote up
private String genSourceCacheKey(GroovyCodeSource codeSource) {
    StringBuilder strToDigest;

    String scriptText = codeSource.getScriptText();
    if (null != scriptText) {
        strToDigest = new StringBuilder((int) (scriptText.length() * 1.2));
        strToDigest.append("scriptText:").append(scriptText);

        CodeSource cs = codeSource.getCodeSource();
        if (null != cs) {
            strToDigest.append("/codeSource:").append(cs);
        }
    } else {
        strToDigest = new StringBuilder(32);
        // if the script text is null, i.e. the script content is invalid
        // use the name as cache key for the time being to trigger the validation by `groovy.lang.GroovyClassLoader.validate`
        // note: the script will not be cached due to the invalid script content,
        //       so it does not matter even if cache key is not the md5 value of script content
        strToDigest.append("name:").append(codeSource.getName());
    }

    try {
        return EncodingGroovyMethods.md5(strToDigest);
    } catch (NoSuchAlgorithmException e) {
        throw new GroovyRuntimeException(e); // should never reach here!
    }
}
 
Example #19
Source File: Implies.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
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");
    }
}
 
Example #20
Source File: AuthPolicyFile.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@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);
            }
        }
    });
}
 
Example #21
Source File: CompilingClassEntry.java    From baratine with GNU General Public License v2.0 5 votes vote down vote up
public CompilingClassEntry(CompilingLoader compilingLoader,
                           DynamicClassLoader loader,
                           String name, PathImpl sourcePath,
                           PathImpl classPath,
                           CodeSource codeSource)
{
  super(loader, name, sourcePath, classPath, codeSource);

  _loader = compilingLoader;
}
 
Example #22
Source File: ClassLoading.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Repeatedly load a class not found in classpath through RMIClassLoader.
 * Arguments: <# reps>
 */
public long run(String[] args) throws Exception {
    int reps = Integer.parseInt(args[0]);
    CodeSource csrc = getClass().getProtectionDomain().getCodeSource();
    String url = "jar:" + csrc.getLocation().toString() + ALTROOT;

    long start = System.currentTimeMillis();
    for (int i = 0; i < reps; i++)
        RMIClassLoader.loadClass(url, CLASSNAME);
    long time = System.currentTimeMillis() - start;

    return time;
}
 
Example #23
Source File: URLClassLoader.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
Resource loadResource( String name ) throws IOException
{
	URL url = new URL( baseUrl, name );
	InputStream in = url.openStream( );
	try
	{
		final byte[] bytes = loadStream( in );
		return new Resource( ) {

			byte[] getBytes( )
			{
				return bytes;
			};

			CodeSource getCodeSource( )
			{
				return codeSource;
			}

			Manifest getManifest( )
			{
				return null;
			}
		};
	}
	finally
	{
		in.close( );
	}
}
 
Example #24
Source File: ClassLoader.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private String defineClassSourceLocation(ProtectionDomain pd)
{
    CodeSource cs = pd.getCodeSource();
    String source = null;
    if (cs != null && cs.getLocation() != null) {
        source = cs.getLocation().toString();
    }
    return source;
}
 
Example #25
Source File: AppletClassLoader.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
protected AppletClassLoader(URL base) {
    super(new URL[0]);
    this.base = base;
    this.codesource =
        new CodeSource(base, (java.security.cert.Certificate[]) null);
    acc = AccessController.getContext();
}
 
Example #26
Source File: Implies.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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");
    }
}
 
Example #27
Source File: Launcher.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #28
Source File: JobCenterAutoConfiguration.java    From summerframework with Apache License 2.0 5 votes vote down vote up
private File findSource(Class<?> sourceClass) {
    try {
        ProtectionDomain domain = (sourceClass != null ? sourceClass.getProtectionDomain() : null);
        CodeSource codeSource = (domain != null ? domain.getCodeSource() : null);
        URL location = (codeSource != null ? codeSource.getLocation() : null);
        File source = (location != null ? findSource(location) : null);
        if (source != null && source.exists() && !isUnitTest()) {
            return source.getAbsoluteFile();
        }
        return null;
    } catch (Exception ex) {
        return null;
    }
}
 
Example #29
Source File: CodeSourceFacadeTest.java    From nem.core with MIT License 5 votes vote down vote up
@Test
public void canCreateFacadeAroundNoCertificates() throws Exception {
	// Act:
	final URL url = new URL("http://nem.com/foo/n.jar");
	final CodeSourceFacade facade = new CodeSourceFacade(new CodeSource(url, new Certificate[] {}));

	// Assert:
	Assert.assertThat(facade.getLocation(), IsEqual.equalTo(url));
	Assert.assertThat(facade.getFirstCertificate(), IsNull.nullValue());
}
 
Example #30
Source File: ReflectUtils.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
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();
}