/src/share/classes/sun/security/tools/policytool/PolicyTool.java
Java | 4131 lines | 3424 code | 297 blank | 410 comment | 166 complexity | 913637797e9544a2a10cf0bb828103f5 MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause-No-Nuclear-License-2014, LGPL-3.0
Large files files are truncated, but you can click here to view the full file
- /*
- * 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) {
- PolicyEntry entries[] = new PolicyEntry[policyEntries.size()];
- for (int i = 0; i < policyEntries.size(); i++)
- entries[i] = policyEntries.elementAt(i);
- return entries;
- }
- return null;
- }
- /**
- * Retrieve the public key mapped to a particular name.
- * If the key has expired, a KeyException is thrown.
- */
- PublicKey getPublicKeyAlias(String name) throws KeyStoreException {
- if (keyStore == null) {
- return null;
- }
- Certificate cert = keyStore.getCertificate(name);
- if (cert == null) {
- return null;
- }
- PublicKey pubKey = cert.getPublicKey();
- return pubKey;
- }
- /**
- * Retrieve all the alias names stored in the certificate database
- */
- String[] getPublicKeyAlias() throws KeyStoreException {
- int numAliases = 0;
- String aliases[] = null;
- if (keyStore == null) {
- return null;
- }
- Enumeration<String> enum_ = keyStore.aliases();
- // first count the number of elements
- while (enum_.hasMoreElements()) {
- enum_.nextElement();
- numAliases++;
- }
- if (numAliases > 0) {
- // now copy them into an array
- aliases = new String[numAliases];
- numAliases = 0;
- enum_ = keyStore.aliases();
- while (enum_.hasMoreElements()) {
- aliases[numAliases] = new String(enum_.nextElement());
- numAliases++;
- }
- }
- return aliases;
- }
- /**
- * This method parses a single string of signers separated by commas
- * ("jordan, duke, pippen") into an array of individual strings.
- */
- String[] parseSigners(String signedBy) {
- String signers[] = null;
- int numSigners = 1;
- int signedByIndex = 0;
- int commaIndex = 0;
- int signerNum = 0;
- // first pass thru "signedBy" counts the number of signers
- while (commaIndex >= 0) {
- commaIndex = signedBy.indexOf(',', signedByIndex);
- if (commaIndex >= 0) {
- numSigners++;
- signedByIndex = commaIndex + 1;
- }
- }
- signers = new String[numSigners];
- // second pass thru "signedBy" transfers signers to array
- commaIndex = 0;
- signedByIndex = 0;
- while (commaIndex >= 0) {
- if ((commaIndex = signedBy.indexOf(',', signedByIndex)) >= 0) {
- // transfer signer and ignore trailing part of the string
- signers[signerNum] =
- signedBy.substring(signedByIndex, commaIndex).trim();
- signerNum++;
- signedByIndex = commaIndex + 1;
- } else {
- // we are at the end of the string -- transfer signer
- signers[signerNum] = signedBy.substring(signedByIndex).trim();
- }
- }
- return signers;
- }
- /**
- * Check to see if the Principal contents are OK
- */
- void verifyPrincipal(String type, String name)
- throws ClassNotFoundException,
- InstantiationException
- {
- if (type.equals(PolicyParser.PrincipalEntry.WILDCARD_CLASS) ||
- type.equals(PolicyParser.REPLACE_NAME)) {
- return;
- };
- Class<?> PRIN = Class.forName("java.security.Principal");
- Class<?> pc = Class.forName(type, true,
- Thread.currentThread().getContextClassLoader());
- if (!PRIN.isAssignableFrom(pc)) {
- MessageFormat form = new MessageFormat(rb.getString
- ("Illegal.Principal.Type.type"));
- Object[] source = {type};
- throw new InstantiationException(form.format(source));
- }
- if (ToolDialog.X500_PRIN_CLASS.equals(pc.getName())) {
- // PolicyParser checks validity of X500Principal name
- // - PolicyTool needs to as well so that it doesn't store
- // an invalid name that can't be read in later
- //
- // this can throw an IllegalArgumentException
- X500Principal newP = new X500Principal(name);
- }
- }
- /**
- * Check to see if the Permission contents are OK
- */
- void verifyPermission(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, true,
- Thread.currentThread().getContextClassLoader());
- Constructor<?> c = null;
- Vector<String> objects = new Vector<>(2);
- if (name != null) objects.add(name);
- if (actions != null) objects.add(actions);
- switch (objects.size()) {
- case 0:
- try {
- c = pc.getConstructor(NOPARAMS);
- break;
- } catch (NoSuchMethodException ex) {
- // proceed to the one-param constructor
- objects.add(null);
- }
- case 1:
- try {
- c = pc.getConstructor(ONEPARAMS);
- break;
- } catch (NoSuchMethodException ex) {
- // proceed to the two-param constructor
- objects.add(null);
- }
- case 2:
- c = pc.getConstructor(TWOPARAMS);
- break;
- }
- Object parameters[] = objects.toArray();
- Permission p = (Permission)c.newInstance(parameters);
- }
- /*
- * Parse command line arguments.
- */
- static void parseArgs(String args[]) {
- /* parse flags */
- int n = 0;
- for (n=0; (n < args.length) && args[n].startsWith("-"); n++) {
- String flags = args[n];
- if (collator.compare(flags, "-file") == 0) {
- if (++n == args.length) usage();
- policyFileName = args[n];
- } else {
- MessageFormat form = new MessageFormat(rb.getString
- ("Illegal.option.option"));
- Object[] source = { flags };
- System.err.println(form.format(source));
- usage();
- }
- }
- }
- static void usage() {
- System.out.println(rb.getString("Usage.policytool.options."));
- System.out.println();
- System.out.println(rb.getString
- (".file.file.policy.file.location"));
- System.out.println();
- System.exit(1);
- }
- /**
- * run the PolicyTool
- */
- public static void main(String args[]) {
- parseArgs(args);
- ToolWindow tw = new ToolWindow(new PolicyTool());
- tw.displayToolWindow(args);
- }
- // split instr to words according to capitalization,
- // like, AWTControl -> A W T Control
- // this method is for easy pronounciation
- static String splitToWords(String instr) {
- return instr.replaceAll("([A-Z])", " $1");
- }
- }
- /**
- * Each entry in the policy configuration file is represented by a
- * PolicyEntry object.
- *
- * A PolicyEntry is a (CodeSource,Permission) pair. The
- * CodeSource contains the (URL, PublicKey) that together identify
- * where the Java bytecodes come from and who (if anyone) signed
- * them. The URL could refer to localhost. The URL could also be
- * null, meaning that this policy entry is given to all comers, as
- * long as they match the signer field. The signer could be null,
- * meaning the code is not signed.
- *
- * The Permission contains the (Type, Name, Action) triplet.
- *
- */
- class PolicyEntry {
- private CodeSource codesource;
- private PolicyTool tool;
- private PolicyParser.GrantEntry grantEntry;
- private boolean testing = false;
- /**
- * Create a PolicyEntry object from the information read in
- * from a policy file.
- */
- PolicyEntry(PolicyTool tool, PolicyParser.GrantEntry ge)
- throws MalformedURLException, NoSuchMethodException,
- ClassNotFoundException, InstantiationException, IllegalAccessException,
- InvocationTargetException, CertificateException,
- IOException, NoSuchAlgorithmException, UnrecoverableKeyException {
- this.tool = tool;
- URL location = null;
- // construct the CodeSource
- if (ge.codeBase != null)
- location = new URL(ge.codeBase);
- this.codesource = new CodeSource(location,
- (java.security.cert.Certificate[]) null);
- if (testing) {
- System.out.println("Adding Policy Entry:");
- System.out.println(" CodeBase = " + location);
- System.out.println(" Signers = " + ge.signedBy);
- System.out.println(" with " + ge.principals.size() +
- " Principals");
- }
- this.grantEntry = ge;
- }
- /**
- * get the codesource associated with this PolicyEntry
- */
- CodeSource getCodeSource() {
- return codesource;
- }
- /**
- * get the GrantEntry associated with this PolicyEntry
- */
- PolicyParser.GrantEntry getGrantEntry() {
- return grantEntry;
- }
- /**
- * convert the header portion, i.e. codebase, signer, principals, of
- * this policy entry into a string
- */
- String headerToString() {
- String pString = principalsToString();
- if (pString.length() == 0) {
- return codebaseToString();
- } else {
- return codebaseToString() + ", " + pString;
- }
- }
- /**
- * convert the Codebase/signer portion of this policy entry into a string
- */
- String codebaseToString() {
- String stringEntry = new String();
- if (grantEntry.codeBase != null &&
- grantEntry.codeBase.equals("") == false)
- stringEntry = stringEntry.concat
- ("CodeBase \"" +
- grantEntry.codeBase +
- "\"");
- if (grantEntry.signedBy != null &&
- grantEntry.signedBy.equals("") == false)
- stringEntry = ((stringEntry.length() > 0) ?
- stringEntry.concat(", SignedBy \"" +
- grantEntry.signedBy +
- "\"") :
- stringEntry.concat("SignedBy \"" +
- grantEntry.signedBy +
- "\""));
- if (stringEntry.length() == 0)
- return new String("CodeBase <ALL>");
- return stringEntry;
- }
- /**
- * convert the Principals portion of this policy entry into a string
- */
- String principalsToString() {
- String result = "";
- if ((grantEntry.principals != null) &&
- (!grantEntry.principals.isEmpty())) {
- StringBuffer buffer = new StringBuffer(200);
- ListIterator<PolicyParser.PrincipalEntry> list =
- grantEntry.principals.listIterator();
- while (list.hasNext()) {
- PolicyParser.PrincipalEntry pppe = list.next();
- buffer.append(" Principal " + pppe.getDisplayClass() + " " +
- pppe.getDisplayName(true));
- if (list.hasNext()) buffer.append(", ");
- }
- result = buffer.toString();
- }
- return result;
- }
- /**
- * convert this policy entry into a PolicyParser.PermissionEntry
- */
- PolicyParser.PermissionEntry toPermissionEntry(Permission perm) {
- String actions = null;
- // get the actions
- if (perm.getActions() != null &&
- perm.getActions().trim() != "")
- actions = perm.getActions();
- PolicyParser.PermissionEntry pe = new PolicyParser.PermissionEntry
- (perm.getClass().getName(),
- perm.getName(),
- actions);
- return pe;
- }
- }
- /**
- * The main window for the PolicyTool
- */
- class ToolWindow extends Frame {
- // use serialVersionUID from JDK 1.2.2 for interoperability
- private static final long serialVersionUID = 5682568601210376777L;
- /* external paddings */
- public static final Insets TOP_PADDING = new Insets(25,0,0,0);
- public static final Insets BOTTOM_PADDING = new Insets(0,0,25,0);
- public static final Insets LITE_BOTTOM_PADDING = new Insets(0,0,10,0);
- public static final Insets LR_PADDING = new Insets(0,10,0,10);
- public static final Insets TOP_BOTTOM_PADDING = new Insets(15, 0, 15, 0);
- public static final Insets L_TOP_BOTTOM_PADDING = new Insets(5,10,15,0);
- public static final Insets LR_BOTTOM_PADDING = new Insets(0,10,5,10);
- public static final Insets L_BOTTOM_PADDING = new Insets(0,10,5,0);
- public static final Insets R_BOTTOM_PADDING = new Insets(0,0,5,10);
- /* buttons and menus */
- public static final String NEW_POLICY_FILE =
- PolicyTool.rb.getString("New");
- public static final String OPEN_POLICY_FILE =
- PolicyTool.rb.getString("Open");
- public static final String SAVE_POLICY_FILE =
- PolicyTool.rb.getString("Save");
- public static final String SAVE_AS_POLICY_FILE =
- PolicyTool.rb.getString("Save.As");
- public static final String VIEW_WARNINGS =
- PolicyTool.rb.getString("View.Warning.Log");
- public static final String QUIT =
- PolicyTool.rb.getString("Exit");
- public static final String ADD_POLICY_ENTRY =
- PolicyTool.rb.getString("Add.Policy.Entry");
- public static final String EDIT_POLICY_ENTRY =
- PolicyTool.rb.getString("Edit.Policy.Entry");
- public static final String REMOVE_POLICY_ENTRY =
- PolicyTool.rb.getString("Remove.Policy.Entry");
- public static final String EDIT_KEYSTORE =
- PolicyTool.rb.getString("Edit");
- public static final String ADD_PUBKEY_ALIAS =
- PolicyTool.rb.getString("Add.Public.Key.Alias");
- public static final String REMOVE_PUBKEY_ALIAS =
- PolicyTool.rb.getString("Remove.Public.Key.Alias");
- /* gridbag index for components in the main window (MW) */
- public static final int MW_FILENAME_LABEL = 0;
- public static final int MW_FILENAME_TEXTFIELD = 1;
- public static final int MW_PANEL = 2;
- public static final int MW_ADD_BUTTON = 0;
- public static final int MW_EDIT_BUTTON = 1;
- public static final int MW_REMOVE_BUTTON = 2;
- public static final int MW_POLICY_LIST = 3; // follows MW_PANEL
- private PolicyTool tool;
- /**
- * Constructor
- */
- ToolWindow(PolicyTool tool) {
- this.tool = tool;
- }
- /**
- * Initialize the PolicyTool window with the necessary components
- */
- private void initWindow() {
- // create the top menu bar
- MenuBar menuBar = new MenuBar();
- // create a File menu
- Menu menu = new Menu(PolicyTool.rb.getString("File"));
- menu.add(NEW_POLICY_FILE);
- menu.add(OPEN_POLICY_FILE);
- menu.add(SAVE_POLICY_FILE);
- menu.add(SAVE_AS_POLICY_FILE);
- menu.add(VIEW_WARNINGS);
- menu.add(QUIT);
- menu.addActionListener(new FileMenuListener(tool, this));
- menuBar.add(menu);
- setMenuBar(menuBar);
- // create a KeyStore menu
- menu = new Menu(PolicyTool.rb.getString("KeyStore"));
- menu.add(EDIT_KEYSTORE);
- menu.addActionListener(new MainWindowListener(tool, this));
- menuBar.add(menu);
- setMenuBar(menuBar);
- // policy entry listing
- Label label = new Label(PolicyTool.rb.getString("Policy.File."));
- addNewComponent(this, label, MW_FILENAME_LABEL,
- 0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
- TOP_BOTTOM_PADDING);
- TextField tf = new TextField(50);
- tf.getAccessibleContext().setAccessibleName(
- PolicyTool.rb.getString("Policy.File."));
- tf.setEditable(false);
- addNewComponent(this, tf, MW_FILENAME_TEXTFIELD,
- 1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
- TOP_BOTTOM_PADDING);
- // add ADD/REMOVE/EDIT buttons in a new panel
- Panel panel = new Panel();
- panel.setLayout(new GridBagLayout());
- Button button = new Button(ADD_POLICY_ENTRY);
- button.addActionListener(new MainWindowListener(tool, this));
- addNewComponent(panel, button, MW_ADD_BUTTON,
- 0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
- LR_PADDING);
- button = new Button(EDIT_POLICY_ENTRY);
- button.addActionListener(new MainWindowListener(tool, this));
- addNewComponent(panel, button, MW_EDIT_BUTTON,
- 1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
- LR_PADDING);
- button = new Button(REMOVE_POLICY_ENTRY);
- button.addActionListener(new MainWindowListener(tool, this));
- addNewComponent(panel, button, MW_REMOVE_BUTTON,
- 2, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
- LR_PADDING);
- addNewComponent(this, panel, MW_PANEL,
- 0, 2, 2, 1, 0.0, 0.0, GridBagConstraints.BOTH,
- BOTTOM_PADDING);
- String policyFile = tool.getPolicyFileName();
- if (policyFile == null) {
- String userHome;
- userHome = java.security.AccessController.doPrivileged(
- new sun.security.action.GetPropertyAction("user.home"));
- policyFile = userHome + File.separatorChar + ".java.policy";
- }
- try {
- // open the policy file
- tool.openPolicy(policyFile);
- // display the policy entries via the policy list textarea
- List list = new List(40, false);
- list.addActionListener(new PolicyListListener(tool, this));
- PolicyEntry entries[] = tool.getEntry();
- if (entries != null) {
- for (int i = 0; i < entries.length; i++)
- list.add(entries[i].headerToString());
- }
- TextField newFilename = (TextField)
- getComponent(MW_FILENAME_TEXTFIELD);
- newFilename.setText(policyFile);
- initPolicyList(list);
- } catch (FileNotFoundException fnfe) {
- // add blank policy listing
- List list = new List(40, false);
- list.addActionListener(new PolicyListListener(tool, this));
- initPolicyList(list);
- tool.setPolicyFileName(null);
- tool.modified = false;
- setVisible(true);
- // just add warning
- tool.warnings.addElement(fnfe.toString());
- } catch (Exception e) {
- // add blank policy listing
- List list = new List(40, false);
- list.addActionListener(new PolicyListListener(tool, this));
- initPolicyList(list);
- tool.setPolicyFileName(null);
- tool.modified = false;
- setVisible(true);
- // display the error
- MessageFormat form = new MessageFormat(PolicyTool.rb.getString
- ("Could.not.open.policy.file.policyFile.e.toString."));
- Object[] source = {policyFile, e.toString()};
- displayErrorDialog(null, form.format(source));
- }
- }
- /**
- * Add a component to the PolicyTool window
- */
- void addNewComponent(Container container, Component component,
- int index, int gridx, int gridy, int gridwidth, int gridheight,
- double weightx, double weighty, int fill, Insets is) {
- // add the component at the specified gridbag index
- container.add(component, index);
- // set the constraints
- GridBagLayout gbl = (GridBagLayout)container.getLayout();
- GridBagConstraints gbc = new GridBagConstraints();
- gbc.gridx = gridx;
- gbc.gridy = gridy;
- gbc.gridwidth = gridwidth;
- gbc.gridheight = gridheight;
- gbc.weightx = weightx;
- gbc.weighty = weighty;
- gbc.fill = fill;
- if (is != null) gbc.insets = is;
- gbl.setConstraints(component, gbc);
- }
- /**
- * Add a component to the PolicyTool window without external padding
- */
- void addNewComponent(Container container, Component component,
- int index, int gridx, int gridy, int gridwidth, int gridheight,
- double weightx, double weighty, int fill) {
- // delegate with "null" external padding
- addNewComponent(container, component, index, gridx, gridy,
- gridwidth, gridheight, weightx, weighty,
- fill, null);
- }
- /**
- * Init the policy_entry_list TEXTAREA component in the
- * PolicyTool window
- */
- void initPolicyList(List policyList) {
- // add the policy list to the window
- addNewComponent(this, policyList, MW_POLICY_LIST,
- 0, 3, 2, 1, 1.0, 1.0, GridBagConstraints.BOTH);
- }
- /**
- * Replace the policy_entry_list TEXTAREA component in the
- * PolicyTool window with an updated one.
- */
- void replacePolicyList(List policyList) {
- // remove the original list of Policy Entries
- // and add the new list of entries
- List list = (List)getComponent(MW_POLICY_LIST);
- list.removeAll();
- String newItems[] = policyList.getItems();
- for (int i = 0; i < newItems.length; i++)
- list.add(newItems[i]);
- }
- /**
- * display the main PolicyTool window
- */
- void displayToolWindow(String args[]) {
- setTitle(PolicyTool.rb.getString("Policy.Tool"));
- setResizable(true);
- addWindowListener(new ToolWindowListener(this));
- setBounds(135, 80, 500, 500);
- setLayout(new GridBagLayout());
- initWindow();
- // display it
- setVisible(true);
- if (tool.newWarning == true) {
- displayStatusDialog(this, PolicyTool.rb.getString
- ("Errors.have.occurred.while.opening.the.policy.configuration.View.the.Warning.Log.for.more.information."));
- }
- }
- /**
- * displays a dialog box describing an error which occurred.
- */
- void displayErrorDialog(Window w, String error) {
- ToolDialog ed = new ToolDialog
- (PolicyTool.rb.getString("Error"), tool, this, true);
- // find where the PolicyTool gui is
- Point location = ((w == null) ?
- getLocationOnScreen() : w.getLocationOnScreen());
- ed.setBounds(location.x + 50, location.y + 50, 600, 100);
- ed.setLayout(new GridBagLayout());
- Label label = new Label(error);
- addNewComponent(ed, label, 0,
- 0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH);
- Button okButton = new Button(PolicyTool.rb.getString("OK"));
- okButton.addActionListener(new ErrorOKButtonListener(ed));
- addNewComponent(ed, okButton, 1,
- 0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL);
- ed.pack();
- ed.setVisible(true);
- }
- /**
- * displays a dialog box describing an error which occurred.
- */
- void displayErrorDialog(Window w, Throwable t) {
- if (t instanceof NoDisplayException) {
- return;
- }
- displayErrorDialog(w, t.toString());
- }
- /**
- * displays a dialog box describing the status of an event
- */
- void displayStatusDialog(Window w, String status) {
- ToolDialog sd = new ToolDialog
- (PolicyTool.rb.getString("Status"), tool, this, true);
- // find the location of the PolicyTool gui
- Point location = ((w == null) ?
- getLocationOnScreen() : w.getLocationOnScreen());
- sd.setBounds(location.x + 50, location.y + 50, 500, 100);
- sd.setLayout(new GridBagLayout());
- Label label = new Label(status);
- addNewComponent(sd, label, 0,
- 0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH);
- Button okButton = new Button(PolicyTool.rb.getString("OK"));
- okButton.addActionListener(new StatusOKButtonListener(sd));
- addNewComponent(sd, okButton, 1,
- 0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL);
- sd.pack();
- sd.setVisible(true);
- }
- /**
- * display the warning log
- */
- void displayWarningLog(Window w) {
- ToolDialog wd = new ToolDialog
- (PolicyTool.rb.getString("Warning"), tool, this, true);
- // find the location of the PolicyTool gui
- Point location = ((w == null) ?
- getLocationOnScreen() : w.getLocationOnScreen());
- wd.setBounds(location.x + 50, location.y + 50, 500, 100);
- wd.setLayout(new GridBagLayout());
- TextArea ta = new TextArea();
- ta.setEditable(false);
- for (int i = 0; i < tool.warnings.size(); i++) {
- ta.append(tool.warnings.elementAt(i));
- ta.append(PolicyTool.rb.getString("NEWLINE"));
- }
- addNewComponent(wd, ta, 0,
- 0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
- BOTTOM_PADDING);
- ta.setFocusable(false);
- Button okButton = new Button(PolicyTool.rb.getString("OK"));
- okButton.addActionListener(new CancelButtonListener(wd));
- addNewComponent(wd, okButton, 1,
- 0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL,
- LR_PADDING);
- wd.pack();
- wd.setVisible(true);
- }
- char displayYesNoDialog(Window w, String title, String prompt, String yes, String no) {
- final ToolDialog tw = new ToolDialog
- (title, tool, this, true);
- Point location = ((w == null) ?
- getLocationOnScreen() : w.getLocationOnScreen());
- tw.setBounds(location.x + 75, location.y + 100, 400, 150);
- tw.setLayout(new GridBagLayout());
- TextArea ta = new TextArea(prompt, 10, 50, TextArea.SCROLLBARS_VERTICAL_ONLY);
- ta.setEditable(false);
- addNewComponent(tw, ta, 0,
- 0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH);
- ta.setFocusable(false);
- Panel panel = new Panel();
- panel.setLayout(new GridBagLayout());
- // StringBuffer to store button press. Must be final.
- final StringBuffer chooseResult = new StringBuffer();
- Button button = new Button(yes);
- button.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- chooseResult.append('Y');
- tw.setVisible(false);
- tw.dispose();
- }
- });
- addNewComponent(panel, button, 0,
- 0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL,
- LR_PADDING);
- button = new Button(no);
- button.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- chooseResult.append('N');
- tw.setVisible(false);
- tw.dispose();
- }
- });
- addNewComponent(panel, button, 1,
- 1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL,
- LR_PADDING);
- addNewComponent(tw, panel, 1,
- 0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL);
- tw.pack();
- tw.setVisible(true);
- if (chooseResult.length() > 0) {
- return chooseResult.charAt(0);
- } else {
- // I did encounter this once, don't why.
- return 'N';
- }
- }
- }
- /**
- * General dialog window
- */
- class ToolDialog extends Dialog {
- // use serialVersionUID from JDK 1.2.2 for interoperability
- private static final long serialVersionUID = -372244357011301190L;
- /* necessary constants */
- public static final int NOACTION = 0;
- public static final int QUIT = 1;
- public static final int NEW = 2;
- public static final int OPEN = 3;
- public static final String ALL_PERM_CLASS =
- "java.security.AllPermission";
- public static final String FILE_PERM_CLASS =
- "java.io.FilePermission";
- public static final String X500_PRIN_CLASS =
- "javax.security.auth.x500.X500Principal";
- /* popup menus */
- public static final String PERM =
- PolicyTool.rb.getString
- ("Permission.");
- public static final String PRIN_TYPE =
- PolicyTool.rb.getString("Principal.Type.");
- public static final String PRIN_NAME =
- PolicyTool.rb.getString("Principal.Name.");
- /* more popu menus */
- public static final String PERM_NAME =
- PolicyTool.rb.getString
- ("Target.Name.");
- /* and more popup menus */
- public static final String PERM_ACTIONS =
- PolicyTool.rb.getString
- ("Actions.");
- /* gridbag index for display PolicyEntry (PE) components */
- public static final int PE_CODEBASE_LABEL = 0;
- public static final int PE_CODEBASE_TEXTFIELD = 1;
- public static final int PE_SIGNEDBY_LABEL = 2;
- public static final int PE_SIGNEDBY_TEXTFIELD = 3;
- public static final int PE_PANEL0 = 4;
- public static final int PE_ADD_PRIN_BUTTON = 0;
- public static final int PE_EDIT_PRIN_BUTTON = 1;
- public static final int PE_REMOVE_PRIN_BUTTON = 2;
- public static final int PE_PRIN_LABEL = 5;
- public static final int PE_PRIN_LIST = 6;
- public static final int PE_PANEL1 = 7;
- public static final int PE_ADD_PERM_BUTTON = 0;
- public static final int PE_EDIT_PERM_BUTTON = 1;
- public static final int PE_REMOVE_PERM_BUTTON = 2;
- public static final int PE_PERM_LIST = 8;
- public static final int PE_PANEL2 = 9;
- public static final int PE_CANCEL_BUTTON = 1;
- public static final int PE_DONE_BUTTON = 0;
- /* the gridbag index for components in the Principal Dialog (PRD) */
- public static final int PRD_DESC_LABEL = 0;
- public static final int PRD_PRIN_CHOICE = 1;
- public static final int PRD_PRIN_TEXTFIELD = 2;
- public static final int PRD_NAME_LABEL = 3;
- public static final int PRD_NAME_TEXTFIELD = 4;
- public static final int PRD_CANCEL_BUTTON = 6;
- public static final int PRD_OK_BUTTON = 5;
- /* the gridbag index for components in the Permission Dialog (PD) */
- public static final int PD_DESC_LABEL = 0;
- public static final int PD_PERM_CHOICE = 1;
- public static final int PD_PERM_TEXTFIELD = 2;
- public static final int PD_NAME_CHOICE = 3;
- public static final int PD_NAME_TEXTFIELD = 4;
- public static final int PD_ACTIONS_CHOICE = 5;
- public static final int PD_ACTIONS_TEXTFIELD = 6;
- public static final int PD_SIGNEDBY_LABEL = 7;
- public static final int PD_SIGNEDBY_TEXTFIELD = 8;
- public static final int PD_CANCEL_BUTTON…
Large files files are truncated, but you can click here to view the full file