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:com.stratuscom.harvester.deployer.StarterServiceDeployer.java

void prepareService(ApplicationEnvironment env)
        throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException,
        IllegalArgumentException, InvocationTargetException, InstantiationException {

    CodeSource serviceCodeSource = new CodeSource(findServiceURL(env.getServiceArchive(), env.getServiceRoot()),
            new Certificate[0]);
    log.log(Level.INFO, MessageNames.CODESOURCE_IS, new Object[] { env.getServiceName(), serviceCodeSource });
    VirtualFileSystemClassLoader cl = createServiceClassloader(env.getServiceName(), env.getServiceRoot(),
            serviceCodeSource);//from  w ww  . ja va 2 s  . c o  m
    env.setClassLoader(cl);

    /*
     Create a codebase context.
     */
    CodebaseContext codebaseContext = codebaseHandler.createContext(env.getServiceName());
    env.setCodebaseContext(codebaseContext);
    exportServiceCodebaseJars(env.getServiceRoot(), codebaseContext);
    addPlatformCodebaseJars(codebaseContext);

    /*
     Setup the classloader's codebase annotation.
     */
    cl.setCodebase(codebaseContext.getCodebaseAnnotation());
    /*
     Grant the appropriate permissions to the service's classloader and
     protection domain.
     */
    Permission[] perms = createPermissionsInClassloader(cl);
    grantPermissions(cl, perms);

    /*
     Create the service's working directory and grant permissions to it.
    */
    createWorkDirectoryFor(env);
    grantPermissionsToWorkDirectoryFor(env);

    /*
     * Create a working context (work manager).
     */
    env.setWorkingContext(contextualWorkManager.createContext(env.getServiceName(), env.getClassLoader()));

    setupLiaisonConfiguration(env);
}

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

public Class<?> defineClass(String name, byte[] classBytes, boolean enhanceClass) {
    securityManager.checkPermission(new SandboxRuntimePermission("defineClass"));

    Class<?> clazz = findLoadedClass(name);
    if (null != clazz)
        return clazz;

    if (enhanceClass) {
        try {//from ww w. j a  v a 2  s.c  om
            classBytes = enhance(name, classBytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

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

    return defineClass(name, classBytes, 0, classBytes.length, domain);
}

From source file:org.apache.catalina.loader.WebappClassLoader.java

/**
 * Find specified class in local repositories.
 *
 * @return the loaded class, or null if the class isn't found
 *///from  w  w  w  .  j  a  va2 s  .  c o m
protected Class findClassInternal(String name) throws ClassNotFoundException {

    if (!validate(name))
        throw new ClassNotFoundException(name);

    String tempPath = name.replace('.', '/');
    String classPath = tempPath + ".class";

    ResourceEntry entry = null;

    entry = findResourceInternal(name, classPath);

    if ((entry == null) || (entry.binaryContent == null))
        throw new ClassNotFoundException(name);

    Class clazz = entry.loadedClass;
    if (clazz != null)
        return clazz;

    // 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) {
            if (entry.manifest == null) {
                definePackage(packageName, null, null, null, null, null, null, null);
            } else {
                definePackage(packageName, entry.manifest, entry.codeBase);
            }
        }

    }

    // Create the code source object
    CodeSource codeSource = new CodeSource(entry.codeBase, entry.certificates);

    if (securityManager != null) {

        // Checking sealing
        if (pkg != null) {
            boolean sealCheck = true;
            if (pkg.isSealed()) {
                sealCheck = pkg.isSealed(entry.codeBase);
            } else {
                sealCheck = (entry.manifest == null) || !isPackageSealed(packageName, entry.manifest);
            }
            if (!sealCheck)
                throw new SecurityException(
                        "Sealing violation loading " + name + " : Package " + packageName + " is sealed.");
        }

    }

    if (entry.loadedClass == null) {
        synchronized (this) {
            if (entry.loadedClass == null) {
                clazz = defineClass(name, entry.binaryContent, 0, entry.binaryContent.length, codeSource);
                entry.loadedClass = clazz;
                entry.binaryContent = null;
                entry.source = null;
                entry.codeBase = null;
                entry.manifest = null;
                entry.certificates = null;
            } else {
                clazz = entry.loadedClass;
            }
        }
    } else {
        clazz = entry.loadedClass;
    }

    return clazz;

}

From source file:org.apache.jasper.compiler.JspRuntimeContext.java

/**
 * Method used to initialize SecurityManager data.
 *//*from   ww w  . j av  a 2s  . 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, 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.apache.jasper.runtime.HttpJspBase
            permissionCollection.add(new RuntimePermission("accessClassInPackage.org.apache.jasper.runtime"));

            if (parentClassLoader instanceof URLClassLoader) {
                URL[] urls = 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);
        }
    }
}

From source file:org.apache.river.container.deployer.StarterServiceDeployer.java

void prepareService(ApplicationEnvironment env)
        throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException,
        IllegalArgumentException, InvocationTargetException, InstantiationException {

    CodeSource serviceCodeSource = new CodeSource(findServiceURL(env.getServiceArchive(), env.getServiceRoot()),
            new Certificate[0]);
    log.log(Level.INFO, MessageNames.CODESOURCE_IS, new Object[] { env.getServiceName(), serviceCodeSource });
    VirtualFileSystemClassLoader cl = createServiceClassloader(env.getServiceRoot(), serviceCodeSource);
    env.setClassLoader(cl);/*from   w  w  w . j a va2  s .c o m*/

    /*
     Create a codebase context.
     */
    CodebaseContext codebaseContext = codebaseHandler.createContext(env.getServiceName());
    env.setCodebaseContext(codebaseContext);
    addPlatformCodebaseJars(codebaseContext);
    exportServiceCodebaseJars(env.getServiceRoot(), codebaseContext);

    /*
     Setup the classloader's codebase annotation.
     */
    cl.setCodebase(codebaseContext.getCodebaseAnnotation());
    /*
     Grant the appropriate permissions to the service's classloader and
     protection domain.
     */
    Permission[] perms = createPermissionsInClassloader(cl);
    grantPermissions(cl, perms);

    /*
     Create the service's working directory and grant permissions to it.
    */
    createWorkDirectoryFor(env);
    grantPermissionsToWorkDirectoryFor(env);

    /*
     * Create a working context (work manager).
     */
    env.setWorkingContext(contextualWorkManager.createContext(env.getServiceName(), env.getClassLoader()));

    setupLiaisonConfiguration(env);
}

From source file:org.echocat.nodoodle.classloading.FileClassLoader.java

private Class<?> defineClass(String name, Resource resource) throws IOException {
    final int i = name.lastIndexOf('.');
    final URL packageUrl = resource.getPackageUrl();
    if (i != -1) {
        final String packageName = name.substring(0, i);
        // Check if package already loaded.
        final Package pkg = getPackage(packageName);
        final Manifest man = resource.getManifest();
        if (pkg != null) {
            // Package found, so check package sealing.
            if (pkg.isSealed()) {
                // Verify that code source URL is the same.
                if (!pkg.isSealed(packageUrl)) {
                    throw new SecurityException("sealing violation: package " + packageName + " is sealed");
                }/*from  www  .ja v a  2  s  .c o  m*/
            } else {
                // Make sure we are not attempting to seal the package
                // at this code source URL.
                if ((man != null) && isSealed(packageName, man)) {
                    throw new SecurityException(
                            "sealing violation: can't seal package " + packageName + ": already loaded");
                }
            }
        } else {
            if (man != null) {
                definePackage(packageName, man, packageUrl);
            } else {
                definePackage(packageName, null, null, null, null, null, null, null);
            }
        }
    }
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final InputStream inputStream = resource.openStream();
    try {
        IOUtils.copy(inputStream, baos);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
    final byte[] bytes = baos.toByteArray();
    final CodeSigner[] signers = resource.getCodeSigners();
    final CodeSource cs = new CodeSource(packageUrl, signers);
    return defineClass(name, bytes, 0, bytes.length, new ProtectionDomain(cs, new Permissions()));
}

From source file:org.eclipse.wb.internal.core.utils.reflect.ProjectClassLoader.java

private static void ensureCodeSource() {
    if (m_fakeCodeSource == null) {
        try {//  w  ww.j  a  va  2s  .  c  o m
            m_fakeCodeSource = new CodeSource(new URL("file:/"), (Certificate[]) null);
        } catch (Throwable e) {
        }
    }
}

From source file:org.gradle.internal.classloader.TransformingClassLoader.java

@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
    if (!shouldTransform(name)) {
        return super.findClass(name);
    }//from w  w w  .jav a 2  s .c o  m

    String resourceName = name.replace('.', '/') + ".class";
    URL resource = findResource(resourceName);

    byte[] bytes;
    CodeSource codeSource;
    try {
        if (resource != null) {
            bytes = loadBytecode(resource);
            bytes = transform(name, bytes);
            URL codeBase = ClasspathUtil.getClasspathForResource(resource, resourceName).toURI().toURL();
            codeSource = new CodeSource(codeBase, (Certificate[]) null);
        } else {
            bytes = generateMissingClass(name);
            codeSource = null;
        }
    } catch (Exception e) {
        throw new GradleException(String.format("Could not load class '%s' from %s.", name, resource), e);
    }

    if (bytes == null) {
        throw new ClassNotFoundException(name);
    }

    String packageName = StringUtils.substringBeforeLast(name, ".");
    Package p = getPackage(packageName);
    if (p == null) {
        definePackage(packageName, null, null, null, null, null, null, null);
    }
    return defineClass(name, bytes, 0, bytes.length, codeSource);
}

From source file:org.jboss.web.tomcat.tc5.TomcatDeployer.java

protected void performDeployInternal(String hostName, WebApplication appInfo, String warUrl,
        AbstractWebContainer.WebDescriptorParser webAppParser) throws Exception {

    WebMetaData metaData = appInfo.getMetaData();
    String ctxPath = metaData.getContextRoot();
    if (ctxPath.equals("/") || ctxPath.equals("/ROOT") || ctxPath.equals("")) {
        log.debug("deploy root context=" + ctxPath);
        ctxPath = "/";
        metaData.setContextRoot(ctxPath);
    }//from   ww  w  .ja va2 s.  c om

    log.info("deploy, ctxPath=" + ctxPath + ", warUrl=" + shortWarUrlFromServerHome(warUrl));

    URL url = new URL(warUrl);

    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    /* If we are using the jboss class loader we need to augment its path
    to include the WEB-INF/{lib,classes} dirs or else scoped class loading
    does not see the war level overrides. The call to setWarURL adds these
    paths to the deployment UCL.
    */
    Loader webLoader = null;
    if (config.isUseJBossWebLoader()) {
        WebCtxLoader jbossLoader = new WebCtxLoader(loader);
        jbossLoader.setWarURL(url);
        webLoader = jbossLoader;
    } else {
        String[] pkgs = config.getFilteredPackages();
        WebAppLoader jbossLoader = new WebAppLoader(loader, pkgs);
        jbossLoader.setDelegate(getJava2ClassLoadingCompliance());
        webLoader = jbossLoader;
    }

    // We need to establish the JNDI ENC prior to the start 
    // of the web container so that init on startup servlets are able 
    // to interact with their ENC. We hook into the context lifecycle 
    // events to be notified of the start of the
    // context as this occurs before the servlets are started.
    if (appInfo.getAppData() == null)
        webAppParser.parseWebAppDescriptors(loader, appInfo.getMetaData());

    appInfo.setName(url.getPath());
    appInfo.setClassLoader(loader);
    appInfo.setURL(url);

    String objectNameS = config.getCatalinaDomain() + ":j2eeType=WebModule,name=//"
            + ((hostName == null) ? "localhost" : hostName) + ctxPath + ",J2EEApplication=none,J2EEServer=none";

    ObjectName objectName = new ObjectName(objectNameS);

    if (server.isRegistered(objectName)) {
        log.debug("Already exists, destroying " + objectName);
        server.invoke(objectName, "destroy", new Object[] {}, new String[] {});
    }

    server.createMBean("org.apache.commons.modeler.BaseModelMBean", objectName,
            new Object[] { config.getContextClassName() }, new String[] { "java.lang.String" });

    // Find and set config file on the context
    // If WAR is packed, expand config file to temp folder
    String ctxConfig = null;
    try {
        ctxConfig = findConfig(url);
    } catch (IOException e) {
        log.debug("No " + CONTEXT_CONFIG_FILE + " in " + url, e);
    }

    server.setAttribute(objectName, new Attribute("docBase", url.getFile()));

    server.setAttribute(objectName, new Attribute("configFile", ctxConfig));

    server.setAttribute(objectName, new Attribute("defaultContextXml", "context.xml"));
    server.setAttribute(objectName, new Attribute("defaultWebXml", "conf/web.xml"));

    server.setAttribute(objectName, new Attribute("javaVMs", javaVMs));

    server.setAttribute(objectName, new Attribute("server", serverName));

    server.setAttribute(objectName, new Attribute("saveConfig", Boolean.FALSE));

    if (webLoader != null) {
        server.setAttribute(objectName, new Attribute("loader", webLoader));
    } else {
        server.setAttribute(objectName, new Attribute("parentClassLoader", loader));
    }

    server.setAttribute(objectName, new Attribute("delegate", new Boolean(getJava2ClassLoadingCompliance())));

    String[] jspCP = getCompileClasspath(loader);
    StringBuffer classpath = new StringBuffer();
    for (int u = 0; u < jspCP.length; u++) {
        String repository = jspCP[u];
        if (repository == null)
            continue;
        if (repository.startsWith("file://"))
            repository = repository.substring(7);
        else if (repository.startsWith("file:"))
            repository = repository.substring(5);
        else
            continue;
        if (repository == null)
            continue;
        // ok it is a file.  Make sure that is is a directory or jar file
        File fp = new File(repository);
        if (!fp.isDirectory()) {
            // if it is not a directory, try to open it as a zipfile.
            try {
                // avoid opening .xml files
                if (fp.getName().toLowerCase().endsWith(".xml"))
                    continue;

                ZipFile zip = new ZipFile(fp);
                zip.close();
            } catch (IOException e) {
                continue;
            }

        }
        if (u > 0)
            classpath.append(File.pathSeparator);
        classpath.append(repository);
    }

    server.setAttribute(objectName, new Attribute("compilerClasspath", classpath.toString()));

    // Set the session cookies flag according to metadata
    switch (metaData.getSessionCookies()) {
    case WebMetaData.SESSION_COOKIES_ENABLED:
        server.setAttribute(objectName, new Attribute("cookies", new Boolean(true)));
        log.debug("Enabling session cookies");
        break;
    case WebMetaData.SESSION_COOKIES_DISABLED:
        server.setAttribute(objectName, new Attribute("cookies", new Boolean(false)));
        log.debug("Disabling session cookies");
        break;
    default:
        log.debug("Using session cookies default setting");
    }

    // Add a valve to estalish the JACC context before authorization valves
    Certificate[] certs = null;
    CodeSource cs = new CodeSource(url, certs);
    JaccContextValve jaccValve = new JaccContextValve(metaData.getJaccContextID(), cs);
    server.invoke(objectName, "addValve", new Object[] { jaccValve },
            new String[] { "org.apache.catalina.Valve" });

    // Pass the metadata to the RunAsListener via a thread local
    RunAsListener.metaDataLocal.set(metaData);

    try {
        // Init the container; this will also start it
        server.invoke(objectName, "init", new Object[] {}, new String[] {});
    } finally {
        RunAsListener.metaDataLocal.set(null);
    }

    // make the context class loader known to the WebMetaData, ws4ee needs it
    // to instanciate service endpoint pojos that live in this webapp
    Loader ctxLoader = (Loader) server.getAttribute(objectName, "loader");
    metaData.setContextLoader(ctxLoader.getClassLoader());

    // Clustering
    if (metaData.getDistributable()) {
        // Try to initate clustering, fallback to standard if no clustering is available
        try {
            AbstractJBossManager manager = null;
            String managerClassName = config.getManagerClass();
            Class managerClass = Thread.currentThread().getContextClassLoader().loadClass(managerClassName);
            manager = (AbstractJBossManager) managerClass.newInstance();

            if (manager instanceof JBossCacheManager) {
                // TODO either deprecate snapshot mode or move its config
                // into jboss-web.xml.
                String snapshotMode = config.getSnapshotMode();
                int snapshotInterval = config.getSnapshotInterval();
                JBossCacheManager jbcm = (JBossCacheManager) manager;
                jbcm.setSnapshotMode(snapshotMode);
                jbcm.setSnapshotInterval(snapshotInterval);
            }

            String name = "//" + ((hostName == null) ? "localhost" : hostName) + ctxPath;
            manager.init(name, metaData, config.isUseJK(), config.isUseLocalCache());

            // Don't assign the manager to the context until all config
            // is done, or else the manager will be started without the config
            server.setAttribute(objectName, new Attribute("manager", manager));

            log.debug("Enabled clustering support for ctxPath=" + ctxPath);
        } catch (ClusteringNotSupportedException e) {
            // JBAS-3513 Just log a WARN, not an ERROR
            log.warn("Failed to setup clustering, clustering disabled. ClusteringNotSupportedException: "
                    + e.getMessage());
        } catch (NoClassDefFoundError ncdf) {
            // JBAS-3513 Just log a WARN, not an ERROR
            log.debug("Classes needed for clustered webapp unavailable", ncdf);
            log.warn("Failed to setup clustering, clustering disabled. NoClassDefFoundError: "
                    + ncdf.getMessage());
        } catch (Throwable t) {
            // TODO consider letting this through and fail the deployment
            log.error("Failed to setup clustering, clustering disabled. Exception: ", t);
        }
    }

    /* Add security association valve after the authorization
    valves so that the authenticated user may be associated with the
    request thread/session.
    */
    SecurityAssociationValve valve = new SecurityAssociationValve(metaData, config.getSecurityManagerService());
    valve.setSubjectAttributeName(config.getSubjectAttributeName());
    server.invoke(objectName, "addValve", new Object[] { valve }, new String[] { "org.apache.catalina.Valve" });

    // Retrieve the state, and throw an exception in case of a failure
    Integer state = (Integer) server.getAttribute(objectName, "state");
    if (state.intValue() != 1) {
        throw new DeploymentException("URL " + warUrl + " deployment failed");
    }

    appInfo.setAppData(objectName);

    // Create mbeans for the servlets
    DeploymentInfo di = webAppParser.getDeploymentInfo();
    di.deployedObject = objectName;
    ObjectName servletQuery = new ObjectName(config.getCatalinaDomain() + ":j2eeType=Servlet,WebModule="
            + objectName.getKeyProperty("name") + ",*");
    Iterator iterator = server.queryMBeans(servletQuery, null).iterator();
    while (iterator.hasNext()) {
        di.mbeans.add(((ObjectInstance) iterator.next()).getObjectName());
    }

    log.debug("Initialized: " + appInfo + " " + objectName);

}

From source file:org.jwebsocket.util.Tools.java

/**
 * Executes a privileged action in sandbox.
 *
 * @param aPermissions The security permissions.
 * @param aAction The action to execute/
 * @return//from  w  w w . ja  v a 2s  .  c o  m
 */
public static Object doPrivileged(PermissionCollection aPermissions, PrivilegedAction aAction) {
    ProtectionDomain lProtectionDomain = new ProtectionDomain(new CodeSource(null, (Certificate[]) null),
            aPermissions);
    AccessControlContext lSecureContext = new AccessControlContext(
            new ProtectionDomain[] { lProtectionDomain });

    return AccessController.doPrivileged(aAction, lSecureContext);
}