/src/share/classes/sun/security/tools/policytool/PolicyTool.java
Java | 4518 lines | 3696 code | 331 blank | 491 comment | 202 complexity | ed5fa049fa423d5fe189c1f699d37584 MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause, LGPL-3.0
Large files files are truncated, but you can click here to view the full file
- /*
- * Copyright (c) 1997, 2013, 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.Component;
- import java.awt.Container;
- import java.awt.Dimension;
- import java.awt.FileDialog;
- import java.awt.GridBagConstraints;
- import java.awt.GridBagLayout;
- import java.awt.Insets;
- import java.awt.Point;
- import java.awt.Toolkit;
- import java.awt.Window;
- 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;
- import javax.swing.*;
- import javax.swing.border.EmptyBorder;
- /**
- * 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.tools.policytool.Resources");
- static final Collator collator = Collator.getInstance();
- static {
- // this is for case insensitive string comparisons
- collator.setStrength(Collator.PRIMARY);
- // Support for Apple menu bar
- if (System.getProperty("apple.laf.useScreenMenuBar") == null) {
- System.setProperty("apple.laf.useScreenMenuBar", "true");
- }
- System.setProperty("apple.awt.application.name", getMessage("Policy.Tool"));
- // Apply the system L&F if not specified with a system property.
- if (System.getProperty("swing.defaultlaf") == null) {
- try {
- UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
- } catch (Exception e) {
- // ignore
- }
- }
- }
- // 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) {
- PolicyTool.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(getMessage
- ("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(getMessage
- ("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(getMessage
- ("Warning.Class.not.found.class"));
- Object[] source = {pe.permission};
- warnings.addElement(form.format(source));
- } catch (InvocationTargetException ite) {
- newWarning = true;
- MessageFormat form = new MessageFormat(getMessage
- ("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(getMessage
- ("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.PrincipalEntry.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(getMessage
- ("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
- */
- @SuppressWarnings("fallthrough")
- 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);
- }
- /* fall through */
- case 1:
- try {
- c = pc.getConstructor(ONEPARAMS);
- break;
- } catch (NoSuchMethodException ex) {
- // proceed to the two-param constructor
- objects.add(null);
- }
- /* fall through */
- 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(getMessage
- ("Illegal.option.option"));
- Object[] source = { flags };
- System.err.println(form.format(source));
- usage();
- }
- }
- }
- static void usage() {
- System.out.println(getMessage("Usage.policytool.options."));
- System.out.println();
- System.out.println(getMessage
- (".file.file.policy.file.location"));
- System.out.println();
- System.exit(1);
- }
- /**
- * run the PolicyTool
- */
- public static void main(String args[]) {
- parseArgs(args);
- SwingUtilities.invokeLater(new Runnable() {
- public void run() {
- 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");
- }
- /**
- * Returns the message corresponding to the key in the bundle.
- * This is preferred over {@link #getString} because it removes
- * any mnemonic '&' character in the string.
- *
- * @param key the key
- *
- * @return the message
- */
- static String getMessage(String key) {
- return removeMnemonicAmpersand(rb.getString(key));
- }
- /**
- * Returns the mnemonic for a message.
- *
- * @param key the key
- *
- * @return the mnemonic <code>int</code>
- */
- static int getMnemonicInt(String key) {
- String message = rb.getString(key);
- return (findMnemonicInt(message));
- }
- /**
- * Returns the mnemonic display index for a message.
- *
- * @param key the key
- *
- * @return the mnemonic display index
- */
- static int getDisplayedMnemonicIndex(String key) {
- String message = rb.getString(key);
- return (findMnemonicIndex(message));
- }
- /**
- * Finds the mnemonic character in a message.
- *
- * The mnemonic character is the first character followed by the first
- * <code>&</code> that is not followed by another <code>&</code>.
- *
- * @return the mnemonic as an <code>int</code>, or <code>0</code> if it
- * can't be found.
- */
- private static int findMnemonicInt(String s) {
- for (int i = 0; i < s.length() - 1; i++) {
- if (s.charAt(i) == '&') {
- if (s.charAt(i + 1) != '&') {
- return KeyEvent.getExtendedKeyCodeForChar(s.charAt(i + 1));
- } else {
- i++;
- }
- }
- }
- return 0;
- }
- /**
- * Finds the index of the mnemonic character in a message.
- *
- * The mnemonic character is the first character followed by the first
- * <code>&</code> that is not followed by another <code>&</code>.
- *
- * @return the mnemonic character index as an <code>int</code>, or <code>-1</code> if it
- * can't be found.
- */
- private static int findMnemonicIndex(String s) {
- for (int i = 0; i < s.length() - 1; i++) {
- if (s.charAt(i) == '&') {
- if (s.charAt(i + 1) != '&') {
- // Return the index of the '&' since it will be removed
- return i;
- } else {
- i++;
- }
- }
- }
- return -1;
- }
- /**
- * Removes the mnemonic identifier (<code>&</code>) from a string unless
- * it's escaped by <code>&&</code> or placed at the end.
- *
- * @param message the message
- *
- * @return a message with the mnemonic identifier removed
- */
- private static String removeMnemonicAmpersand(String message) {
- StringBuilder s = new StringBuilder();
- for (int i = 0; i < message.length(); i++) {
- char current = message.charAt(i);
- if (current != '&' || i == message.length() - 1
- || message.charAt(i + 1) == '&') {
- s.append(current);
- }
- }
- return s.toString();
- }
- }
- /**
- * 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 JFrame {
- // use serialVersionUID from JDK 1.2.2 for interoperability
- private static final long serialVersionUID = 5682568601210376777L;
- /* ESCAPE key */
- static final KeyStroke escKey = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
- /* 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_TOP_BOTTOM_PADDING = new Insets(15, 4, 15, 4);
- 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, 25, 5);
- public static final Insets R_PADDING = new Insets(0, 0, 0, 5);
- /* buttons and menus */
- public static final String NEW_POLICY_FILE = "New";
- public static final String OPEN_POLICY_FILE = "Open";
- public static final String SAVE_POLICY_FILE = "Save";
- public static final String SAVE_AS_POLICY_FILE = "Save.As";
- public static final String VIEW_WARNINGS = "View.Warning.Log";
- public static final String QUIT = "Exit";
- public static final String ADD_POLICY_ENTRY = "Add.Policy.Entry";
- public static final String EDIT_POLICY_ENTRY = "Edit.Policy.Entry";
- public static final String REMOVE_POLICY_ENTRY = "Remove.Policy.Entry";
- public static final String EDIT_KEYSTORE = "Edit";
- public static final String ADD_PUBKEY_ALIAS = "Add.Public.Key.Alias";
- public static final String REMOVE_PUBKEY_ALIAS = "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
- /* The preferred height of JTextField should match JComboBox. */
- static final int TEXTFIELD_HEIGHT = new JComboBox().getPreferredSize().height;
- private PolicyTool tool;
- /**
- * Constructor
- */
- ToolWindow(PolicyTool tool) {
- this.tool = tool;
- }
- /**
- * Don't call getComponent directly on the window
- */
- public Component getComponent(int n) {
- Component c = getContentPane().getComponent(n);
- if (c instanceof JScrollPane) {
- c = ((JScrollPane)c).getViewport().getView();
- }
- return c;
- }
- /**
- * Initialize the PolicyTool window with the necessary components
- */
- private void initWindow() {
- // The ToolWindowListener will handle closing the window.
- setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
- // create the top menu bar
- JMenuBar menuBar = new JMenuBar();
- // create a File menu
- JMenu menu = new JMenu();
- configureButton(menu, "File");
- ActionListener actionListener = new FileMenuListener(tool, this);
- addMenuItem(menu, NEW_POLICY_FILE, actionListener, "N");
- addMenuItem(menu, OPEN_POLICY_FILE, actionListener, "O");
- addMenuItem(menu, SAVE_POLICY_FILE, actionListener, "S");
- addMenuItem(menu, SAVE_AS_POLICY_FILE, actionListener, null);
- addMenuItem(menu, VIEW_WARNINGS, actionListener, null);
- addMenuItem(menu, QUIT, actionListener, null);
- menuBar.add(menu);
- // create a KeyStore menu
- menu = new JMenu();
- configureButton(menu, "KeyStore");
- actionListener = new MainWindowListener(tool, this);
- addMenuItem(menu, EDIT_KEYSTORE, actionListener, null);
- menuBar.add(menu);
- setJMenuBar(menuBar);
- // Create some space around components
- ((JPanel)getContentPane()).setBorder(new EmptyBorder(6, 6, 6, 6));
- // policy entry listing
- JLabel label = new JLabel(PolicyTool.getMessage("Policy.File."));
- addNewComponent(this, label, MW_FILENAME_LABEL,
- 0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
- LR_TOP_BOTTOM_PADDING);
- JTextField tf = new JTextField(50);
- tf.setPreferredSize(new Dimension(tf.getPreferredSize().width, TEXTFIELD_HEIGHT));
- tf.getAccessibleContext().setAccessibleName(
- PolicyTool.getMessage("Policy.File."));
- tf.setEditable(false);
- addNewComponent(this, tf, MW_FILENAME_TEXTFIELD,
- 1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
- LR_TOP_BOTTOM_PADDING);
- // add ADD/REMOVE/EDIT buttons in a new panel
- JPanel panel = new JPanel();
- panel.setLayout(new GridBagLayout());
- JButton button = new JButton();
- configureButton(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 JButton();
- configureButton(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 JButton();
- configureButton(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
- DefaultListModel listModel = new DefaultListModel();
- JList list = new JList(listModel);
- list.setVisibleRowCount(15);
- list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
- list.addMouseListener(new PolicyListListener(tool, this));
- PolicyEntry entries[] = tool.getEntry();
- if (entries != null) {
- for (int i = 0; i < entries.length; i++) {
- listModel.addElement(entries[i].headerToString());
- }
- }
- JTextField newFilename = (JTextField)
- getComponent(MW_FILENAME_TEXTFIELD);
- newFilename.setText(policyFile);
- initPolicyList(list);
- } catch (FileNotFoundException fnfe) {
- // add blank policy listing
- JList list = new JList(new DefaultListModel());
- list.setVisibleRowCount(15);
- list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
- list.addMouseListener(new PolicyListListener(tool, this));
- initPolicyList(list);
- tool.setPolicyFileName(null);
- tool.modified = false;
- // just add warning
- tool.warnings.addElement(fnfe.toString());
- } catch (Exception e) {
- // add blank policy listing
- JList list = new JList(new DefaultListModel());
- list.setVisibleRowCount(15);
- list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
- list.addMouseListener(new PolicyListListener(tool, this));
- initPolicyList(list);
- tool.setPolicyFileName(null);
- tool.modified = false;
- // display the error
- MessageFormat form = new MessageFormat(PolicyTool.getMessage
- ("Could.not.open.policy.file.policyFile.e.toString."));
- Object[] source = {policyFile, e.toString()};
- displayErrorDialog(null, form.format(source));
- }
- }
- // Platform specific modifier (control / command).
- private int shortCutModifier = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
- private void addMenuItem(JMenu menu, String key, ActionListener actionListener, String accelerator) {
- JMenuItem menuItem = new JMenuItem();
- configureButton(menuItem, key);
- if (PolicyTool.rb.containsKey(key + ".accelerator")) {
- // Accelerator from resources takes precedence
- accelerator = PolicyTool.getMessage(key + ".accelerator");
- }
- if (accelerator != null && !accelerator.isEmpty()) {
- KeyStroke keyStroke;
- if (accelerator.length() == 1) {
- keyStroke = KeyStroke.getKeyStroke(KeyEvent.getExtendedKeyCodeForChar(accelerator.charAt(0)),
- shortCutModifier);
- } else {
- keyStroke = KeyStroke.getKeyStroke(accelerator);
- }
- menuItem.setAccelerator(keyStroke);
- }
- menuItem.addActionListener(actionListener);
- menu.add(menuItem);
- }
- static void configureButton(AbstractButton button, String key) {
- button.setText(PolicyTool.getMessage(key));
- button.setActionCommand(key);
- int mnemonicInt = PolicyTool.getMnemonicInt(key);
- if (mnemonicInt > 0) {
- button.setMnemonic(mnemonicInt);
- button.setDisplayedMnemonicIndex(PolicyTool.getDisplayedMnemonicIndex(key));
- }
- }
- static void configureLabelFor(JLabel label, JComponent component, String key) {
- label.setText(PolicyTool.getMessage(key));
- label.setLabelFor(component);
- int mnemonicInt = PolicyTool.getMnemonicInt(key);
- if (mnemonicInt > 0) {
- label.setDisplayedMnemonic(mnemonicInt);
- label.setDisplayedMnemonicIndex(PolicyTool.getDisplayedMnemonicIndex(key));
- }
- }
- /**
- * Add a component to the PolicyTool window
- */
- void addNewComponent(Container container, JComponent component,
- int index, int gridx, int gridy, int gridwidth, int gridheight,
- double weightx, double weighty, int fill, Insets is) {
- if (container instanceof JFrame) {
- container = ((JFrame)container).getContentPane();
- } else if (container instanceof JDialog) {
- container = ((JDialog)container).getContentPane();
- }
- // 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, JComponent 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(JList policyList) {
- // add the policy list to the window
- //policyList.setPreferredSize(new Dimension(500, 350));
- JScrollPane scrollPane = new JScrollPane(policyList);
- addNewComponent(this, scrollPane, 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(JList policyList) {
- // remove the original list of Policy Entries
- // and add the new list of entries
- JList list = (JList)getComponent(MW_POLICY_LIST);
- list.setModel(policyList.getModel());
- }
- /**
- * display the main PolicyTool window
- */
- void displayToolWindow(String args[]) {
- setTitle(PolicyTool.getMessage("Policy.Tool"));
- setResizable(true);
- addWindowListener(new ToolWindowListener(tool, this));
- //setBounds(135, 80, 500, 500);
- getContentPane().setLayout(new GridBagLayout());
- initWindow();
- pack();
- setLocationRelativeTo(null);
- // display it
- setVisible(true);
- if (tool.newWarning == true) {
- displayStatusDialog(this, PolicyTool.getMessage
- ("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.getMessage("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());
- JLabel label = new JLabel(error);
- addNewComponent(ed, label, 0,
- 0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH);
- JButton okButton = new JButton(PolicyTool.getMessage("OK"));
- ActionListener okListener = new ErrorOKButtonListener(ed);
- okButton.addActionListener(okListener);
- addNewComponent(ed, okButton, 1,
- 0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL);
- ed.getRootPane().setDefaultButton(okButton);
- ed.getRootPane().registerKeyboardAction(okListener, escKey, JComponent.WHEN_IN_FOCUSED_WINDOW);
- ed.pack();
- ed.setLocationRelativeTo(w);
- 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());
- }
- …
Large files files are truncated, but you can click here to view the full file