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:org.rhq.bindings.ScriptEngineFactory.java

/**
 * This method is similar to the {@link #getScriptEngine(String, PackageFinder, StandardBindings)} method
 * but additionally applies a security wrapper on the returned script engine so that the scripts execute
 * with the provided java permissions./* w  w  w  . java2s. com*/
 * 
 * @see #getScriptEngine(String, PackageFinder, StandardBindings)
 */
public static ScriptEngine getSecuredScriptEngine(final String language, final PackageFinder packageFinder,
        final StandardBindings bindings, final PermissionCollection permissions)
        throws ScriptException, IOException {
    CodeSource src = new CodeSource(new URL("http://rhq-project.org/scripting"), (Certificate[]) null);
    ProtectionDomain scriptDomain = new ProtectionDomain(src, permissions);
    AccessControlContext ctx = new AccessControlContext(new ProtectionDomain[] { scriptDomain });
    try {
        return AccessController.doPrivileged(new PrivilegedExceptionAction<ScriptEngine>() {
            @Override
            public ScriptEngine run() throws Exception {
                //This might seem a bit excessive but is necessary due to the 
                //change in security handling in the rhino script engine
                //that occured in Java6u27 (due to a CVE desribed here:
                //https://bugzilla.redhat.com/show_bug.cgi?id=CVE-2011-3544)

                //In Java 6u26 and earlier, it was enough to wrap a script engine
                //in the sandbox and everything would work.

                //Java 6u27 introduced new behavior where the rhino script engine
                //remembers the access control context with which it has been 
                //constructed and combines that with the callers protection domain
                //when a script is executed. Because this class has all perms and
                //all the code in RHQ that called ScriptEngine.eval* also
                //had all perms, the scripts would never be sandboxed even if the call
                //was pushed through the SandboxedScriptEngine.

                //This means that the below wrapping is necessary for the security
                //to work in java6 pre u27 while the surrounding privileged block 
                //is necessary for the security to be applied in java6 u27 and later.
                return new SandboxedScriptEngine(getScriptEngine(language, packageFinder, bindings),
                        permissions);
            }
        }, ctx);
    } catch (PrivilegedActionException e) {
        Throwable cause = e.getCause();
        if (cause instanceof IOException) {
            throw (IOException) cause;
        } else if (cause instanceof ScriptException) {
            throw (ScriptException) cause;
        } else {
            throw new ScriptException(e);
        }
    }
}

From source file:org.spoutcraft.launcher.launch.MinecraftClassLoader.java

private Class<?> findClassInjar(String name, File file) throws ClassNotFoundException {
    byte classByte[];
    Class<?> result = null;
    JarFile jar = null;/*from   w  w w. ja v  a2  s . co  m*/
    try {
        jar = new JarFile(file);
        JarEntry entry = jar.getJarEntry(name.replace(".", "/") + ".class");
        if (entry != null) {
            InputStream is = jar.getInputStream(entry);
            ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
            int next = is.read();
            while (-1 != next) {
                byteStream.write(next);
                next = is.read();
            }

            classByte = byteStream.toByteArray();
            result = defineClass(name, classByte, 0, classByte.length,
                    new CodeSource(file.toURI().toURL(), (CodeSigner[]) null));
            loadedClasses.put(name, result);
            return result;
        }
    } catch (FileNotFoundException e) {
        // Assume temp file has been cleaned if the thread is interrupted
        if (!Thread.currentThread().isInterrupted()) {
            e.printStackTrace();
        }
    } catch (ZipException zipEx) {
        System.out.println("Failed to open " + name + " from " + file.getPath());
        zipEx.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            jar.close();
        } catch (IOException ignore) {
        }
    }
    return null;
}

From source file:org.springframework.boot.web.servlet.server.DocumentRootTests.java

@Test
public void codeSourceArchivePath() throws Exception {
    CodeSource codeSource = new CodeSource(new URL("file", "", "/some/test/path/"), (Certificate[]) null);
    File codeSourceArchive = this.documentRoot.getCodeSourceArchive(codeSource);
    assertThat(codeSourceArchive).isEqualTo(new File("/some/test/path/"));
}

From source file:org.springframework.boot.web.servlet.server.DocumentRootTests.java

@Test
public void codeSourceArchivePathContainingSpaces() throws Exception {
    CodeSource codeSource = new CodeSource(new URL("file", "", "/test/path/with%20space/"),
            (Certificate[]) null);
    File codeSourceArchive = this.documentRoot.getCodeSourceArchive(codeSource);
    assertThat(codeSourceArchive).isEqualTo(new File("/test/path/with space/"));
}

From source file:org.tinygroup.jspengine.compiler.JspRuntimeContext.java

/**
 * Method used to initialize SecurityManager data.
 *///  ww  w . j  a v a  2 s  . co  m
private void initSecurity() {

    // Setup the PermissionCollection for this web app context
    // based on the permissions configured for the root of the
    // web app context directory, then add a file read permission
    // for that directory.
    Policy policy = Policy.getPolicy();
    if (policy != null) {
        try {
            // Get the permissions for the web app context
            String docBase = context.getRealPath("/");
            if (docBase == null) {
                docBase = options.getScratchDir().toString();
            }
            String codeBase = docBase;
            if (!codeBase.endsWith(File.separator)) {
                codeBase = codeBase + File.separator;
            }
            File contextDir = new File(codeBase);
            URL url = contextDir.getCanonicalFile().toURL();
            codeSource = new CodeSource(url, (Certificate[]) null);
            permissionCollection = policy.getPermissions(codeSource);

            // Create a file read permission for web app context directory
            if (!docBase.endsWith(File.separator)) {
                permissionCollection.add(new FilePermission(docBase, "read"));
                docBase = docBase + File.separator;
            } else {
                permissionCollection
                        .add(new FilePermission(docBase.substring(0, docBase.length() - 1), "read"));
            }
            docBase = docBase + "-";
            permissionCollection.add(new FilePermission(docBase, "read"));

            // Create a file read permission for web app tempdir (work)
            // directory
            String workDir = options.getScratchDir().toString();
            if (!workDir.endsWith(File.separator)) {
                permissionCollection.add(new FilePermission(workDir, "read"));
                workDir = workDir + File.separator;
            }
            workDir = workDir + "-";
            permissionCollection.add(new FilePermission(workDir, "read"));

            // Allow the JSP to access
            // org.tinygroup.jspengine.runtime.HttpJspBase
            permissionCollection
                    .add(new RuntimePermission("accessClassInPackage.org.tinygroup.jspengine.runtime"));

            if (parentClassLoader instanceof URLClassLoader) {
                URL[] urls = ((URLClassLoader) parentClassLoader).getURLs();
                String jarUrl = null;
                String jndiUrl = null;
                for (int i = 0; i < urls.length; i++) {
                    if (jndiUrl == null && urls[i].toString().startsWith("jndi:")) {
                        jndiUrl = urls[i].toString() + "-";
                    }
                    if (jarUrl == null && urls[i].toString().startsWith("jar:jndi:")) {
                        jarUrl = urls[i].toString();
                        jarUrl = jarUrl.substring(0, jarUrl.length() - 2);
                        jarUrl = jarUrl.substring(0, jarUrl.lastIndexOf('/')) + "/-";
                    }
                }
                if (jarUrl != null) {
                    permissionCollection.add(new FilePermission(jarUrl, "read"));
                    permissionCollection.add(new FilePermission(jarUrl.substring(4), "read"));
                }
                if (jndiUrl != null)
                    permissionCollection.add(new FilePermission(jndiUrl, "read"));
            }
        } catch (Exception e) {
            context.log("Security Init for context failed", e);
        }
    }
}