Search in sources :

Example 1 with CodeSource

use of java.security.CodeSource in project groovy by apache.

the class JavacJavaCompiler method makeParameters.

private String[] makeParameters(List<String> files, GroovyClassLoader parentClassLoader) {
    Map options = config.getJointCompilationOptions();
    LinkedList<String> paras = new LinkedList<String>();
    File target = config.getTargetDirectory();
    if (target == null)
        target = new File(".");
    // defaults
    paras.add("-d");
    paras.add(target.getAbsolutePath());
    paras.add("-sourcepath");
    paras.add(((File) options.get("stubDir")).getAbsolutePath());
    // add flags
    String[] flags = (String[]) options.get("flags");
    if (flags != null) {
        for (String flag : flags) {
            paras.add('-' + flag);
        }
    }
    boolean hadClasspath = false;
    // add namedValues
    String[] namedValues = (String[]) options.get("namedValues");
    if (namedValues != null) {
        for (int i = 0; i < namedValues.length; i += 2) {
            String name = namedValues[i];
            if (name.equals("classpath"))
                hadClasspath = true;
            paras.add('-' + name);
            paras.add(namedValues[i + 1]);
        }
    }
    // append classpath if not already defined
    if (!hadClasspath) {
        // add all classpaths that compilation unit sees
        List<String> paths = new ArrayList<String>(config.getClasspath());
        ClassLoader cl = parentClassLoader;
        while (cl != null) {
            if (cl instanceof URLClassLoader) {
                for (URL u : ((URLClassLoader) cl).getURLs()) {
                    try {
                        paths.add(new File(u.toURI()).getPath());
                    } catch (URISyntaxException e) {
                    // ignore it
                    }
                }
            }
            cl = cl.getParent();
        }
        try {
            CodeSource codeSource = AccessController.doPrivileged(new PrivilegedAction<CodeSource>() {

                @Override
                public CodeSource run() {
                    return GroovyObject.class.getProtectionDomain().getCodeSource();
                }
            });
            if (codeSource != null) {
                paths.add(new File(codeSource.getLocation().toURI()).getPath());
            }
        } catch (URISyntaxException e) {
        // ignore it
        }
        StringBuilder resultPath = new StringBuilder(DefaultGroovyMethods.join((Iterable) paths, File.pathSeparator));
        paras.add("-classpath");
        paras.add(resultPath.toString());
    }
    // files to compile
    paras.addAll(files);
    return paras.toArray(new String[paras.size()]);
}
Also used : URISyntaxException(java.net.URISyntaxException) CodeSource(java.security.CodeSource) URL(java.net.URL) URLClassLoader(java.net.URLClassLoader) URLClassLoader(java.net.URLClassLoader) GroovyClassLoader(groovy.lang.GroovyClassLoader) File(java.io.File)

Example 2 with CodeSource

use of java.security.CodeSource in project tomcat by apache.

the class WebappClassLoaderBase method findClassInternal.

/**
     * Find specified class in local repositories.
     *
     * @param name The binary name of the class to be loaded
     *
     * @return the loaded class, or null if the class isn't found
     */
protected Class<?> findClassInternal(String name) {
    checkStateForResourceLoading(name);
    if (name == null) {
        return null;
    }
    String path = binaryNameToPath(name, true);
    ResourceEntry entry = resourceEntries.get(path);
    WebResource resource = null;
    if (entry == null) {
        resource = resources.getClassLoaderResource(path);
        if (!resource.exists()) {
            return null;
        }
        entry = new ResourceEntry();
        entry.lastModified = resource.getLastModified();
        // Add the entry in the local resource repository
        synchronized (resourceEntries) {
            // Ensures that all the threads which may be in a race to load
            // a particular class all end up with the same ResourceEntry
            // instance
            ResourceEntry entry2 = resourceEntries.get(path);
            if (entry2 == null) {
                resourceEntries.put(path, entry);
            } else {
                entry = entry2;
            }
        }
    }
    Class<?> clazz = entry.loadedClass;
    if (clazz != null)
        return clazz;
    synchronized (getClassLoadingLock(name)) {
        clazz = entry.loadedClass;
        if (clazz != null)
            return clazz;
        if (resource == null) {
            resource = resources.getClassLoaderResource(path);
        }
        if (!resource.exists()) {
            return null;
        }
        byte[] binaryContent = resource.getContent();
        Manifest manifest = resource.getManifest();
        URL codeBase = resource.getCodeBase();
        Certificate[] certificates = resource.getCertificates();
        if (transformers.size() > 0) {
            // If the resource is a class just being loaded, decorate it
            // with any attached transformers
            String className = name.endsWith(CLASS_FILE_SUFFIX) ? name.substring(0, name.length() - CLASS_FILE_SUFFIX.length()) : name;
            String internalName = className.replace(".", "/");
            for (ClassFileTransformer transformer : this.transformers) {
                try {
                    byte[] transformed = transformer.transform(this, internalName, null, null, binaryContent);
                    if (transformed != null) {
                        binaryContent = transformed;
                    }
                } catch (IllegalClassFormatException e) {
                    log.error(sm.getString("webappClassLoader.transformError", name), e);
                    return null;
                }
            }
        }
        // Looking up the package
        String packageName = null;
        int pos = name.lastIndexOf('.');
        if (pos != -1)
            packageName = name.substring(0, pos);
        Package pkg = null;
        if (packageName != null) {
            pkg = getPackage(packageName);
            // Define the package (if null)
            if (pkg == null) {
                try {
                    if (manifest == null) {
                        definePackage(packageName, null, null, null, null, null, null, null);
                    } else {
                        definePackage(packageName, manifest, codeBase);
                    }
                } catch (IllegalArgumentException e) {
                // Ignore: normal error due to dual definition of package
                }
                pkg = getPackage(packageName);
            }
        }
        if (securityManager != null) {
            // Checking sealing
            if (pkg != null) {
                boolean sealCheck = true;
                if (pkg.isSealed()) {
                    sealCheck = pkg.isSealed(codeBase);
                } else {
                    sealCheck = (manifest == null) || !isPackageSealed(packageName, manifest);
                }
                if (!sealCheck)
                    throw new SecurityException("Sealing violation loading " + name + " : Package " + packageName + " is sealed.");
            }
        }
        try {
            clazz = defineClass(name, binaryContent, 0, binaryContent.length, new CodeSource(codeBase, certificates));
        } catch (UnsupportedClassVersionError ucve) {
            throw new UnsupportedClassVersionError(ucve.getLocalizedMessage() + " " + sm.getString("webappClassLoader.wrongVersion", name));
        }
        entry.loadedClass = clazz;
    }
    return clazz;
}
Also used : ClassFileTransformer(java.lang.instrument.ClassFileTransformer) WebResource(org.apache.catalina.WebResource) Manifest(java.util.jar.Manifest) CodeSource(java.security.CodeSource) URL(java.net.URL) IllegalClassFormatException(java.lang.instrument.IllegalClassFormatException) Certificate(java.security.cert.Certificate)

Example 3 with CodeSource

use of java.security.CodeSource in project tomcat by apache.

the class JspRuntimeContext method initSecurity.

/**
     * Method used to initialize SecurityManager data.
     */
private SecurityHolder 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();
    CodeSource source = null;
    PermissionCollection permissions = null;
    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().toURI().toURL();
            source = new CodeSource(url, (Certificate[]) null);
            permissions = policy.getPermissions(source);
            // Create a file read permission for web app context directory
            if (!docBase.endsWith(File.separator)) {
                permissions.add(new FilePermission(docBase, "read"));
                docBase = docBase + File.separator;
            } else {
                permissions.add(new FilePermission(docBase.substring(0, docBase.length() - 1), "read"));
            }
            docBase = docBase + "-";
            permissions.add(new FilePermission(docBase, "read"));
            // Spec says apps should have read/write for their temp
            // directory. This is fine, as no security sensitive files, at
            // least any that the app doesn't have full control of anyway,
            // will be written here.
            String workDir = options.getScratchDir().toString();
            if (!workDir.endsWith(File.separator)) {
                permissions.add(new FilePermission(workDir, "read,write"));
                workDir = workDir + File.separator;
            }
            workDir = workDir + "-";
            permissions.add(new FilePermission(workDir, "read,write,delete"));
            // Allow the JSP to access org.apache.jasper.runtime.HttpJspBase
            permissions.add(new RuntimePermission("accessClassInPackage.org.apache.jasper.runtime"));
        } catch (Exception e) {
            context.log("Security Init for context failed", e);
        }
    }
    return new SecurityHolder(source, permissions);
}
Also used : Policy(java.security.Policy) PermissionCollection(java.security.PermissionCollection) CodeSource(java.security.CodeSource) File(java.io.File) FilePermission(java.io.FilePermission) URL(java.net.URL) FileNotFoundException(java.io.FileNotFoundException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 4 with CodeSource

use of java.security.CodeSource in project elasticsearch by elastic.

the class ESPolicyUnitTests method testNullLocation.

/**
     * test with null location
     * <p>
     * its unclear when/if this happens, see https://bugs.openjdk.java.net/browse/JDK-8129972
     */
public void testNullLocation() throws Exception {
    assumeTrue("test cannot run with security manager", System.getSecurityManager() == null);
    PermissionCollection noPermissions = new Permissions();
    ESPolicy policy = new ESPolicy(noPermissions, Collections.emptyMap(), true);
    assertFalse(policy.implies(new ProtectionDomain(new CodeSource(null, (Certificate[]) null), noPermissions), new FilePermission("foo", "read")));
}
Also used : PermissionCollection(java.security.PermissionCollection) ProtectionDomain(java.security.ProtectionDomain) Permissions(java.security.Permissions) CodeSource(java.security.CodeSource) FilePermission(java.io.FilePermission)

Example 5 with CodeSource

use of java.security.CodeSource in project jetty.project by eclipse.

the class TypeUtil method getLoadedFrom.

/* ------------------------------------------------------------ */
public static Resource getLoadedFrom(Class<?> clazz) {
    ProtectionDomain domain = clazz.getProtectionDomain();
    if (domain != null) {
        CodeSource source = domain.getCodeSource();
        if (source != null) {
            URL location = source.getLocation();
            if (location != null)
                return Resource.newResource(location);
        }
    }
    String rname = clazz.getName().replace('.', '/') + ".class";
    ClassLoader loader = clazz.getClassLoader();
    URL url = (loader == null ? ClassLoader.getSystemClassLoader() : loader).getResource(rname);
    if (url != null) {
        try {
            return Resource.newResource(URIUtil.getJarSource(url.toString()));
        } catch (Exception e) {
            LOG.debug(e);
        }
    }
    return null;
}
Also used : ProtectionDomain(java.security.ProtectionDomain) CodeSource(java.security.CodeSource) URL(java.net.URL) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Aggregations

CodeSource (java.security.CodeSource)85 URL (java.net.URL)43 ProtectionDomain (java.security.ProtectionDomain)29 File (java.io.File)24 IOException (java.io.IOException)16 Certificate (java.security.cert.Certificate)14 URISyntaxException (java.net.URISyntaxException)10 Permissions (java.security.Permissions)10 Policy (java.security.Policy)10 JarFile (java.util.jar.JarFile)10 PermissionCollection (java.security.PermissionCollection)9 URI (java.net.URI)8 FilePermission (java.io.FilePermission)7 MalformedURLException (java.net.MalformedURLException)5 AccessControlContext (java.security.AccessControlContext)5 URLClassLoader (java.net.URLClassLoader)4 GroovyClassLoader (groovy.lang.GroovyClassLoader)3 JarURLConnection (java.net.JarURLConnection)3 SocketPermission (java.net.SocketPermission)3 Path (java.nio.file.Path)3