2437 lines · 93.5 KB · Java
RawDownload
             * cases where the user has a single unified policyfile             * with both java policy entries and auth entries             */             boolean loaded_one = initPolicyFile(POLICY, POLICY_URL, newInfo);            // To maintain strict backward compatibility            // we load the static policy only if POLICY load failed            if (!loaded_one) {                // use static policy if all else fails                initStaticPolicy(newInfo);            }             initPolicyFile(AUTH_POLICY, AUTH_POLICY_URL, newInfo);        }    }     private boolean initPolicyFile(final String propname, final String urlname,                                final PolicyInfo newInfo) {        Boolean loadedPolicy =            AccessController.doPrivileged(new PrivilegedAction<Boolean>() {            public Boolean run() {                boolean loaded_policy = false;                 if (allowSystemProperties) {                    String extra_policy = System.getProperty(propname);                    if (extra_policy != null) {                        boolean overrideAll = false;                        if (extra_policy.startsWith("=")) {                            overrideAll = true;                            extra_policy = extra_policy.substring(1);                        }                        try {                            extra_policy =                                PropertyExpander.expand(extra_policy);                            URL policyURL;                             File policyFile = new File(extra_policy);                            if (policyFile.exists()) {                                policyURL = ParseUtil.fileToEncodedURL                                    (new File(policyFile.getCanonicalPath()));                            } else {                                policyURL = new URL(extra_policy);                            }                            if (debug != null)                                debug.println("reading "+policyURL);                            if (init(policyURL, newInfo))                                loaded_policy = true;                        } catch (Exception e) {                            // ignore.                            if (debug != null) {                                debug.println("caught exception: "+e);                            }                        }                        if (overrideAll) {                            if (debug != null) {                                debug.println("overriding other policies!");                            }                            return Boolean.valueOf(loaded_policy);                        }                    }                }                 int n = 1;                String policy_uri;                 while ((policy_uri = Security.getProperty(urlname+n)) != null) {                    try {                        URL policy_url = null;                        String expanded_uri = PropertyExpander.expand                                (policy_uri).replace(File.separatorChar, '/');                         if (policy_uri.startsWith("file:${java.home}/") ||                            policy_uri.startsWith("file:${user.home}/")) {                             // this special case accommodates                            // the situation java.home/user.home                            // expand to a single slash, resulting in                            // a file://foo URI                            policy_url = new File                                (expanded_uri.substring(5)).toURI().toURL();                        } else {                            policy_url = new URI(expanded_uri).toURL();                        }                         if (debug != null)                            debug.println("reading "+policy_url);                        if (init(policy_url, newInfo))                            loaded_policy = true;                    } catch (Exception e) {                        if (debug != null) {                            debug.println("error reading policy "+e);                            e.printStackTrace();                        }                        // ignore that policy                    }                    n++;                }                return Boolean.valueOf(loaded_policy);            }        });         return loadedPolicy.booleanValue();    }     /**     * Reads a policy configuration into the Policy object using a     * Reader object.     *     * @param policyFile the policy Reader object.     */    private boolean init(URL policy, PolicyInfo newInfo) {        boolean success = false;        PolicyParser pp = new PolicyParser(expandProperties);        InputStreamReader isr = null;        try {             // read in policy using UTF-8 by default            //            // check non-standard system property to see if            // the default encoding should be used instead             if (notUtf8) {                isr = new InputStreamReader                                (PolicyUtil.getInputStream(policy));            } else {                isr = new InputStreamReader                                (PolicyUtil.getInputStream(policy), "UTF-8");            }             pp.read(isr);             KeyStore keyStore = null;            try {                keyStore = PolicyUtil.getKeyStore                                (policy,                                pp.getKeyStoreUrl(),                                pp.getKeyStoreType(),                                pp.getKeyStoreProvider(),                                pp.getStorePassURL(),                                debug);            } catch (Exception e) {                // ignore, treat it like we have no keystore                if (debug != null) {                    e.printStackTrace();                }            }             Enumeration<PolicyParser.GrantEntry> enum_ = pp.grantElements();            while (enum_.hasMoreElements()) {                PolicyParser.GrantEntry ge = enum_.nextElement();                addGrantEntry(ge, keyStore, newInfo);            }        } catch (PolicyParser.ParsingException pe) {            MessageFormat form = new MessageFormat(ResourcesMgr.getString                (POLICY + ".error.parsing.policy.message"));            Object[] source = {policy, pe.getLocalizedMessage()};            System.err.println(form.format(source));            if (debug != null)                pe.printStackTrace();         } catch (Exception e) {            if (debug != null) {                debug.println("error parsing "+policy);                debug.println(e.toString());                e.printStackTrace();            }        } finally {            if (isr != null) {                try {                    isr.close();                    success = true;                } catch (IOException e) {                    // ignore the exception                }            } else {                success = true;            }        }         return success;    }     private void initStaticPolicy(final PolicyInfo newInfo) {        AccessController.doPrivileged(new PrivilegedAction<Void>() {            public Void run() {                PolicyEntry pe = new PolicyEntry(new CodeSource(null,                    (Certificate[]) null));                pe.add(SecurityConstants.LOCAL_LISTEN_PERMISSION);                pe.add(new PropertyPermission("java.version",                    SecurityConstants.PROPERTY_READ_ACTION));                pe.add(new PropertyPermission("java.vendor",                    SecurityConstants.PROPERTY_READ_ACTION));                pe.add(new PropertyPermission("java.vendor.url",                    SecurityConstants.PROPERTY_READ_ACTION));                pe.add(new PropertyPermission("java.class.version",                    SecurityConstants.PROPERTY_READ_ACTION));                pe.add(new PropertyPermission("os.name",                    SecurityConstants.PROPERTY_READ_ACTION));                pe.add(new PropertyPermission("os.version",                    SecurityConstants.PROPERTY_READ_ACTION));                pe.add(new PropertyPermission("os.arch",                    SecurityConstants.PROPERTY_READ_ACTION));                pe.add(new PropertyPermission("file.separator",                    SecurityConstants.PROPERTY_READ_ACTION));                pe.add(new PropertyPermission("path.separator",                    SecurityConstants.PROPERTY_READ_ACTION));                pe.add(new PropertyPermission("line.separator",                    SecurityConstants.PROPERTY_READ_ACTION));                pe.add(new PropertyPermission                                ("java.specification.version",                                    SecurityConstants.PROPERTY_READ_ACTION));                pe.add(new PropertyPermission                                ("java.specification.vendor",                                    SecurityConstants.PROPERTY_READ_ACTION));                pe.add(new PropertyPermission                                ("java.specification.name",                                    SecurityConstants.PROPERTY_READ_ACTION));                pe.add(new PropertyPermission                                ("java.vm.specification.version",                                    SecurityConstants.PROPERTY_READ_ACTION));                pe.add(new PropertyPermission                                ("java.vm.specification.vendor",                                    SecurityConstants.PROPERTY_READ_ACTION));                pe.add(new PropertyPermission                                ("java.vm.specification.name",                                    SecurityConstants.PROPERTY_READ_ACTION));                pe.add(new PropertyPermission("java.vm.version",                    SecurityConstants.PROPERTY_READ_ACTION));                pe.add(new PropertyPermission("java.vm.vendor",                    SecurityConstants.PROPERTY_READ_ACTION));                pe.add(new PropertyPermission("java.vm.name",                    SecurityConstants.PROPERTY_READ_ACTION));                 // No need to sync because noone has access to newInfo yet                newInfo.policyEntries.add(pe);                 // Add AllPermissions for standard extensions                String[] extCodebases = PolicyParser.parseExtDirs(                    PolicyParser.EXTDIRS_EXPANSION, 0);                if (extCodebases != null && extCodebases.length > 0) {                    for (int i = 0; i < extCodebases.length; i++) {                        try {                            pe = new PolicyEntry(canonicalizeCodebase(                                new CodeSource(new URL(extCodebases[i]),                                    (Certificate[]) null), false ));                            pe.add(SecurityConstants.ALL_PERMISSION);                             // No need to sync because noone has access to                            // newInfo yet                            newInfo.policyEntries.add(pe);                        } catch (Exception e) {                            // this is probably bad (though not dangerous).                            // What should we do?                        }                    }                }                return null;            }        });    }     /**     * Given a GrantEntry, create a codeSource.     *     * @return null if signedBy alias is not recognized     */    private CodeSource getCodeSource(PolicyParser.GrantEntry ge, KeyStore keyStore,        PolicyInfo newInfo) throws java.net.MalformedURLException    {        Certificate[] certs = null;        if (ge.signedBy != null) {            certs = getCertificates(keyStore, ge.signedBy, newInfo);            if (certs == null) {                // we don't have a key for this alias,                // just return                if (debug != null) {                    debug.println("  -- No certs for alias '" +                                       ge.signedBy + "' - ignoring entry");                }                return null;            }        }         URL location;         if (ge.codeBase != null)            location = new URL(ge.codeBase);        else            location = null;         return (canonicalizeCodebase(new CodeSource(location, certs),false));    }     /**     * Add one policy entry to the list.     */    private void addGrantEntry(PolicyParser.GrantEntry ge,                               KeyStore keyStore, PolicyInfo newInfo) {         if (debug != null) {            debug.println("Adding policy entry: ");            debug.println("  signedBy " + ge.signedBy);            debug.println("  codeBase " + ge.codeBase);            if (ge.principals != null && ge.principals.size() > 0) {                ListIterator<PolicyParser.PrincipalEntry> li =                                                ge.principals.listIterator();                while (li.hasNext()) {                    PolicyParser.PrincipalEntry pppe = li.next();                debug.println("  " + pppe.toString());                }            }        }         try {            CodeSource codesource = getCodeSource(ge, keyStore, newInfo);            // skip if signedBy alias was unknown...            if (codesource == null) return;             // perform keystore alias principal replacement.            // for example, if alias resolves to X509 certificate,            // replace principal with:  <X500Principal class>  <SubjectDN>            // -- skip if alias is unknown            if (replacePrincipals(ge.principals, keyStore) == false)                return;            PolicyEntry entry = new PolicyEntry(codesource, ge.principals);            Enumeration<PolicyParser.PermissionEntry> enum_ =                                                ge.permissionElements();            while (enum_.hasMoreElements()) {                PolicyParser.PermissionEntry pe = enum_.nextElement();                 try {                    // perform ${{ ... }} expansions within permission name                    expandPermissionName(pe, keyStore);                     // XXX special case PrivateCredentialPermission-SELF                    Permission perm;                    if (pe.permission.equals                        ("javax.security.auth.PrivateCredentialPermission") &&                        pe.name.endsWith(" self")) {                        pe.name = pe.name.substring(0, pe.name.indexOf("self"))                                + SELF;                    }                    // check for self                    if (pe.name != null && pe.name.indexOf(SELF) != -1) {                        // Create a "SelfPermission" , it could be an                        // an unresolved permission which will be resolved                        // when implies is called                        // Add it to entry                        Certificate certs[];                        if (pe.signedBy != null) {                            certs = getCertificates(keyStore,                                                    pe.signedBy,                                                    newInfo);                        } else {                            certs = null;                        }                        perm = new SelfPermission(pe.permission,                                                  pe.name,                                                  pe.action,                                                  certs);                    } else {                        perm = getInstance(pe.permission,                                           pe.name,                                           pe.action);                    }                    entry.add(perm);                    if (debug != null) {                        debug.println("  "+perm);                    }                } catch (ClassNotFoundException cnfe) {                    Certificate certs[];                    if (pe.signedBy != null) {                        certs = getCertificates(keyStore,                                                pe.signedBy,                                                newInfo);                    } else {                        certs = null;                    }                     // only add if we had no signer or we had a                    // a signer and found the keys for it.                    if (certs != null || pe.signedBy == null) {                        Permission perm = new UnresolvedPermission(                                                  pe.permission,                                                  pe.name,                                                  pe.action,                                                  certs);                        entry.add(perm);                        if (debug != null) {                            debug.println("  "+perm);                        }                    }                } catch (java.lang.reflect.InvocationTargetException ite) {                    MessageFormat form = new MessageFormat                        (ResourcesMgr.getString                         (POLICY +                          ".error.adding.Permission.perm.message"));                    Object[] source = {pe.permission,                                       ite.getTargetException().toString()};                    System.err.println(form.format(source));                } catch (Exception e) {                    MessageFormat form = new MessageFormat                        (ResourcesMgr.getString                         (POLICY +                          ".error.adding.Permission.perm.message"));                    Object[] source = {pe.permission,                                       e.toString()};                    System.err.println(form.format(source));                }            }             // No need to sync because noone has access to newInfo yet            newInfo.policyEntries.add(entry);        } catch (Exception e) {            MessageFormat form = new MessageFormat(ResourcesMgr.getString                                         (POLICY                                         + ".error.adding.Entry.message"));            Object[] source = {e.toString()};            System.err.println(form.format(source));        }        if (debug != null)            debug.println();    }     /**     * Returns a new Permission object of the given Type. The Permission is     * created by getting the     * Class object using the <code>Class.forName</code> method, and using     * the reflection API to invoke the (String name, String actions)     * constructor on the     * object.     *     * @param type the type of Permission being created.     * @param name the name of the Permission being created.     * @param actions the actions of the Permission being created.     *     * @exception  ClassNotFoundException  if the particular Permission     *             class could not be found.     *     * @exception  IllegalAccessException  if the class or initializer is     *               not accessible.     *     * @exception  InstantiationException  if getInstance tries to     *               instantiate an abstract class or an interface, or if the     *               instantiation fails for some other reason.     *     * @exception  NoSuchMethodException if the (String, String) constructor     *               is not found.     *     * @exception  InvocationTargetException if the underlying Permission     *               constructor throws an exception.     *     */     private static final Permission getInstance(String type,                                    String name,                                    String actions)        throws ClassNotFoundException,               InstantiationException,               IllegalAccessException,               NoSuchMethodException,               InvocationTargetException    {        //XXX we might want to keep a hash of created factories...        Class<?> pc = Class.forName(type);        Permission answer = getKnownInstance(pc, name, actions);        if (answer != null) {            return answer;        }         if (name == null && actions == null) {            try {                Constructor<?> c = pc.getConstructor(PARAMS0);                return (Permission) c.newInstance(new Object[] {});            } catch (NoSuchMethodException ne) {                try {                    Constructor<?> c = pc.getConstructor(PARAMS1);                    return (Permission) c.newInstance(                              new Object[] { name});                } catch (NoSuchMethodException ne1 ) {                    Constructor<?> c = pc.getConstructor(PARAMS2);                    return (Permission) c.newInstance(                        new Object[] { name, actions });                }            }        } else {            if (name != null && actions == null) {                try {                    Constructor<?> c = pc.getConstructor(PARAMS1);                    return (Permission) c.newInstance(new Object[] { name});                } catch (NoSuchMethodException ne) {                    Constructor<?> c = pc.getConstructor(PARAMS2);                    return (Permission) c.newInstance(                          new Object[] { name, actions });                }            } else {                Constructor<?> c = pc.getConstructor(PARAMS2);                return (Permission) c.newInstance(                      new Object[] { name, actions });             }

Lines 501–1000 of 2437. Previous lines