Example usage for java.security CodeSource CodeSource

List of usage examples for java.security CodeSource CodeSource

Introduction

In this page you can find the example usage for java.security CodeSource CodeSource.

Prototype

public CodeSource(URL url, CodeSigner[] signers) 

Source Link

Document

Constructs a CodeSource and associates it with the specified location and set of code signers.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {

    SecurityManager sm = new SecurityManager();
    System.setSecurityManager(sm);
    URL codebase = new URL("http://java.sun.com/");

    //codebase = new File("c:\\java\\").toURI().toURL();
    //codebase = new File(System.getProperty("user.home")).toURI().toURL();

    CodeSource cs = new CodeSource(codebase, (Certificate[]) null);

    PermissionCollection pcoll = Policy.getPolicy().getPermissions(cs);

    Enumeration e = pcoll.elements();
    for (; e.hasMoreElements();) {
        Permission p = (Permission) e.nextElement();
    }//ww  w  .j  av a 2  s  . c o  m
}

From source file:com.thoughtworks.acceptance.SecurityManagerTest.java

protected void setUp() throws Exception {
    super.setUp();
    System.setSecurityManager(null);
    source = new CodeSource(new File("target").toURI().toURL(), (Certificate[]) null);

    sm = new DynamicSecurityManager();
    Policy policy = Policy.getPolicy();
    sm.setPermissions(source, policy.getPermissions(source));
    sm.addPermission(source, new RuntimePermission("setSecurityManager"));

    File mainClasses = new File(System.getProperty("user.dir"), "target/classes/-");
    File testClasses = new File(System.getProperty("user.dir"), "target/test-classes/-");
    String[] javaClassPath = StringUtils.split(System.getProperty("java.class.path"), File.pathSeparatorChar);
    File javaHome = new File(System.getProperty("java.home"), "-");

    // necessary permission start here
    sm.addPermission(source, new FilePermission(mainClasses.toString(), "read"));
    sm.addPermission(source, new FilePermission(testClasses.toString(), "read"));
    sm.addPermission(source, new FilePermission(javaHome.toString(), "read"));
    for (int i = 0; i < javaClassPath.length; ++i) {
        if (javaClassPath[i].endsWith(".jar")) {
            sm.addPermission(source, new FilePermission(javaClassPath[i], "read"));
        }/*w ww .java 2s.  c o m*/
    }
}

From source file:org.ngrinder.script.handler.GroovyScriptHandler.java

@Override
public String checkSyntaxErrors(String path, String script) {
    URL url;//ww w .java  2  s  .  c  o  m
    try {
        url = new URL("file", "", path);
        final CompilationUnit unit = new CompilationUnit(CompilerConfiguration.DEFAULT,
                new CodeSource(url, (java.security.cert.Certificate[]) null), null);
        unit.addSource(path, script);
        unit.compile(Phases.CONVERSION);
    } catch (MalformedURLException e) {
        noOp();
    } catch (CompilationFailedException ce) {
        return ce.getMessage();
    }
    return null;
}

From source file:com.jaspersoft.jasperserver.api.engine.jasperreports.util.PermissionsListProtectionDomainProvider.java

protected CodeSource getCodeSource() {
    try {/*from  w w  w.j a va 2  s  .c o  m*/
        URL location = new URL(null, "repo:/", new URLStreamHandler() {
            protected URLConnection openConnection(URL u) throws IOException {
                throw new IOException("Cannot read from repo:/ location");
            }
        });
        return new CodeSource(location, (Certificate[]) null);
    } catch (MalformedURLException e) {
        throw new JSExceptionWrapper(e);
    }
}

From source file:me.rgcjonas.portableMinecraftLauncher.ModdingClassLoader.java

public Class<?> findClass(String name) throws ClassNotFoundException {
    byte[] data = null;
    String resourceName = name.replace('.', '/').concat(".class"); //getResource expects this form
    if (moddedClasses.containsKey(name)) {
        data = moddedClasses.get(name);//from   w  ww  .j a v  a2  s.c om
    } else {
        try {
            InputStream is = this.getResourceAsStream(resourceName);
            if (is == null) {
                System.out.println("class not found: " + resourceName + "\n");
                throw new ClassNotFoundException();
            }
            data = IOUtils.toByteArray(is);
        } catch (IOException e) {
            throw new ClassNotFoundException(e.toString());
        }
    }
    CodeSource source = new CodeSource(this.getResource(resourceName), new Certificate[] {});
    return defineClass(name, data, 0, data.length, source);
}

From source file:com.github.wolf480pl.mias4j.util.AbstractTransformingClassLoader.java

protected CodeSource getCodeSourceAndDefinePackage(URLConnection resourceConn, String resourceName,
        String className) {//from w ww .  ja v a 2 s  .c  o  m
    URL codeSourceURL = null;
    CodeSigner[] signers = null;
    Manifest man = null;

    if (resourceConn instanceof JarURLConnection) {
        codeSourceURL = ((JarURLConnection) resourceConn).getJarFileURL();
        try {
            man = ((JarURLConnection) resourceConn).getManifest();
        } catch (IOException e) {
            LOG.warn("Couldn't get jar manifest", e);
        }
        try {
            signers = ((JarURLConnection) resourceConn).getJarEntry().getCodeSigners();
        } catch (IOException e) {
            LOG.warn("Couldn't get jar signers", e);
        }
    }

    boolean guessedCodeSource = false;
    if (codeSourceURL == null) {
        codeSourceURL = guessCodeSourceURL(resourceName, resourceConn.getURL());
        guessedCodeSource = true;
    }
    CodeSource cs = new CodeSource(codeSourceURL, signers);

    // If we guess wrong code source URL, we don't want to accidentally seal a package with that URL.
    definePackageIfNotExists(className, man, guessedCodeSource ? null : codeSourceURL);

    // TODO: Do we really want to assign codesource permissions and protection domain based on a guessed CodeSource?
    return cs;
}

From source file:com.seeburger.vfs2.util.VFSClassLoader.java

/**
 * Loads and verifies the class with name and located with res.
 *///from w  w w  .j  av  a 2s  .  co m
private Class<?> defineClass(final String name, final Resource res) throws IOException {
    final URL url = res.getCodeSourceURL();
    final String pkgName = res.getPackageName();
    if (pkgName != null) {
        final Package pkg = getPackage(pkgName);
        if (pkg != null) {
            if (pkg.isSealed()) {
                if (!pkg.isSealed(url)) {
                    throw new FileSystemException("vfs.impl/pkg-sealed-other-url", pkgName);
                }
            } else {
                if (isSealed(res)) {
                    throw new FileSystemException("vfs.impl/pkg-sealing-unsealed", pkgName);
                }
            }
        } else {
            definePackage(pkgName, res);
        }
    }

    final byte[] bytes = res.getBytes();
    final Certificate[] certs = res.getFileObject().getContent().getCertificates();
    final CodeSource cs = new CodeSource(url, certs);
    return defineClass(name, bytes, 0, bytes.length, cs);
}

From source file:com.seeburger.vfs2.util.VFSClassLoader.java

/**
 * Calls super.getPermissions both for the code source and also
 * adds the permissions granted to the parent layers.
 * @param cs the CodeSource./*from www.java  2 s  . com*/
 * @return The PermissionCollections.
 */
@Override
protected PermissionCollection getPermissions(final CodeSource cs) {
    try {
        final String url = cs.getLocation().toString();
        FileObject file = lookupFileObject(url);
        if (file == null) {
            return super.getPermissions(cs);
        }

        FileObject parentLayer = file.getFileSystem().getParentLayer();
        if (parentLayer == null) {
            return super.getPermissions(cs);
        }

        Permissions combi = new Permissions();
        PermissionCollection permCollect = super.getPermissions(cs);
        copyPermissions(permCollect, combi);

        for (FileObject parent = parentLayer; parent != null; parent = parent.getFileSystem()
                .getParentLayer()) {
            final CodeSource parentcs = new CodeSource(parent.getURL(), parent.getContent().getCertificates());
            permCollect = super.getPermissions(parentcs);
            copyPermissions(permCollect, combi);
        }

        return combi;
    } catch (final FileSystemException fse) {
        throw new SecurityException(fse.getMessage());
    }
}

From source file:net.datenwerke.sandbox.SandboxLoader.java

@Override
protected Class<?> loadClass(final String name, boolean resolve) throws ClassNotFoundException {
    Class clazz = null;//from w  ww .j  a va 2s  .  c  o m

    if (debug)
        logger.log(Level.INFO,
                getName() + "(" + System.identityHashCode(this) + ")" + " about to load class: " + name);

    if (null != enhancer)
        enhancer.classtoBeLoaded(this, name, resolve);

    boolean trustedSource = false;

    if (name.startsWith("java.") || bypassClazz(name)) {
        clazz = super.loadClass(name, resolve);

        /* check if it comes from an available jar */
        if (!name.startsWith("java.") && null != whitelistedUcp) {
            String path = name.replace('.', '/').concat(".class");

            Resource res = whitelistedUcp.getResource(path, false);
            if (res != null)
                trustedSource = true;
        }

    } else {
        /* check subcontext */
        if (hasSubloaders) {
            SandboxLoader subLoader = doGetSubLoaderByClassContext(name);
            if (null != subLoader)
                return subLoader.loadClass(name, resolve);
        }

        /* check if we have already handeled this class */
        clazz = findLoadedClass(name);
        if (clazz != null) {
            if (null != whitelistedUcp) {
                String path = name.replace('.', '/').concat(".class");
                Resource res = whitelistedUcp.getResource(path, false);
                if (res != null)
                    trustedSource = true;
            }
        } else {
            try {
                String basePath = name.replace('.', '/');
                String path = basePath.concat(".class");

                ProtectionDomain domain = null;
                try {
                    CodeSource codeSource = new CodeSource(new URL("file", "", codesource.concat(basePath)),
                            (java.security.cert.Certificate[]) null);
                    domain = new ProtectionDomain(codeSource, new Permissions(), this, null);
                } catch (MalformedURLException e) {
                    throw new RuntimeException("Could not create protection domain.");
                }

                /* define package */
                int i = name.lastIndexOf('.');
                if (i != -1) {
                    String pkgName = name.substring(0, i);
                    java.lang.Package pkg = getPackage(pkgName);
                    if (pkg == null) {
                        definePackage(pkgName, null, null, null, null, null, null, null);
                    }
                }

                /* first strategy .. check jars */
                if (null != whitelistedUcp) {
                    Resource res = whitelistedUcp.getResource(path, false);
                    if (res != null) {
                        byte[] cBytes = enhance(name, res.getBytes());
                        clazz = defineClass(name, cBytes, 0, cBytes.length, domain);
                        trustedSource = true;
                    }
                }

                /* load class */
                if (clazz == null) {
                    InputStream in = null;
                    try {
                        /* we only load from local sources */
                        in = parent.getResourceAsStream(path);
                        byte[] cBytes = null;
                        if (in != null)
                            cBytes = IOUtils.toByteArray(in);

                        if (null == cBytes && null != enhancer)
                            cBytes = enhancer.loadClass(this, name);
                        if (null == cBytes)
                            throw new ClassNotFoundException("Could not find " + name);

                        /* load and define class */
                        cBytes = enhance(name, cBytes);
                        clazz = defineClass(name, cBytes, 0, cBytes.length, domain);
                    } finally {
                        if (null != in) {
                            try {
                                in.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }

                /* do we need to resolve */
                if (resolve)
                    resolveClass(clazz);
            } catch (IOException e) {
                throw new ClassNotFoundException("Could not load " + name, e);
            } catch (Exception e) {
                throw new ClassNotFoundException("Could not load " + name, e);
            }
        }
    }

    if (!trustedSource && null != clazz && null != securityManager)
        securityManager.checkClassAccess(name);

    if (null != enhancer)
        enhancer.classLoaded(this, name, clazz);

    return clazz;
}

From source file:com.googlecode.onevre.utils.ServerClassLoader.java

private Class<?> defineClassFromJar(String name, URL url, File jar, String pathName) throws IOException {
    JarFile jarFile = new JarFile(jar);
    JarEntry entry = jarFile.getJarEntry(pathName);
    InputStream input = jarFile.getInputStream(entry);
    byte[] classData = new byte[(int) entry.getSize()];
    int totalBytes = 0;
    while (totalBytes < classData.length) {
        int bytesRead = input.read(classData, totalBytes, classData.length - totalBytes);
        if (bytesRead == -1) {
            throw new IOException("Jar Entry too short!");
        }//from   www.j  a  v  a2 s.  c o m
        totalBytes += bytesRead;
    }
    Class<?> loadedClass = defineClass(name, classData, 0, classData.length,
            new CodeSource(url, entry.getCertificates()));
    input.close();
    jarFile.close();
    return loadedClass;
}