Java Code Examples for java.security.CodeSource

The following examples show how to use java.security.CodeSource. These examples are extracted from open source projects. 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 Project: jaxb2-maven-plugin   Author: mojohaus   File: XsdGeneratorHelperTest.java    License: 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 #2
Source Project: baratine   Author: baratine   File: SimpleLoader.java    License: 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 Project: jdk8u_jdk   Author: JetBrains   File: Launcher.java    License: 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 #4
Source Project: hottub   Author: dsrg-uoft   File: JarFile.java    License: 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 #5
Source Project: jdk8u60   Author: chenghanpeng   File: Activation.java    License: 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 #6
Source Project: TencentKona-8   Author: Tencent   File: Activation.java    License: 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 #7
Source Project: jdk8u-dev-jdk   Author: frohoff   File: ClassLoader.java    License: GNU General Public License v2.0 6 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 #8
Source Project: openjdk-8-source   Author: keerath   File: Launcher.java    License: 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 #9
Source Project: sofa-ark   Author: sofastack   File: ClassUtils.java    License: 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 Project: javamelody   Author: javamelody   File: HeapHistogram.java    License: 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 #11
Source Project: brpc-java   Author: baidu   File: ReflectUtils.java    License: 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 #12
Source Project: nem.core   Author: NemProject   File: CodeSourceFacadeTest.java    License: 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 #13
Source Project: birt   Author: eclipse   File: URLClassLoader.java    License: 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 #14
Source Project: jdk8u-jdk   Author: lambdalab-mirror   File: ClassLoading.java    License: 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 #15
Source Project: jdk8u-jdk   Author: frohoff   File: AuthPolicyFile.java    License: 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 #16
Source Project: jdk8u_jdk   Author: JetBrains   File: Implies.java    License: 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 #17
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: MethodUtil.java    License: 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 #18
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: ClassLoader.java    License: 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 #19
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: Launcher.java    License: 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 #20
Source Project: jeesuite-libs   Author: vakinge   File: ReflectUtils.java    License: 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 #21
Source Project: camunda-bpm-process-test-coverage   Author: camunda   File: ClassLocationURL.java    License: Apache License 2.0 5 votes vote down vote up
static URL urlFromCodeSource(Class aclass) {
  try {
    CodeSource codeSource = aclass.getProtectionDomain().getCodeSource();
    URL url = codeSource != null ? codeSource.getLocation() : null;
    // url is in one of two forms
    // 1) ./build/classes/
    // 2) jardir/JarName.jar
    return url;
  } catch (SecurityException ex) {
    return null;
  }
}
 
Example #22
Source Project: jdk8u-jdk   Author: frohoff   File: RegistryImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 });
}
 
Example #23
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: ClassLoader.java    License: 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 #24
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: AppletClassLoader.java    License: 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 #25
Source Project: jdk8u60   Author: chenghanpeng   File: NashornLoader.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
protected PermissionCollection getPermissions(final CodeSource codesource) {
    final Permissions permCollection = new Permissions();
    for (final Permission perm : SCRIPT_PERMISSIONS) {
        permCollection.add(perm);
    }
    return permCollection;
}
 
Example #26
Source Project: jsongood   Author: LaiZhou   File: ReflectUtils.java    License: 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 #27
Source Project: jdk8u_jdk   Author: JetBrains   File: NullCodeSource.java    License: 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 #28
Source Project: groovy   Author: apache   File: GroovyClassLoader.java    License: 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 #29
Source Project: jdk8u-jdk   Author: frohoff   File: ClassLoader.java    License: 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 #30
Source Project: hottub   Author: dsrg-uoft   File: Launcher.java    License: 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;
}