4131 lines · 144.1 KB · Java
RawDownload
/* * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation.  Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.security.tools.policytool; import java.io.*;import java.util.LinkedList;import java.util.ListIterator;import java.util.Vector;import java.util.Enumeration;import java.net.URL;import java.net.MalformedURLException;import java.lang.reflect.*;import java.text.Collator;import java.text.MessageFormat;import sun.security.util.PropertyExpander;import sun.security.util.PropertyExpander.ExpandException;import java.awt.*;import java.awt.event.*;import java.security.cert.Certificate;import java.security.cert.CertificateException;import java.security.*;import sun.security.provider.*;import sun.security.util.PolicyUtil;import javax.security.auth.x500.X500Principal; /** * PolicyTool may be used by users and administrators to configure the * overall java security policy (currently stored in the policy file). * Using PolicyTool administrators may add and remove policies from * the policy file. <p> * * @see java.security.Policy * @since   1.2 */ public class PolicyTool {     // for i18n    static final java.util.ResourceBundle rb =        java.util.ResourceBundle.getBundle("sun.security.util.Resources");    static final Collator collator = Collator.getInstance();    static {        // this is for case insensitive string comparisons        collator.setStrength(Collator.PRIMARY);    };     // anyone can add warnings    Vector<String> warnings;    boolean newWarning = false;     // set to true if policy modified.    // this way upon exit we know if to ask the user to save changes    boolean modified = false;     private static final boolean testing = false;    private static final Class[] TWOPARAMS = { String.class, String.class };    private static final Class[] ONEPARAMS = { String.class };    private static final Class[] NOPARAMS  = {};    /*     * All of the policy entries are read in from the     * policy file and stored here.  Updates to the policy entries     * using addEntry() and removeEntry() are made here.  To ultimately save     * the policy entries back to the policy file, the SavePolicy button     * must be clicked.     **/    private static String policyFileName = null;    private Vector<PolicyEntry> policyEntries = null;    private PolicyParser parser = null;     /* The public key alias information is stored here.  */    private KeyStore keyStore = null;    private String keyStoreName = " ";    private String keyStoreType = " ";    private String keyStoreProvider = " ";    private String keyStorePwdURL = " ";     /* standard PKCS11 KeyStore type */    private static final String P11KEYSTORE = "PKCS11";     /* reserved word for PKCS11 KeyStores */    private static final String NONE = "NONE";     /**     * default constructor     */    private PolicyTool() {        policyEntries = new Vector<PolicyEntry>();        parser = new PolicyParser();        warnings = new Vector<String>();    }     /**     * get the PolicyFileName     */    String getPolicyFileName() {        return policyFileName;    }     /**     * set the PolicyFileName     */    void setPolicyFileName(String policyFileName) {        this.policyFileName = policyFileName;    }    /**    * clear keyStore info    */    void clearKeyStoreInfo() {        this.keyStoreName = null;        this.keyStoreType = null;        this.keyStoreProvider = null;        this.keyStorePwdURL = null;         this.keyStore = null;    }     /**     * get the keyStore URL name     */    String getKeyStoreName() {        return keyStoreName;    }     /**     * get the keyStore Type     */    String getKeyStoreType() {        return keyStoreType;    }     /**     * get the keyStore Provider     */    String getKeyStoreProvider() {        return keyStoreProvider;    }     /**     * get the keyStore password URL     */    String getKeyStorePwdURL() {        return keyStorePwdURL;    }     /**     * Open and read a policy file     */    void openPolicy(String filename) throws FileNotFoundException,                                        PolicyParser.ParsingException,                                        KeyStoreException,                                        CertificateException,                                        InstantiationException,                                        MalformedURLException,                                        IOException,                                        NoSuchAlgorithmException,                                        IllegalAccessException,                                        NoSuchMethodException,                                        UnrecoverableKeyException,                                        NoSuchProviderException,                                        ClassNotFoundException,                                        PropertyExpander.ExpandException,                                        InvocationTargetException {         newWarning = false;         // start fresh - blow away the current state        policyEntries = new Vector<PolicyEntry>();        parser = new PolicyParser();        warnings = new Vector<String>();        setPolicyFileName(null);        clearKeyStoreInfo();         // see if user is opening a NEW policy file        if (filename == null) {            modified = false;            return;        }         // Read in the policy entries from the file and        // populate the parser vector table.  The parser vector        // table only holds the entries as strings, so it only        // guarantees that the policies are syntactically        // correct.        setPolicyFileName(filename);        parser.read(new FileReader(filename));         // open the keystore        openKeyStore(parser.getKeyStoreUrl(), parser.getKeyStoreType(),                parser.getKeyStoreProvider(), parser.getStorePassURL());         // Update the local vector with the same policy entries.        // This guarantees that the policy entries are not only        // syntactically correct, but semantically valid as well.        Enumeration<PolicyParser.GrantEntry> enum_ = parser.grantElements();        while (enum_.hasMoreElements()) {            PolicyParser.GrantEntry ge = enum_.nextElement();             // see if all the signers have public keys            if (ge.signedBy != null) {                 String signers[] = parseSigners(ge.signedBy);                for (int i = 0; i < signers.length; i++) {                    PublicKey pubKey = getPublicKeyAlias(signers[i]);                    if (pubKey == null) {                        newWarning = true;                        MessageFormat form = new MessageFormat(rb.getString                            ("Warning.A.public.key.for.alias.signers.i.does.not.exist.Make.sure.a.KeyStore.is.properly.configured."));                        Object[] source = {signers[i]};                        warnings.addElement(form.format(source));                    }                }            }             // check to see if the Principals are valid            ListIterator<PolicyParser.PrincipalEntry> prinList =                                                ge.principals.listIterator(0);            while (prinList.hasNext()) {                PolicyParser.PrincipalEntry pe = prinList.next();                try {                    verifyPrincipal(pe.getPrincipalClass(),                                pe.getPrincipalName());                } catch (ClassNotFoundException fnfe) {                    newWarning = true;                    MessageFormat form = new MessageFormat(rb.getString                                ("Warning.Class.not.found.class"));                    Object[] source = {pe.getPrincipalClass()};                    warnings.addElement(form.format(source));                }            }             // check to see if the Permissions are valid            Enumeration<PolicyParser.PermissionEntry> perms =                                                ge.permissionElements();            while (perms.hasMoreElements()) {                PolicyParser.PermissionEntry pe = perms.nextElement();                try {                    verifyPermission(pe.permission, pe.name, pe.action);                } catch (ClassNotFoundException fnfe) {                    newWarning = true;                    MessageFormat form = new MessageFormat(rb.getString                                ("Warning.Class.not.found.class"));                    Object[] source = {pe.permission};                    warnings.addElement(form.format(source));                } catch (InvocationTargetException ite) {                    newWarning = true;                    MessageFormat form = new MessageFormat(rb.getString                        ("Warning.Invalid.argument.s.for.constructor.arg"));                    Object[] source = {pe.permission};                    warnings.addElement(form.format(source));                }                 // see if all the permission signers have public keys                if (pe.signedBy != null) {                     String signers[] = parseSigners(pe.signedBy);                     for (int i = 0; i < signers.length; i++) {                        PublicKey pubKey = getPublicKeyAlias(signers[i]);                        if (pubKey == null) {                            newWarning = true;                            MessageFormat form = new MessageFormat(rb.getString                                ("Warning.A.public.key.for.alias.signers.i.does.not.exist.Make.sure.a.KeyStore.is.properly.configured."));                            Object[] source = {signers[i]};                            warnings.addElement(form.format(source));                        }                    }                }            }            PolicyEntry pEntry = new PolicyEntry(this, ge);            policyEntries.addElement(pEntry);        }         // just read in the policy -- nothing has been modified yet        modified = false;    }      /**     * Save a policy to a file     */    void savePolicy(String filename)    throws FileNotFoundException, IOException {        // save the policy entries to a file        parser.setKeyStoreUrl(keyStoreName);        parser.setKeyStoreType(keyStoreType);        parser.setKeyStoreProvider(keyStoreProvider);        parser.setStorePassURL(keyStorePwdURL);        parser.write(new FileWriter(filename));        modified = false;    }     /**     * Open the KeyStore     */    void openKeyStore(String name,                String type,                String provider,                String pwdURL) throws   KeyStoreException,                                        NoSuchAlgorithmException,                                        UnrecoverableKeyException,                                        IOException,                                        CertificateException,                                        NoSuchProviderException,                                        ExpandException {         if (name == null && type == null &&            provider == null && pwdURL == null) {             // policy did not specify a keystore during open            // or use wants to reset keystore values             this.keyStoreName = null;            this.keyStoreType = null;            this.keyStoreProvider = null;            this.keyStorePwdURL = null;             // caller will set (tool.modified = true) if appropriate             return;        }         URL policyURL = null;        if (policyFileName != null) {            File pfile = new File(policyFileName);            policyURL = new URL("file:" + pfile.getCanonicalPath());        }         // although PolicyUtil.getKeyStore may properly handle        // defaults and property expansion, we do it here so that        // if the call is successful, we can set the proper values        // (PolicyUtil.getKeyStore does not return expanded values)         if (name != null && name.length() > 0) {            name = PropertyExpander.expand(name).replace                                        (File.separatorChar, '/');        }        if (type == null || type.length() == 0) {            type = KeyStore.getDefaultType();        }        if (pwdURL != null && pwdURL.length() > 0) {            pwdURL = PropertyExpander.expand(pwdURL).replace                                        (File.separatorChar, '/');        }         try {            this.keyStore = PolicyUtil.getKeyStore(policyURL,                                                name,                                                type,                                                provider,                                                pwdURL,                                                null);        } catch (IOException ioe) {             // copied from sun.security.pkcs11.SunPKCS11            String MSG = "no password provided, and no callback handler " +                        "available for retrieving password";             Throwable cause = ioe.getCause();            if (cause != null &&                cause instanceof javax.security.auth.login.LoginException &&                MSG.equals(cause.getMessage())) {                 // throw a more friendly exception message                throw new IOException(MSG);            } else {                throw ioe;            }        }         this.keyStoreName = name;        this.keyStoreType = type;        this.keyStoreProvider = provider;        this.keyStorePwdURL = pwdURL;         // caller will set (tool.modified = true)    }     /**     * Add a Grant entry to the overall policy at the specified index.     * A policy entry consists of a CodeSource.     */    boolean addEntry(PolicyEntry pe, int index) {         if (index < 0) {            // new entry -- just add it to the end            policyEntries.addElement(pe);            parser.add(pe.getGrantEntry());        } else {            // existing entry -- replace old one            PolicyEntry origPe = policyEntries.elementAt(index);            parser.replace(origPe.getGrantEntry(), pe.getGrantEntry());            policyEntries.setElementAt(pe, index);        }        return true;    }     /**     * Add a Principal entry to an existing PolicyEntry at the specified index.     * A Principal entry consists of a class, and name.     *     * If the principal already exists, it is not added again.     */    boolean addPrinEntry(PolicyEntry pe,                        PolicyParser.PrincipalEntry newPrin,                        int index) {         // first add the principal to the Policy Parser entry        PolicyParser.GrantEntry grantEntry = pe.getGrantEntry();        if (grantEntry.contains(newPrin) == true)            return false;         LinkedList<PolicyParser.PrincipalEntry> prinList =                                                grantEntry.principals;        if (index != -1)            prinList.set(index, newPrin);        else            prinList.add(newPrin);         modified = true;        return true;    }     /**     * Add a Permission entry to an existing PolicyEntry at the specified index.     * A Permission entry consists of a permission, name, and actions.     *     * If the permission already exists, it is not added again.     */    boolean addPermEntry(PolicyEntry pe,                        PolicyParser.PermissionEntry newPerm,                        int index) {         // first add the permission to the Policy Parser Vector        PolicyParser.GrantEntry grantEntry = pe.getGrantEntry();        if (grantEntry.contains(newPerm) == true)            return false;         Vector<PolicyParser.PermissionEntry> permList =                                                grantEntry.permissionEntries;        if (index != -1)            permList.setElementAt(newPerm, index);        else            permList.addElement(newPerm);         modified = true;        return true;    }     /**     * Remove a Permission entry from an existing PolicyEntry.     */    boolean removePermEntry(PolicyEntry pe,                        PolicyParser.PermissionEntry perm) {         // remove the Permission from the GrantEntry        PolicyParser.GrantEntry ppge = pe.getGrantEntry();        modified = ppge.remove(perm);        return modified;    }     /**     * remove an entry from the overall policy     */    boolean removeEntry(PolicyEntry pe) {         parser.remove(pe.getGrantEntry());        modified = true;        return (policyEntries.removeElement(pe));    }     /**     * retrieve all Policy Entries     */    PolicyEntry[] getEntry() {         if (policyEntries.size() > 0) {

Lines 1–500 of 4131.