Search in sources :

Example 76 with CodeSource

use of java.security.CodeSource in project jaggery by wso2.

the class ModuleManager method initScripts.

@SuppressFBWarnings("PATH_TRAVERSAL_IN")
private void initScripts(Module moduleObject, Context cx, JavaScriptModule module, boolean isCustom) throws ScriptException {
    String name = null;
    String path = null;
    JavaScriptScript script;
    List scriptList = moduleObject.getScripts();
    Iterator itr = scriptList.iterator();
    while (itr.hasNext()) {
        try {
            //process methods
            org.jaggeryjs.jaggery.core.Script scriptObject = (org.jaggeryjs.jaggery.core.Script) itr.next();
            name = scriptObject.getName();
            path = scriptObject.getPath();
            script = new JavaScriptScript(name);
            Reader reader;
            final String fileName;
            ScriptCachingContext sctx;
            if (isCustom) {
                String filteredPath = filterPath(path);
                fileName = modulesDir + File.separator + module.getName() + File.separator + filterPath(path);
                reader = new FileReader(fileName);
                int endIndex = filteredPath.lastIndexOf(File.separator);
                sctx = new ScriptCachingContext(String.valueOf(MultitenantConstants.SUPER_TENANT_ID), '<' + module.getName() + '>', filteredPath.substring(0, endIndex), filteredPath.substring(endIndex));
            } else {
                reader = new InputStreamReader(ModuleManager.class.getClassLoader().getResourceAsStream(path));
                fileName = modulesDir + File.separator + name;
                int endIndex = path.lastIndexOf('/');
                sctx = new ScriptCachingContext(String.valueOf(MultitenantConstants.SUPER_TENANT_ID), "<<" + name + ">>", '/' + path.substring(0, endIndex), path.substring(endIndex));
            }
            CacheManager cacheManager = new CacheManager(null);
            sctx.setSecurityDomain(new RhinoSecurityDomain() {

                @SuppressFBWarnings("PATH_TRAVERSAL_IN")
                @Override
                public CodeSource getCodeSource() throws ScriptException {
                    try {
                        URL url = new File(fileName).getCanonicalFile().toURI().toURL();
                        return new CodeSource(url, (Certificate[]) null);
                    } catch (MalformedURLException e) {
                        throw new ScriptException(e);
                    } catch (IOException e) {
                        throw new ScriptException(e);
                    }
                }
            });
            sctx.setSourceModifiedTime(1);
            Script cachedScript = cacheManager.getScriptObject(reader, sctx);
            if (cachedScript == null) {
                cacheManager.cacheScript(reader, sctx);
                cachedScript = cacheManager.getScriptObject(reader, sctx);
            }
            script.setScript(cachedScript);
            module.addScript(script);
        } catch (FileNotFoundException e) {
            String msg = "Error executing script. Script cannot be found, name : " + name + ", path : " + path;
            log.error(msg, e);
            throw new ScriptException(msg, e);
        }
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) RhinoSecurityDomain(org.jaggeryjs.scriptengine.security.RhinoSecurityDomain) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) URL(java.net.URL) ScriptException(org.jaggeryjs.scriptengine.exceptions.ScriptException) Iterator(java.util.Iterator) CacheManager(org.jaggeryjs.scriptengine.cache.CacheManager) List(java.util.List) Script(org.mozilla.javascript.Script) ScriptCachingContext(org.jaggeryjs.scriptengine.cache.ScriptCachingContext) CodeSource(java.security.CodeSource) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Example 77 with CodeSource

use of java.security.CodeSource in project wildfly by wildfly.

the class JACCAuthorizationManager method hasPermission.

private boolean hasPermission(Account account, Deployment deployment, ServletInfo servletInfo, Permission permission) {
    CodeSource codeSource = servletInfo.getServletClass().getProtectionDomain().getCodeSource();
    ProtectionDomain domain = new ProtectionDomain(codeSource, null, null, getGrantedRoles(account, deployment));
    return hasPermission(domain, permission);
}
Also used : ProtectionDomain(java.security.ProtectionDomain) CodeSource(java.security.CodeSource)

Example 78 with CodeSource

use of java.security.CodeSource in project wildfly by wildfly.

the class ControllerServlet method service.

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
        Provider[] providers = Security.getProviders();
        for (int i = 0; i < providers.length; i++) {
            final Provider provider = providers[i];
            log.debug("Provider name: " + provider.getName());
            log.debug("Provider information: " + provider.getInfo());
            log.debug("Provider version: " + provider.getVersion());
            URL url = null;
            ProtectionDomain pd = provider.getClass().getProtectionDomain();
            if (pd != null) {
                CodeSource cs = pd.getCodeSource();
                if (cs != null) {
                    url = cs.getLocation();
                }
            }
            log.debug("Provider code base: " + url);
        }
        Cipher.getInstance("DummyAlg/DummyMode/DummyPadding", "DP");
        response.getWriter().write("ok");
        response.getWriter().close();
    } catch (Exception e) {
        throw new ServletException(e);
    }
}
Also used : ServletException(javax.servlet.ServletException) ProtectionDomain(java.security.ProtectionDomain) CodeSource(java.security.CodeSource) URL(java.net.URL) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) Provider(java.security.Provider) DummyProvider(org.jboss.as.test.integration.deployment.jcedeployment.provider.DummyProvider)

Example 79 with CodeSource

use of java.security.CodeSource in project lwjgl by LWJGL.

the class AppletLoader method updateClassPath.

/**
	 * Edits the ClassPath at runtime to include the jars
	 * that have just been downloaded and then adds the
	 * lwjgl natives folder property.
	 *
	 * @param path location where applet is stored
	 * @throws Exception if it fails to add classpath
	 */
protected void updateClassPath(final String path) throws Exception {
    setState(STATE_UPDATING_CLASSPATH);
    percentage = 95;
    URL[] urls = new URL[urlList.length];
    for (int i = 0; i < urlList.length; i++) {
        String file = new File(path, getJarName(urlList[i])).toURI().toString();
        // fix JVM bug where ! is not escaped
        file = file.replace("!", "%21");
        urls[i] = new URL(file);
    }
    // get AppletLoader certificates
    final Certificate[] certs = getCurrentCertificates();
    // detect if we are running on a mac and save result as boolean
    String osName = System.getProperty("os.name");
    final boolean isMacOS = (osName.startsWith("Mac") || osName.startsWith("Darwin"));
    // add downloaded jars to the classpath with required permissions
    classLoader = new URLClassLoader(urls) {

        protected PermissionCollection getPermissions(CodeSource codesource) {
            PermissionCollection perms = null;
            try {
                // no permissions
                perms = new Permissions();
                // if certificates match the AppletLoader certificates then we should be all set
                if (certificatesMatch(certs, codesource.getCertificates())) {
                    perms.add(new AllPermission());
                    return perms;
                }
                String host = getCodeBase().getHost();
                if (host != null && (host.length() > 0)) {
                    // add permission for downloaded jars to access host they were from
                    perms.add(new SocketPermission(host, "connect,accept"));
                } else if ("file".equals(codesource.getLocation().getProtocol())) {
                    // if running locally add file permission
                    String path = codesource.getLocation().getFile().replace('/', File.separatorChar);
                    perms.add(new FilePermission(path, "read"));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return perms;
        }

        // allow non lwjgl native to be found from cache directory
        protected String findLibrary(String libname) {
            String libPath = path + "natives" + File.separator + LWJGLUtil.mapLibraryName(libname);
            if (new File(libPath).exists()) {
                return libPath;
            }
            return super.findLibrary(libname);
        }
    };
    debug_sleep(2000);
    // unload natives loaded by a previous instance of this lwjgl applet
    unloadNatives(path);
    // add natives files path to native class path
    System.setProperty("org.lwjgl.librarypath", path + "natives");
    // Make sure jinput knows about the new path too
    System.setProperty("net.java.games.input.librarypath", path + "natives");
    // set the library path, useful for non lwjgl natives
    System.setProperty("java.library.path", path + "natives");
    // mark natives as loaded
    natives_loaded = true;
}
Also used : PermissionCollection(java.security.PermissionCollection) SocketPermission(java.net.SocketPermission) CodeSource(java.security.CodeSource) FilePermission(java.io.FilePermission) URL(java.net.URL) AccessControlException(java.security.AccessControlException) IOException(java.io.IOException) URLClassLoader(java.net.URLClassLoader) Permissions(java.security.Permissions) AllPermission(java.security.AllPermission) JarFile(java.util.jar.JarFile) ZipFile(java.util.zip.ZipFile) File(java.io.File) Certificate(java.security.cert.Certificate)

Example 80 with CodeSource

use of java.security.CodeSource in project gerrit by GerritCodeReview.

the class GerritLauncher method locateMyArchive.

private static File locateMyArchive() throws FileNotFoundException {
    final ClassLoader myCL = GerritLauncher.class.getClassLoader();
    final String myName = GerritLauncher.class.getName().replace('.', '/') + ".class";
    final URL myClazz = myCL.getResource(myName);
    if (myClazz == null) {
        throw new FileNotFoundException("Cannot find JAR: no " + myName);
    }
    //
    try {
        JarFile jar = ((JarURLConnection) myClazz.openConnection()).getJarFile();
        File path = new File(jar.getName());
        if (path.isFile()) {
            return path;
        }
    } catch (Exception e) {
    // Nope, that didn't work. Try a different method.
    //
    }
    //
    if ("file".equals(myClazz.getProtocol())) {
        final File path = new File(myClazz.getPath());
        if (path.isFile() && path.getParentFile().isDirectory()) {
            throw new FileNotFoundException(NOT_ARCHIVED);
        }
    }
    // The CodeSource might be able to give us the source as a stream.
    // If so, copy it to a local file so we have random access to it.
    //
    final CodeSource src = GerritLauncher.class.getProtectionDomain().getCodeSource();
    if (src != null) {
        try (InputStream in = src.getLocation().openStream()) {
            final File tmp = createTempFile("gerrit_", ".zip");
            try (OutputStream out = Files.newOutputStream(tmp.toPath())) {
                final byte[] buf = new byte[4096];
                int n;
                while ((n = in.read(buf, 0, buf.length)) > 0) {
                    out.write(buf, 0, n);
                }
            }
            return tmp;
        } catch (IOException e) {
        // Nope, that didn't work.
        //
        }
    }
    throw new FileNotFoundException("Cannot find local copy of JAR");
}
Also used : JarURLConnection(java.net.JarURLConnection) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) JarFile(java.util.jar.JarFile) CodeSource(java.security.CodeSource) URL(java.net.URL) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) InvocationTargetException(java.lang.reflect.InvocationTargetException) URLClassLoader(java.net.URLClassLoader) JarFile(java.util.jar.JarFile) ZipFile(java.util.zip.ZipFile) File(java.io.File)

Aggregations

CodeSource (java.security.CodeSource)104 URL (java.net.URL)49 ProtectionDomain (java.security.ProtectionDomain)39 File (java.io.File)30 IOException (java.io.IOException)20 Certificate (java.security.cert.Certificate)17 JarFile (java.util.jar.JarFile)13 PermissionCollection (java.security.PermissionCollection)12 URI (java.net.URI)11 URISyntaxException (java.net.URISyntaxException)11 Permissions (java.security.Permissions)11 Policy (java.security.Policy)10 FilePermission (java.io.FilePermission)7 InputStream (java.io.InputStream)6 AccessControlContext (java.security.AccessControlContext)6 MalformedURLException (java.net.MalformedURLException)5 Permission (java.security.Permission)4 JarEntry (java.util.jar.JarEntry)4 GroovyClassLoader (groovy.lang.GroovyClassLoader)3 URLClassLoader (java.net.URLClassLoader)3