Search in sources :

Example 41 with Permission

use of java.security.Permission in project Bytecoder by mirkosertic.

the class FactoryURLClassLoader method getPermissions.

/**
 * Returns the permissions for the given codesource object.
 * The implementation of this method first calls super.getPermissions
 * and then adds permissions based on the URL of the codesource.
 * <p>
 * If the protocol of this URL is "jar", then the permission granted
 * is based on the permission that is required by the URL of the Jar
 * file.
 * <p>
 * If the protocol is "file" and there is an authority component, then
 * permission to connect to and accept connections from that authority
 * may be granted. If the protocol is "file"
 * and the path specifies a file, then permission to read that
 * file is granted. If protocol is "file" and the path is
 * a directory, permission is granted to read all files
 * and (recursively) all files and subdirectories contained in
 * that directory.
 * <p>
 * If the protocol is not "file", then permission
 * to connect to and accept connections from the URL's host is granted.
 * @param codesource the codesource
 * @exception NullPointerException if {@code codesource} is {@code null}.
 * @return the permissions granted to the codesource
 */
protected PermissionCollection getPermissions(CodeSource codesource) {
    PermissionCollection perms = super.getPermissions(codesource);
    URL url = codesource.getLocation();
    Permission p;
    URLConnection urlConnection;
    try {
        urlConnection = url.openConnection();
        p = urlConnection.getPermission();
    } catch (java.io.IOException ioe) {
        p = null;
        urlConnection = null;
    }
    if (p instanceof FilePermission) {
        // if the permission has a separator char on the end,
        // it means the codebase is a directory, and we need
        // to add an additional permission to read recursively
        String path = p.getName();
        if (path.endsWith(File.separator)) {
            path += "-";
            p = new FilePermission(path, SecurityConstants.FILE_READ_ACTION);
        }
    } else if ((p == null) && (url.getProtocol().equals("file"))) {
        String path = url.getFile().replace('/', File.separatorChar);
        path = ParseUtil.decode(path);
        if (path.endsWith(File.separator))
            path += "-";
        p = new FilePermission(path, SecurityConstants.FILE_READ_ACTION);
    } else {
        /**
         * Not loading from a 'file:' URL so we want to give the class
         * permission to connect to and accept from the remote host
         * after we've made sure the host is the correct one and is valid.
         */
        URL locUrl = url;
        if (urlConnection instanceof JarURLConnection) {
            locUrl = ((JarURLConnection) urlConnection).getJarFileURL();
        }
        String host = locUrl.getHost();
        if (host != null && (host.length() > 0))
            p = new SocketPermission(host, SecurityConstants.SOCKET_CONNECT_ACCEPT_ACTION);
    }
    if (p != null) {
        final SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            final Permission fp = p;
            AccessController.doPrivileged(new PrivilegedAction<>() {

                public Void run() throws SecurityException {
                    sm.checkPermission(fp);
                    return null;
                }
            }, acc);
        }
        perms.add(p);
    }
    return perms;
}
Also used : PermissionCollection(java.security.PermissionCollection) IOException(java.io.IOException) FilePermission(java.io.FilePermission) FilePermission(java.io.FilePermission) Permission(java.security.Permission)

Example 42 with Permission

use of java.security.Permission in project Bytecoder by mirkosertic.

the class SubjectDomainCombiner method combineJavaxPolicy.

/**
 * Use the javax.security.auth.Policy implementation
 */
private ProtectionDomain[] combineJavaxPolicy(ProtectionDomain[] currentDomains, ProtectionDomain[] assignedDomains) {
    if (!allowCaching) {
        java.security.AccessController.doPrivileged(new PrivilegedAction<Void>() {

            @SuppressWarnings("deprecation")
            public Void run() {
                // Call refresh only caching is disallowed
                javax.security.auth.Policy.getPolicy().refresh();
                return null;
            }
        });
    }
    int cLen = (currentDomains == null ? 0 : currentDomains.length);
    int aLen = (assignedDomains == null ? 0 : assignedDomains.length);
    // the ProtectionDomains for the new AccessControlContext
    // that we will return
    ProtectionDomain[] newDomains = new ProtectionDomain[cLen + aLen];
    synchronized (cachedPDs) {
        if (!subject.isReadOnly() && !subject.getPrincipals().equals(principalSet)) {
            // if the Subject was mutated, clear the PD cache
            Set<Principal> newSet = subject.getPrincipals();
            synchronized (newSet) {
                principalSet = new java.util.HashSet<Principal>(newSet);
            }
            principals = principalSet.toArray(new Principal[principalSet.size()]);
            cachedPDs.clear();
            if (debug != null) {
                debug.println("Subject mutated - clearing cache");
            }
        }
        for (int i = 0; i < cLen; i++) {
            ProtectionDomain pd = currentDomains[i];
            ProtectionDomain subjectPd = cachedPDs.getValue(pd);
            if (subjectPd == null) {
                if (pd.staticPermissionsOnly()) {
                    // keep static ProtectionDomain objects static
                    subjectPd = pd;
                } else {
                    // XXX
                    // we must first add the original permissions.
                    // that way when we later add the new JAAS permissions,
                    // any unresolved JAAS-related permissions will
                    // automatically get resolved.
                    // get the original perms
                    Permissions perms = new Permissions();
                    PermissionCollection coll = pd.getPermissions();
                    java.util.Enumeration<Permission> e;
                    if (coll != null) {
                        synchronized (coll) {
                            e = coll.elements();
                            while (e.hasMoreElements()) {
                                Permission newPerm = e.nextElement();
                                perms.add(newPerm);
                            }
                        }
                    }
                    // get perms from the policy
                    final java.security.CodeSource finalCs = pd.getCodeSource();
                    final Subject finalS = subject;
                    PermissionCollection newPerms = java.security.AccessController.doPrivileged(new PrivilegedAction<PermissionCollection>() {

                        @SuppressWarnings("deprecation")
                        public PermissionCollection run() {
                            return javax.security.auth.Policy.getPolicy().getPermissions(finalS, finalCs);
                        }
                    });
                    // avoiding duplicates
                    synchronized (newPerms) {
                        e = newPerms.elements();
                        while (e.hasMoreElements()) {
                            Permission newPerm = e.nextElement();
                            if (!perms.implies(newPerm)) {
                                perms.add(newPerm);
                                if (debug != null)
                                    debug.println("Adding perm " + newPerm + "\n");
                            }
                        }
                    }
                    subjectPd = new ProtectionDomain(finalCs, perms, pd.getClassLoader(), principals);
                }
                if (allowCaching)
                    cachedPDs.putValue(pd, subjectPd);
            }
            newDomains[i] = subjectPd;
        }
    }
    if (debug != null) {
        debug.println("updated current: ");
        for (int i = 0; i < cLen; i++) {
            debug.println("\tupdated[" + i + "] = " + newDomains[i]);
        }
    }
    // now add on the assigned domains
    if (aLen > 0) {
        System.arraycopy(assignedDomains, 0, newDomains, cLen, aLen);
    }
    if (debug != null) {
        if (newDomains == null || newDomains.length == 0) {
            debug.println("returning null");
        } else {
            debug.println("combinedDomains: ");
            for (int i = 0; i < newDomains.length; i++) {
                debug.println("newDomain " + i + ": " + newDomains[i].toString());
            }
        }
    }
    // return the new ProtectionDomains
    if (newDomains == null || newDomains.length == 0) {
        return null;
    } else {
        return newDomains;
    }
}
Also used : ProtectionDomain(java.security.ProtectionDomain) PermissionCollection(java.security.PermissionCollection) Permissions(java.security.Permissions) Permission(java.security.Permission) Principal(java.security.Principal)

Example 43 with Permission

use of java.security.Permission in project Bytecoder by mirkosertic.

the class PolicyPermissions method getPermissions.

/**
 * Examines the global policy for the specified CodeSource, and
 * creates a PermissionCollection object with
 * the set of permissions for that principal's protection domain.
 *
 * @param permissions the permissions to populate
 * @param codesource the codesource associated with the caller.
 * This encapsulates the original location of the code (where the code
 * came from) and the public key(s) of its signer.
 *
 * @return the set of permissions according to the policy.
 */
Permissions getPermissions(final Permissions perms, final CodeSource cs) {
    if (!initialized) {
        init();
    }
    final CodeSource[] codesource = { null };
    codesource[0] = canonicalizeCodebase(cs, true);
    if (debug != null) {
        debug.println("evaluate(" + codesource[0] + ")\n");
    }
    for (int i = 0; i < policyEntries.size(); i++) {
        PolicyEntry entry = policyEntries.elementAt(i);
        if (debug != null) {
            debug.println("PolicyFile CodeSource implies: " + entry.codesource.toString() + "\n\n" + "\t" + codesource[0].toString() + "\n\n");
        }
        if (entry.codesource.implies(codesource[0])) {
            for (int j = 0; j < entry.permissions.size(); j++) {
                Permission p = entry.permissions.elementAt(j);
                if (debug != null) {
                    debug.println("  granting " + p);
                }
                if (!addSelfPermissions(p, entry.codesource, codesource[0], perms)) {
                    // we could check for duplicates
                    // before adding new permissions,
                    // but the SubjectDomainCombiner
                    // already checks for duplicates later
                    perms.add(p);
                }
            }
        }
    }
    if (!ignoreIdentityScope) {
        Certificate[] certs = codesource[0].getCertificates();
        if (certs != null) {
            for (int k = 0; k < certs.length; k++) {
                if (aliasMapping.get(certs[k]) == null && checkForTrustedIdentity(certs[k])) {
                    // checkForTrustedIdentity added it
                    // to the policy for us. next time
                    // around we'll find it. This time
                    // around we need to add it.
                    perms.add(new java.security.AllPermission());
                }
            }
        }
    }
    return perms;
}
Also used : UnresolvedPermission(java.security.UnresolvedPermission) PrivateCredentialPermission(javax.security.auth.PrivateCredentialPermission) Permission(java.security.Permission) CodeSource(java.security.CodeSource) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 44 with Permission

use of java.security.Permission in project Bytecoder by mirkosertic.

the class PolicyPermissions method init.

private synchronized void init() {
    if (notInit) {
        if (perms == null) {
            perms = new Permissions();
        }
        if (additionalPerms != null) {
            Enumeration<Permission> e = additionalPerms.elements();
            while (e.hasMoreElements()) {
                perms.add(e.nextElement());
            }
            additionalPerms = null;
        }
        policy.getPermissions(perms, codesource);
        notInit = false;
    }
}
Also used : Permissions(java.security.Permissions) UnresolvedPermission(java.security.UnresolvedPermission) PrivateCredentialPermission(javax.security.auth.PrivateCredentialPermission) Permission(java.security.Permission)

Example 45 with Permission

use of java.security.Permission in project Bytecoder by mirkosertic.

the class URLClassPath method check.

/*
     * Check whether the resource URL should be returned.
     * Throw exception on failure.
     * Called internally within this file.
     */
public static void check(URL url) throws IOException {
    SecurityManager security = System.getSecurityManager();
    if (security != null) {
        URLConnection urlConnection = url.openConnection();
        Permission perm = urlConnection.getPermission();
        if (perm != null) {
            try {
                security.checkPermission(perm);
            } catch (SecurityException se) {
                // security managers
                if ((perm instanceof java.io.FilePermission) && perm.getActions().indexOf("read") != -1) {
                    security.checkRead(perm.getName());
                } else if ((perm instanceof java.net.SocketPermission) && perm.getActions().indexOf("connect") != -1) {
                    URL locUrl = url;
                    if (urlConnection instanceof JarURLConnection) {
                        locUrl = ((JarURLConnection) urlConnection).getJarFileURL();
                    }
                    security.checkConnect(locUrl.getHost(), locUrl.getPort());
                } else {
                    throw se;
                }
            }
        }
    }
}
Also used : JarURLConnection(java.net.JarURLConnection) Permission(java.security.Permission) HttpURLConnection(java.net.HttpURLConnection) URLConnection(java.net.URLConnection) JarURLConnection(java.net.JarURLConnection) URL(java.net.URL)

Aggregations

Permission (java.security.Permission)236 Test (org.junit.Test)55 PermissionCollection (java.security.PermissionCollection)39 FilePermission (java.io.FilePermission)38 Permissions (java.security.Permissions)31 ProtectionDomain (java.security.ProtectionDomain)27 IOException (java.io.IOException)20 AllPermission (java.security.AllPermission)20 QuickTest (com.hazelcast.test.annotation.QuickTest)17 File (java.io.File)17 URL (java.net.URL)16 AccessControlException (java.security.AccessControlException)14 Principal (java.security.Principal)14 PropertyPermission (java.util.PropertyPermission)14 Policy (java.security.Policy)13 MBeanPermission (javax.management.MBeanPermission)13 AccessControlContext (java.security.AccessControlContext)12 CodeSource (java.security.CodeSource)11 SecurityPermission (java.security.SecurityPermission)11 ArrayList (java.util.ArrayList)10