PolicyFile.java revision 0
0N/A/*
782N/A * Copyright 1997-2006 Sun Microsystems, Inc. All Rights Reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
0N/A * published by the Free Software Foundation. Sun designates this
0N/A * particular file as subject to the "Classpath" exception as provided
0N/A * by Sun in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
0N/A * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
0N/A * CA 95054 USA or visit www.sun.com if you need additional information or
0N/A * have any questions.
0N/A */
0N/A
0N/Apackage sun.security.provider;
0N/A
0N/Aimport java.io.*;
0N/Aimport java.lang.RuntimePermission;
0N/Aimport java.lang.reflect.*;
0N/Aimport java.lang.ref.*;
0N/Aimport java.net.MalformedURLException;
0N/Aimport java.net.URL;
0N/Aimport java.net.URI;
0N/Aimport java.util.*;
0N/Aimport java.util.Enumeration;
0N/Aimport java.util.Hashtable;
0N/Aimport java.util.List;
0N/Aimport java.util.StringTokenizer;
0N/Aimport java.util.PropertyPermission;
0N/Aimport java.util.ArrayList;
0N/Aimport java.util.ListIterator;
0N/Aimport java.util.WeakHashMap;
0N/Aimport java.text.MessageFormat;
0N/Aimport com.sun.security.auth.PrincipalComparator;
0N/Aimport java.security.*;
0N/Aimport java.security.cert.Certificate;
0N/Aimport java.security.cert.X509Certificate;
0N/Aimport javax.security.auth.PrivateCredentialPermission;
0N/Aimport javax.security.auth.Subject;
0N/Aimport javax.security.auth.x500.X500Principal;
0N/Aimport java.io.FilePermission;
0N/Aimport java.net.SocketPermission;
0N/Aimport java.net.NetPermission;
0N/Aimport java.util.PropertyPermission;
0N/Aimport java.util.concurrent.atomic.AtomicReference;
0N/Aimport java.awt.AWTPermission;
0N/A/*
0N/Aimport javax.security.auth.AuthPermission;
0N/Aimport javax.security.auth.kerberos.ServicePermission;
0N/Aimport javax.security.auth.kerberos.DelegationPermission;
0N/Aimport java.io.SerializablePermission;
0N/Aimport java.util.logging.LoggingPermission;
0N/Aimport java.sql.SQLPermission;
0N/Aimport java.lang.reflect.ReflectPermission;
0N/Aimport javax.sound.sampled.AudioPermission;
0N/Aimport javax.net.ssl.SSLPermission;
0N/A*/
0N/Aimport sun.security.util.Password;
0N/Aimport sun.security.util.PolicyUtil;
0N/Aimport sun.security.util.PropertyExpander;
0N/Aimport sun.security.util.Debug;
0N/Aimport sun.security.util.ResourcesMgr;
0N/Aimport sun.security.util.SecurityConstants;
0N/Aimport sun.net.www.ParseUtil;
0N/A
0N/A/**
0N/A * This class represents a default implementation for
0N/A * <code>java.security.Policy</code>.
0N/A *
0N/A * Note:
0N/A * For backward compatibility with JAAS 1.0 it loads
0N/A * both java.auth.policy and java.policy. However it
0N/A * is recommended that java.auth.policy be not used
0N/A * and the java.policy contain all grant entries including
0N/A * that contain principal-based entries.
0N/A *
0N/A *
0N/A * <p> This object stores the policy for entire Java runtime,
0N/A * and is the amalgamation of multiple static policy
0N/A * configurations that resides in files.
0N/A * The algorithm for locating the policy file(s) and reading their
0N/A * information into this <code>Policy</code> object is:
0N/A *
0N/A * <ol>
0N/A * <li>
0N/A * Loop through the <code>java.security.Security</code> properties,
0N/A * <i>policy.url.1</i>, <i>policy.url.2</i>, ...,
0N/A * <i>policy.url.X</i>" and
0N/A * <i>auth.policy.url.1</i>, <i>auth.policy.url.2</i>, ...,
0N/A * <i>auth.policy.url.X</i>". These properties are set
0N/A * in the Java security properties file, which is located in the file named
0N/A * &lt;JAVA_HOME&gt;/lib/security/java.security.
0N/A * &lt;JAVA_HOME&gt; refers to the value of the java.home system property,
0N/A * and specifies the directory where the JRE is installed.
0N/A * Each property value specifies a <code>URL</code> pointing to a
0N/A * policy file to be loaded. Read in and load each policy.
0N/A *
0N/A * <i>auth.policy.url</i> is supported only for backward compatibility.
0N/A *
0N/A * <li>
0N/A * The <code>java.lang.System</code> property <i>java.security.policy</i>
0N/A * may also be set to a <code>URL</code> pointing to another policy file
0N/A * (which is the case when a user uses the -D switch at runtime).
0N/A * If this property is defined, and its use is allowed by the
0N/A * security property file (the Security property,
0N/A * <i>policy.allowSystemProperty</i> is set to <i>true</i>),
0N/A * also load that policy.
0N/A *
0N/A * <li>
0N/A * The <code>java.lang.System</code> property
0N/A * <i>java.security.auth.policy</i> may also be set to a
0N/A * <code>URL</code> pointing to another policy file
0N/A * (which is the case when a user uses the -D switch at runtime).
0N/A * If this property is defined, and its use is allowed by the
0N/A * security property file (the Security property,
0N/A * <i>policy.allowSystemProperty</i> is set to <i>true</i>),
0N/A * also load that policy.
0N/A *
0N/A * <i>java.security.auth.policy</i> is supported only for backward
0N/A * compatibility.
0N/A *
0N/A * If the <i>java.security.policy</i> or
0N/A * <i>java.security.auth.policy</i> property is defined using
0N/A * "==" (rather than "="), then ignore all other specified
0N/A * policies and only load this policy.
0N/A * </ol>
0N/A *
0N/A * Each policy file consists of one or more grant entries, each of
0N/A * which consists of a number of permission entries.
0N/A *
0N/A * <pre>
0N/A * grant signedBy "<b>alias</b>", codeBase "<b>URL</b>",
0N/A * principal <b>principalClass</b> "<b>principalName</b>",
0N/A * principal <b>principalClass</b> "<b>principalName</b>",
0N/A * ... {
0N/A *
0N/A * permission <b>Type</b> "<b>name</b> "<b>action</b>",
0N/A * signedBy "<b>alias</b>";
0N/A * permission <b>Type</b> "<b>name</b> "<b>action</b>",
0N/A * signedBy "<b>alias</b>";
0N/A * ....
0N/A * };
0N/A * </pre>
0N/A *
0N/A * All non-bold items above must appear as is (although case
0N/A * doesn't matter and some are optional, as noted below).
0N/A * principal entries are optional and need not be present.
0N/A * Italicized items represent variable values.
0N/A *
0N/A * <p> A grant entry must begin with the word <code>grant</code>.
0N/A * The <code>signedBy</code>,<code>codeBase</code> and <code>principal</code>
0N/A * name/value pairs are optional.
0N/A * If they are not present, then any signer (including unsigned code)
0N/A * will match, and any codeBase will match.
0N/A * Note that the <i>principalClass</i>
0N/A * may be set to the wildcard value, *, which allows it to match
0N/A * any <code>Principal</code> class. In addition, the <i>principalName</i>
0N/A * may also be set to the wildcard value, *, allowing it to match
0N/A * any <code>Principal</code> name. When setting the <i>principalName</i>
0N/A * to the *, do not surround the * with quotes.
0N/A *
0N/A * <p> A permission entry must begin with the word <code>permission</code>.
0N/A * The word <code><i>Type</i></code> in the template above is
0N/A * a specific permission type, such as <code>java.io.FilePermission</code>
0N/A * or <code>java.lang.RuntimePermission</code>.
0N/A *
0N/A * <p> The "<i>action</i>" is required for
0N/A * many permission types, such as <code>java.io.FilePermission</code>
0N/A * (where it specifies what type of file access that is permitted).
0N/A * It is not required for categories such as
0N/A * <code>java.lang.RuntimePermission</code>
0N/A * where it is not necessary - you either have the
0N/A * permission specified by the <code>"<i>name</i>"</code>
0N/A * value following the type name or you don't.
0N/A *
0N/A * <p> The <code>signedBy</code> name/value pair for a permission entry
0N/A * is optional. If present, it indicates a signed permission. That is,
0N/A * the permission class itself must be signed by the given alias in
0N/A * order for it to be granted. For example,
0N/A * suppose you have the following grant entry:
0N/A *
0N/A * <pre>
0N/A * grant principal foo.com.Principal "Duke" {
0N/A * permission Foo "foobar", signedBy "FooSoft";
0N/A * }
0N/A * </pre>
0N/A *
0N/A * <p> Then this permission of type <i>Foo</i> is granted if the
0N/A * <code>Foo.class</code> permission has been signed by the
0N/A * "FooSoft" alias, or if XXX <code>Foo.class</code> is a
0N/A * system class (i.e., is found on the CLASSPATH).
0N/A *
0N/A *
0N/A * <p> Items that appear in an entry must appear in the specified order
0N/A * (<code>permission</code>, <i>Type</i>, "<i>name</i>", and
0N/A * "<i>action</i>"). An entry is terminated with a semicolon.
0N/A *
0N/A * <p> Case is unimportant for the identifiers (<code>permission</code>,
0N/A * <code>signedBy</code>, <code>codeBase</code>, etc.) but is
0N/A * significant for the <i>Type</i>
0N/A * or for any string that is passed in as a value. <p>
0N/A *
0N/A * <p> An example of two entries in a policy configuration file is
0N/A * <pre>
0N/A * // if the code is comes from "foo.com" and is running as "Duke",
0N/A * // grant it read/write to all files in /tmp.
0N/A *
0N/A * grant codeBase "foo.com", principal foo.com.Principal "Duke" {
0N/A * permission java.io.FilePermission "/tmp/*", "read,write";
0N/A * };
0N/A *
0N/A * // grant any code running as "Duke" permission to read
0N/A * // the "java.vendor" Property.
0N/A *
0N/A * grant principal foo.com.Principal "Duke" {
0N/A * permission java.util.PropertyPermission "java.vendor";
0N/A *
0N/A *
0N/A * </pre>
0N/A * This Policy implementation supports special handling of any
0N/A * permission that contains the string, "<b>${{self}}</b>", as part of
0N/A * its target name. When such a permission is evaluated
0N/A * (such as during a security check), <b>${{self}}</b> is replaced
0N/A * with one or more Principal class/name pairs. The exact
0N/A * replacement performed depends upon the contents of the
0N/A * grant clause to which the permission belongs.
0N/A *<p>
0N/A *
0N/A * If the grant clause does not contain any principal information,
0N/A * the permission will be ignored (permissions containing
0N/A * <b>${{self}}</b> in their target names are only valid in the context
0N/A * of a principal-based grant clause). For example, BarPermission
0N/A * will always be ignored in the following grant clause:
0N/A *
0N/A *<pre>
0N/A * grant codebase "www.foo.com", signedby "duke" {
0N/A * permission BarPermission "... ${{self}} ...";
0N/A * };
0N/A *</pre>
0N/A *
0N/A * If the grant clause contains principal information, <b>${{self}}</b>
0N/A * will be replaced with that same principal information.
0N/A * For example, <b>${{self}}</b> in BarPermission will be replaced by
0N/A * <b>javax.security.auth.x500.X500Principal "cn=Duke"</b>
0N/A * in the following grant clause:
0N/A *
0N/A * <pre>
0N/A * grant principal javax.security.auth.x500.X500Principal "cn=Duke" {
0N/A * permission BarPermission "... ${{self}} ...";
0N/A * };
0N/A * </pre>
0N/A *
0N/A * If there is a comma-separated list of principals in the grant
0N/A * clause, then <b>${{self}}</b> will be replaced by the same
0N/A * comma-separated list or principals.
0N/A * In the case where both the principal class and name are
0N/A * wildcarded in the grant clause, <b>${{self}}</b> is replaced
0N/A * with all the principals associated with the <code>Subject</code>
0N/A * in the current <code>AccessControlContext</code>.
0N/A *
0N/A *
0N/A * <p> For PrivateCredentialPermissions, you can also use "<b>self</b>"
0N/A * instead of "<b>${{self}}</b>". However the use of "<b>self</b>" is
0N/A * deprecated in favour of "<b>${{self}}</b>".
0N/A *
0N/A * @see java.security.CodeSource
0N/A * @see java.security.Permissions
0N/A * @see java.security.ProtectionDomain
0N/A */
0N/Apublic class PolicyFile extends java.security.Policy {
0N/A
0N/A private static final Debug debug = Debug.getInstance("policy");
0N/A
0N/A private static final String NONE = "NONE";
0N/A private static final String P11KEYSTORE = "PKCS11";
0N/A
0N/A private static final String SELF = "${{self}}";
0N/A private static final String X500PRINCIPAL =
0N/A "javax.security.auth.x500.X500Principal";
0N/A private static final String POLICY = "java.security.policy";
0N/A private static final String SECURITY_MANAGER = "java.security.manager";
0N/A private static final String POLICY_URL = "policy.url.";
0N/A private static final String AUTH_POLICY = "java.security.auth.policy";
0N/A private static final String AUTH_POLICY_URL = "auth.policy.url.";
0N/A
0N/A private static final int DEFAULT_CACHE_SIZE = 1;
0N/A
0N/A /** the scope to check */
0N/A private static IdentityScope scope = null;
0N/A
0N/A // contains the policy grant entries, PD cache, and alias mapping
0N/A private AtomicReference<PolicyInfo> policyInfo =
0N/A new AtomicReference<PolicyInfo>();
0N/A private boolean constructed = false;
0N/A
0N/A private boolean expandProperties = true;
0N/A private boolean ignoreIdentityScope = false;
0N/A private boolean allowSystemProperties = true;
0N/A private boolean notUtf8 = false;
0N/A private URL url;
0N/A
0N/A // for use with the reflection API
0N/A
0N/A private static final Class[] PARAMS0 = { };
0N/A private static final Class[] PARAMS1 = { String.class };
0N/A private static final Class[] PARAMS2 = { String.class, String.class };
0N/A
0N/A /**
0N/A * Initializes the Policy object and reads the default policy
0N/A * configuration file(s) into the Policy object.
0N/A */
0N/A public PolicyFile() {
0N/A init((URL)null);
0N/A }
0N/A
0N/A /**
0N/A * Initializes the Policy object and reads the default policy
0N/A * from the specified URL only.
0N/A */
0N/A public PolicyFile(URL url) {
0N/A this.url = url;
0N/A init(url);
0N/A }
0N/A
0N/A /**
0N/A * Initializes the Policy object and reads the default policy
0N/A * configuration file(s) into the Policy object.
0N/A *
0N/A * The algorithm for locating the policy file(s) and reading their
0N/A * information into the Policy object is:
0N/A * <pre>
0N/A * loop through the Security Properties named "policy.url.1",
0N/A * ""policy.url.2", "auth.policy.url.1", "auth.policy.url.2" etc, until
0N/A * you don't find one. Each of these specify a policy file.
0N/A *
0N/A * if none of these could be loaded, use a builtin static policy
0N/A * equivalent to the default lib/security/java.policy file.
0N/A *
0N/A * if the system property "java.policy" or "java.auth.policy" is defined
0N/A * (which is the
0N/A * case when the user uses the -D switch at runtime), and
0N/A * its use is allowed by the security property file,
0N/A * also load it.
0N/A * </pre>
0N/A *
0N/A * Each policy file consists of one or more grant entries, each of
0N/A * which consists of a number of permission entries.
0N/A * <pre>
0N/A * grant signedBy "<i>alias</i>", codeBase "<i>URL</i>" {
0N/A * permission <i>Type</i> "<i>name</i>", "<i>action</i>",
0N/A * signedBy "<i>alias</i>";
0N/A * ....
0N/A * permission <i>Type</i> "<i>name</i>", "<i>action</i>",
0N/A * signedBy "<i>alias</i>";
0N/A * };
0N/A *
0N/A * </pre>
0N/A *
0N/A * All non-italicized items above must appear as is (although case
0N/A * doesn't matter and some are optional, as noted below).
0N/A * Italicized items represent variable values.
0N/A *
0N/A * <p> A grant entry must begin with the word <code>grant</code>.
0N/A * The <code>signedBy</code> and <code>codeBase</code> name/value
0N/A * pairs are optional.
0N/A * If they are not present, then any signer (including unsigned code)
0N/A * will match, and any codeBase will match.
0N/A *
0N/A * <p> A permission entry must begin with the word <code>permission</code>.
0N/A * The word <code><i>Type</i></code> in the template above would actually
0N/A * be a specific permission type, such as
0N/A * <code>java.io.FilePermission</code> or
0N/A * <code>java.lang.RuntimePermission</code>.
0N/A *
0N/A * <p>The "<i>action</i>" is required for
0N/A * many permission types, such as <code>java.io.FilePermission</code>
0N/A * (where it specifies what type of file access is permitted).
0N/A * It is not required for categories such as
0N/A * <code>java.lang.RuntimePermission</code>
0N/A * where it is not necessary - you either have the
0N/A * permission specified by the <code>"<i>name</i>"</code>
0N/A * value following the type name or you don't.
0N/A *
0N/A * <p>The <code>signedBy</code> name/value pair for a permission entry
0N/A * is optional. If present, it indicates a signed permission. That is,
0N/A * the permission class itself must be signed by the given alias in
0N/A * order for it to be granted. For example,
0N/A * suppose you have the following grant entry:
0N/A *
0N/A * <pre>
0N/A * grant {
0N/A * permission Foo "foobar", signedBy "FooSoft";
0N/A * }
0N/A * </pre>
0N/A *
0N/A * <p>Then this permission of type <i>Foo</i> is granted if the
0N/A * <code>Foo.class</code> permission has been signed by the
0N/A * "FooSoft" alias, or if <code>Foo.class</code> is a
0N/A * system class (i.e., is found on the CLASSPATH).
0N/A *
0N/A * <p>Items that appear in an entry must appear in the specified order
0N/A * (<code>permission</code>, <i>Type</i>, "<i>name</i>", and
0N/A * "<i>action</i>"). An entry is terminated with a semicolon.
0N/A *
0N/A * <p>Case is unimportant for the identifiers (<code>permission</code>,
0N/A * <code>signedBy</code>, <code>codeBase</code>, etc.) but is
0N/A * significant for the <i>Type</i>
0N/A * or for any string that is passed in as a value. <p>
0N/A *
0N/A * <p>An example of two entries in a policy configuration file is
0N/A * <pre>
0N/A * // if the code is signed by "Duke", grant it read/write to all
0N/A * // files in /tmp.
0N/A *
0N/A * grant signedBy "Duke" {
0N/A * permission java.io.FilePermission "/tmp/*", "read,write";
0N/A * };
0N/A * <p>
0N/A * // grant everyone the following permission
0N/A *
0N/A * grant {
0N/A * permission java.util.PropertyPermission "java.vendor";
0N/A * };
0N/A * </pre>
0N/A */
0N/A private void init(URL url) {
0N/A // Properties are set once for each init(); ignore changes between
0N/A // between diff invocations of initPolicyFile(policy, url, info).
0N/A String numCacheStr =
0N/A AccessController.doPrivileged(new PrivilegedAction<String>() {
0N/A public String run() {
0N/A expandProperties = "true".equalsIgnoreCase
0N/A (Security.getProperty("policy.expandProperties"));
0N/A ignoreIdentityScope = "true".equalsIgnoreCase
0N/A (Security.getProperty("policy.ignoreIdentityScope"));
0N/A allowSystemProperties = "true".equalsIgnoreCase
0N/A (Security.getProperty("policy.allowSystemProperty"));
0N/A notUtf8 = "false".equalsIgnoreCase
0N/A (System.getProperty("sun.security.policy.utf8"));
0N/A return System.getProperty("sun.security.policy.numcaches");
0N/A }});
0N/A
0N/A int numCaches;
0N/A if (numCacheStr != null) {
0N/A try {
0N/A numCaches = Integer.parseInt(numCacheStr);
0N/A } catch (NumberFormatException e) {
0N/A numCaches = DEFAULT_CACHE_SIZE;
0N/A }
0N/A } else {
0N/A numCaches = DEFAULT_CACHE_SIZE;
0N/A }
0N/A // System.out.println("number caches=" + numCaches);
0N/A PolicyInfo newInfo = new PolicyInfo(numCaches);
0N/A initPolicyFile(newInfo, url);
0N/A policyInfo.set(newInfo);
0N/A }
0N/A
0N/A private void initPolicyFile(final PolicyInfo newInfo, final URL url) {
0N/A
0N/A if (url != null) {
0N/A
0N/A /**
0N/A * If the caller specified a URL via Policy.getInstance,
0N/A * we only read from that URL
0N/A */
0N/A
0N/A if (debug != null) {
0N/A debug.println("reading "+url);
0N/A }
0N/A AccessController.doPrivileged(new PrivilegedAction<Void>() {
0N/A public Void run() {
0N/A if (init(url, newInfo) == false) {
0N/A // use static policy if all else fails
0N/A initStaticPolicy(newInfo);
0N/A }
0N/A return null;
0N/A }
0N/A });
0N/A
0N/A } else {
0N/A
0N/A /**
0N/A * Caller did not specify URL via Policy.getInstance.
0N/A * Read from URLs listed in the java.security properties file.
0N/A *
0N/A * We call initPolicyFile with POLICY , POLICY_URL and then
0N/A * call it with AUTH_POLICY and AUTH_POLICY_URL
0N/A * So first we will process the JAVA standard policy
0N/A * and then process the JAVA AUTH Policy.
0N/A * This is for backward compatibility as well as to handle
0N/A * cases where the user has a single unified policyfile
0N/A * with both java policy entries and auth entries
0N/A */
0N/A
0N/A boolean loaded_one = initPolicyFile(POLICY, POLICY_URL, newInfo);
0N/A // To maintain strict backward compatibility
0N/A // we load the static policy only if POLICY load failed
0N/A if (!loaded_one) {
0N/A // use static policy if all else fails
0N/A initStaticPolicy(newInfo);
0N/A }
0N/A
0N/A initPolicyFile(AUTH_POLICY, AUTH_POLICY_URL, newInfo);
0N/A }
0N/A }
0N/A
0N/A private boolean initPolicyFile(final String propname, final String urlname,
0N/A final PolicyInfo newInfo) {
0N/A Boolean loadedPolicy =
0N/A AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
0N/A public Boolean run() {
0N/A boolean loaded_policy = false;
0N/A
0N/A if (allowSystemProperties) {
0N/A String extra_policy = System.getProperty(propname);
0N/A if (extra_policy != null) {
0N/A boolean overrideAll = false;
0N/A if (extra_policy.startsWith("=")) {
0N/A overrideAll = true;
0N/A extra_policy = extra_policy.substring(1);
0N/A }
0N/A try {
0N/A extra_policy =
0N/A PropertyExpander.expand(extra_policy);
0N/A URL policyURL;
0N/A
0N/A File policyFile = new File(extra_policy);
0N/A if (policyFile.exists()) {
0N/A policyURL = ParseUtil.fileToEncodedURL
0N/A (new File(policyFile.getCanonicalPath()));
0N/A } else {
0N/A policyURL = new URL(extra_policy);
0N/A }
0N/A if (debug != null)
0N/A debug.println("reading "+policyURL);
0N/A if (init(policyURL, newInfo))
0N/A loaded_policy = true;
782N/A } catch (Exception e) {
782N/A // ignore.
0N/A if (debug != null) {
0N/A debug.println("caught exception: "+e);
0N/A }
0N/A }
0N/A if (overrideAll) {
0N/A if (debug != null) {
0N/A debug.println("overriding other policies!");
0N/A }
782N/A return Boolean.valueOf(loaded_policy);
782N/A }
782N/A }
782N/A }
782N/A
782N/A int n = 1;
782N/A String policy_uri;
782N/A
782N/A while ((policy_uri = Security.getProperty(urlname+n)) != null) {
782N/A try {
0N/A URL policy_url = null;
0N/A String expanded_uri = PropertyExpander.expand
0N/A (policy_uri).replace(File.separatorChar, '/');
0N/A
0N/A if (policy_uri.startsWith("file:${java.home}/") ||
0N/A policy_uri.startsWith("file:${user.home}/")) {
0N/A
0N/A // this special case accommodates
0N/A // the situation java.home/user.home
0N/A // expand to a single slash, resulting in
0N/A // a file://foo URI
0N/A policy_url = new File
0N/A (expanded_uri.substring(5)).toURI().toURL();
0N/A } else {
0N/A policy_url = new URI(expanded_uri).toURL();
0N/A }
0N/A
782N/A if (debug != null)
782N/A debug.println("reading "+policy_url);
0N/A if (init(policy_url, newInfo))
0N/A loaded_policy = true;
0N/A } catch (Exception e) {
0N/A if (debug != null) {
0N/A debug.println("error reading policy "+e);
0N/A e.printStackTrace();
0N/A }
0N/A // ignore that policy
782N/A }
782N/A n++;
782N/A }
0N/A return Boolean.valueOf(loaded_policy);
0N/A }
0N/A });
0N/A
0N/A return loadedPolicy.booleanValue();
0N/A }
0N/A
0N/A /**
0N/A * Reads a policy configuration into the Policy object using a
0N/A * Reader object.
0N/A *
0N/A * @param policyFile the policy Reader object.
0N/A */
0N/A private boolean init(URL policy, PolicyInfo newInfo) {
0N/A boolean success = false;
0N/A PolicyParser pp = new PolicyParser(expandProperties);
0N/A InputStreamReader isr = null;
0N/A try {
0N/A
0N/A // read in policy using UTF-8 by default
0N/A //
0N/A // check non-standard system property to see if
0N/A // the default encoding should be used instead
0N/A
0N/A if (notUtf8) {
0N/A isr = new InputStreamReader
0N/A (PolicyUtil.getInputStream(policy));
0N/A } else {
0N/A isr = new InputStreamReader
0N/A (PolicyUtil.getInputStream(policy), "UTF-8");
0N/A }
0N/A
0N/A pp.read(isr);
0N/A
0N/A KeyStore keyStore = null;
0N/A try {
0N/A keyStore = PolicyUtil.getKeyStore
0N/A (policy,
0N/A pp.getKeyStoreUrl(),
0N/A pp.getKeyStoreType(),
0N/A pp.getKeyStoreProvider(),
0N/A pp.getStorePassURL(),
0N/A debug);
0N/A } catch (Exception e) {
0N/A // ignore, treat it like we have no keystore
0N/A if (debug != null) {
0N/A e.printStackTrace();
0N/A }
0N/A }
0N/A
0N/A Enumeration<PolicyParser.GrantEntry> enum_ = pp.grantElements();
0N/A while (enum_.hasMoreElements()) {
0N/A PolicyParser.GrantEntry ge = enum_.nextElement();
0N/A addGrantEntry(ge, keyStore, newInfo);
0N/A }
0N/A } catch (PolicyParser.ParsingException pe) {
0N/A MessageFormat form = new MessageFormat(ResourcesMgr.getString
0N/A (POLICY + ": error parsing policy:\n\tmessage"));
0N/A Object[] source = {policy, pe.getLocalizedMessage()};
0N/A System.err.println(form.format(source));
0N/A if (debug != null)
0N/A pe.printStackTrace();
0N/A
0N/A } catch (Exception e) {
0N/A if (debug != null) {
0N/A debug.println("error parsing "+policy);
0N/A debug.println(e.toString());
0N/A e.printStackTrace();
0N/A }
0N/A } finally {
0N/A if (isr != null) {
0N/A try {
0N/A isr.close();
0N/A success = true;
0N/A } catch (IOException e) {
0N/A // ignore the exception
0N/A }
0N/A } else {
0N/A success = true;
0N/A }
0N/A }
0N/A
0N/A return success;
0N/A }
0N/A
0N/A private void initStaticPolicy(final PolicyInfo newInfo) {
0N/A AccessController.doPrivileged(new PrivilegedAction<Void>() {
0N/A public Void run() {
0N/A PolicyEntry pe = new PolicyEntry(new CodeSource(null,
0N/A (Certificate[]) null));
0N/A pe.add(SecurityConstants.LOCAL_LISTEN_PERMISSION);
0N/A pe.add(new PropertyPermission("java.version",
0N/A SecurityConstants.PROPERTY_READ_ACTION));
0N/A pe.add(new PropertyPermission("java.vendor",
0N/A SecurityConstants.PROPERTY_READ_ACTION));
0N/A pe.add(new PropertyPermission("java.vendor.url",
0N/A SecurityConstants.PROPERTY_READ_ACTION));
0N/A pe.add(new PropertyPermission("java.class.version",
0N/A SecurityConstants.PROPERTY_READ_ACTION));
0N/A pe.add(new PropertyPermission("os.name",
0N/A SecurityConstants.PROPERTY_READ_ACTION));
0N/A pe.add(new PropertyPermission("os.version",
0N/A SecurityConstants.PROPERTY_READ_ACTION));
0N/A pe.add(new PropertyPermission("os.arch",
0N/A SecurityConstants.PROPERTY_READ_ACTION));
0N/A pe.add(new PropertyPermission("file.separator",
0N/A SecurityConstants.PROPERTY_READ_ACTION));
0N/A pe.add(new PropertyPermission("path.separator",
0N/A SecurityConstants.PROPERTY_READ_ACTION));
0N/A pe.add(new PropertyPermission("line.separator",
0N/A SecurityConstants.PROPERTY_READ_ACTION));
0N/A pe.add(new PropertyPermission
0N/A ("java.specification.version",
0N/A SecurityConstants.PROPERTY_READ_ACTION));
0N/A pe.add(new PropertyPermission
0N/A ("java.specification.vendor",
0N/A SecurityConstants.PROPERTY_READ_ACTION));
0N/A pe.add(new PropertyPermission
0N/A ("java.specification.name",
0N/A SecurityConstants.PROPERTY_READ_ACTION));
0N/A pe.add(new PropertyPermission
0N/A ("java.vm.specification.version",
0N/A SecurityConstants.PROPERTY_READ_ACTION));
0N/A pe.add(new PropertyPermission
0N/A ("java.vm.specification.vendor",
0N/A SecurityConstants.PROPERTY_READ_ACTION));
0N/A pe.add(new PropertyPermission
0N/A ("java.vm.specification.name",
0N/A SecurityConstants.PROPERTY_READ_ACTION));
0N/A pe.add(new PropertyPermission("java.vm.version",
0N/A SecurityConstants.PROPERTY_READ_ACTION));
0N/A pe.add(new PropertyPermission("java.vm.vendor",
0N/A SecurityConstants.PROPERTY_READ_ACTION));
0N/A pe.add(new PropertyPermission("java.vm.name",
0N/A SecurityConstants.PROPERTY_READ_ACTION));
0N/A
0N/A // No need to sync because noone has access to newInfo yet
0N/A newInfo.policyEntries.add(pe);
0N/A
0N/A // Add AllPermissions for standard extensions
0N/A String[] extCodebases = PolicyParser.parseExtDirs(
0N/A PolicyParser.EXTDIRS_EXPANSION, 0);
0N/A if (extCodebases != null && extCodebases.length > 0) {
0N/A for (int i = 0; i < extCodebases.length; i++) {
0N/A try {
0N/A pe = new PolicyEntry(canonicalizeCodebase(
0N/A new CodeSource(new URL(extCodebases[i]),
0N/A (Certificate[]) null), false ));
0N/A pe.add(SecurityConstants.ALL_PERMISSION);
0N/A
0N/A // No need to sync because noone has access to
0N/A // newInfo yet
0N/A newInfo.policyEntries.add(pe);
0N/A } catch (Exception e) {
0N/A // this is probably bad (though not dangerous).
0N/A // What should we do?
0N/A }
0N/A }
0N/A }
0N/A return null;
0N/A }
0N/A });
0N/A }
0N/A
0N/A /**
0N/A * Given a GrantEntry, create a codeSource.
0N/A *
0N/A * @return null if signedBy alias is not recognized
0N/A */
0N/A private CodeSource getCodeSource(PolicyParser.GrantEntry ge, KeyStore keyStore,
0N/A PolicyInfo newInfo) throws java.net.MalformedURLException
0N/A {
0N/A Certificate[] certs = null;
0N/A if (ge.signedBy != null) {
0N/A certs = getCertificates(keyStore, ge.signedBy, newInfo);
0N/A if (certs == null) {
0N/A // we don't have a key for this alias,
0N/A // just return
0N/A if (debug != null) {
0N/A debug.println(" -- No certs for alias '" +
0N/A ge.signedBy + "' - ignoring entry");
0N/A }
0N/A return null;
0N/A }
0N/A }
0N/A
0N/A URL location;
0N/A
0N/A if (ge.codeBase != null)
0N/A location = new URL(ge.codeBase);
0N/A else
0N/A location = null;
0N/A
0N/A return (canonicalizeCodebase(new CodeSource(location, certs),false));
0N/A }
0N/A
0N/A /**
0N/A * Add one policy entry to the list.
0N/A */
0N/A private void addGrantEntry(PolicyParser.GrantEntry ge,
0N/A KeyStore keyStore, PolicyInfo newInfo) {
0N/A
0N/A if (debug != null) {
0N/A debug.println("Adding policy entry: ");
0N/A debug.println(" signedBy " + ge.signedBy);
0N/A debug.println(" codeBase " + ge.codeBase);
0N/A if (ge.principals != null && ge.principals.size() > 0) {
0N/A ListIterator<PolicyParser.PrincipalEntry> li =
0N/A ge.principals.listIterator();
0N/A while (li.hasNext()) {
0N/A PolicyParser.PrincipalEntry pppe = li.next();
0N/A debug.println(" " + pppe.toString());
0N/A }
0N/A }
0N/A }
0N/A
0N/A try {
0N/A CodeSource codesource = getCodeSource(ge, keyStore, newInfo);
0N/A // skip if signedBy alias was unknown...
0N/A if (codesource == null) return;
0N/A
0N/A // perform keystore alias principal replacement.
0N/A // for example, if alias resolves to X509 certificate,
0N/A // replace principal with: <X500Principal class> <SubjectDN>
0N/A // -- skip if alias is unknown
0N/A if (replacePrincipals(ge.principals, keyStore) == false)
0N/A return;
0N/A PolicyEntry entry = new PolicyEntry(codesource, ge.principals);
0N/A Enumeration<PolicyParser.PermissionEntry> enum_ =
0N/A ge.permissionElements();
0N/A while (enum_.hasMoreElements()) {
0N/A PolicyParser.PermissionEntry pe = enum_.nextElement();
0N/A
0N/A try {
0N/A // perform ${{ ... }} expansions within permission name
0N/A expandPermissionName(pe, keyStore);
0N/A
0N/A // XXX special case PrivateCredentialPermission-SELF
0N/A Permission perm;
0N/A if (pe.permission.equals
0N/A ("javax.security.auth.PrivateCredentialPermission") &&
0N/A pe.name.endsWith(" self")) {
0N/A pe.name = pe.name.substring(0, pe.name.indexOf("self"))
0N/A + SELF;
0N/A }
0N/A // check for self
0N/A if (pe.name != null && pe.name.indexOf(SELF) != -1) {
0N/A // Create a "SelfPermission" , it could be an
0N/A // an unresolved permission which will be resolved
0N/A // when implies is called
0N/A // Add it to entry
0N/A Certificate certs[];
0N/A if (pe.signedBy != null) {
0N/A certs = getCertificates(keyStore,
0N/A pe.signedBy,
0N/A newInfo);
0N/A } else {
0N/A certs = null;
0N/A }
0N/A perm = new SelfPermission(pe.permission,
0N/A pe.name,
0N/A pe.action,
0N/A certs);
0N/A } else {
0N/A perm = getInstance(pe.permission,
0N/A pe.name,
0N/A pe.action);
0N/A }
0N/A entry.add(perm);
0N/A if (debug != null) {
0N/A debug.println(" "+perm);
0N/A }
0N/A } catch (ClassNotFoundException cnfe) {
0N/A Certificate certs[];
0N/A if (pe.signedBy != null) {
0N/A certs = getCertificates(keyStore,
0N/A pe.signedBy,
0N/A newInfo);
0N/A } else {
0N/A certs = null;
0N/A }
0N/A
0N/A // only add if we had no signer or we had a
0N/A // a signer and found the keys for it.
0N/A if (certs != null || pe.signedBy == null) {
0N/A Permission perm = new UnresolvedPermission(
0N/A pe.permission,
0N/A pe.name,
0N/A pe.action,
0N/A certs);
0N/A entry.add(perm);
0N/A if (debug != null) {
0N/A debug.println(" "+perm);
0N/A }
0N/A }
0N/A } catch (java.lang.reflect.InvocationTargetException ite) {
0N/A MessageFormat form = new MessageFormat
0N/A (ResourcesMgr.getString
0N/A (POLICY +
0N/A ": error adding Permission, perm:\n\tmessage"));
0N/A Object[] source = {pe.permission,
0N/A ite.getTargetException().toString()};
0N/A System.err.println(form.format(source));
0N/A } catch (Exception e) {
0N/A MessageFormat form = new MessageFormat
0N/A (ResourcesMgr.getString
0N/A (POLICY +
0N/A ": error adding Permission, perm:\n\tmessage"));
0N/A Object[] source = {pe.permission,
0N/A e.toString()};
0N/A System.err.println(form.format(source));
0N/A }
0N/A }
0N/A
0N/A // No need to sync because noone has access to newInfo yet
0N/A newInfo.policyEntries.add(entry);
0N/A } catch (Exception e) {
0N/A MessageFormat form = new MessageFormat(ResourcesMgr.getString
0N/A (POLICY
0N/A + ": error adding Entry:\n\tmessage"));
0N/A Object[] source = {e.toString()};
0N/A System.err.println(form.format(source));
0N/A }
0N/A if (debug != null)
0N/A debug.println();
0N/A }
0N/A
0N/A /**
0N/A * Returns a new Permission object of the given Type. The Permission is
0N/A * created by getting the
0N/A * Class object using the <code>Class.forName</code> method, and using
0N/A * the reflection API to invoke the (String name, String actions)
0N/A * constructor on the
0N/A * object.
0N/A *
0N/A * @param type the type of Permission being created.
0N/A * @param name the name of the Permission being created.
0N/A * @param actions the actions of the Permission being created.
0N/A *
0N/A * @exception ClassNotFoundException if the particular Permission
0N/A * class could not be found.
0N/A *
0N/A * @exception IllegalAccessException if the class or initializer is
0N/A * not accessible.
0N/A *
0N/A * @exception InstantiationException if getInstance tries to
0N/A * instantiate an abstract class or an interface, or if the
0N/A * instantiation fails for some other reason.
0N/A *
0N/A * @exception NoSuchMethodException if the (String, String) constructor
0N/A * is not found.
0N/A *
0N/A * @exception InvocationTargetException if the underlying Permission
0N/A * constructor throws an exception.
0N/A *
0N/A */
0N/A
0N/A private static final Permission getInstance(String type,
0N/A String name,
0N/A String actions)
0N/A throws ClassNotFoundException,
0N/A InstantiationException,
0N/A IllegalAccessException,
0N/A NoSuchMethodException,
0N/A InvocationTargetException
0N/A {
0N/A //XXX we might want to keep a hash of created factories...
0N/A Class<?> pc = Class.forName(type);
0N/A Permission answer = getKnownInstance(pc, name, actions);
0N/A if (answer != null) {
0N/A return answer;
0N/A }
0N/A
0N/A if (name == null && actions == null) {
0N/A try {
0N/A Constructor<?> c = pc.getConstructor(PARAMS0);
0N/A return (Permission) c.newInstance(new Object[] {});
0N/A } catch (NoSuchMethodException ne) {
0N/A try {
0N/A Constructor<?> c = pc.getConstructor(PARAMS1);
0N/A return (Permission) c.newInstance(
0N/A new Object[] { name});
0N/A } catch (NoSuchMethodException ne1 ) {
0N/A Constructor<?> c = pc.getConstructor(PARAMS2);
0N/A return (Permission) c.newInstance(
0N/A new Object[] { name, actions });
0N/A }
0N/A }
0N/A } else {
0N/A if (name != null && actions == null) {
0N/A try {
0N/A Constructor<?> c = pc.getConstructor(PARAMS1);
0N/A return (Permission) c.newInstance(new Object[] { name});
0N/A } catch (NoSuchMethodException ne) {
0N/A Constructor<?> c = pc.getConstructor(PARAMS2);
0N/A return (Permission) c.newInstance(
0N/A new Object[] { name, actions });
0N/A }
0N/A } else {
0N/A Constructor<?> c = pc.getConstructor(PARAMS2);
0N/A return (Permission) c.newInstance(
0N/A new Object[] { name, actions });
0N/A }
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Creates one of the well-known permissions directly instead of
0N/A * via reflection. Keep list short to not penalize non-JDK-defined
0N/A * permissions.
0N/A */
0N/A private static final Permission getKnownInstance(Class claz,
0N/A String name, String actions) {
0N/A // XXX shorten list to most popular ones?
0N/A if (claz.equals(FilePermission.class)) {
0N/A return new FilePermission(name, actions);
0N/A } else if (claz.equals(SocketPermission.class)) {
0N/A return new SocketPermission(name, actions);
0N/A } else if (claz.equals(RuntimePermission.class)) {
0N/A return new RuntimePermission(name, actions);
0N/A } else if (claz.equals(PropertyPermission.class)) {
0N/A return new PropertyPermission(name, actions);
0N/A } else if (claz.equals(NetPermission.class)) {
0N/A return new NetPermission(name, actions);
0N/A } else if (claz.equals(AllPermission.class)) {
0N/A return SecurityConstants.ALL_PERMISSION;
0N/A } else if (claz.equals(AWTPermission.class)) {
0N/A return new AWTPermission(name, actions);
0N/A/*
0N/A } else if (claz.equals(ReflectPermission.class)) {
0N/A return new ReflectPermission(name, actions);
0N/A } else if (claz.equals(SecurityPermission.class)) {
0N/A return new SecurityPermission(name, actions);
0N/A } else if (claz.equals(PrivateCredentialPermission.class)) {
0N/A return new PrivateCredentialPermission(name, actions);
0N/A } else if (claz.equals(AuthPermission.class)) {
0N/A return new AuthPermission(name, actions);
0N/A } else if (claz.equals(ServicePermission.class)) {
0N/A return new ServicePermission(name, actions);
0N/A } else if (claz.equals(DelegationPermission.class)) {
0N/A return new DelegationPermission(name, actions);
0N/A } else if (claz.equals(SerializablePermission.class)) {
0N/A return new SerializablePermission(name, actions);
0N/A } else if (claz.equals(AudioPermission.class)) {
0N/A return new AudioPermission(name, actions);
0N/A } else if (claz.equals(SSLPermission.class)) {
0N/A return new SSLPermission(name, actions);
0N/A } else if (claz.equals(LoggingPermission.class)) {
0N/A return new LoggingPermission(name, actions);
0N/A } else if (claz.equals(SQLPermission.class)) {
0N/A return new SQLPermission(name, actions);
0N/A*/
0N/A } else {
0N/A return null;
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Fetch all certs associated with this alias.
0N/A */
0N/A private Certificate[] getCertificates
0N/A (KeyStore keyStore, String aliases, PolicyInfo newInfo) {
0N/A
0N/A List<Certificate> vcerts = null;
0N/A
0N/A StringTokenizer st = new StringTokenizer(aliases, ",");
0N/A int n = 0;
0N/A
0N/A while (st.hasMoreTokens()) {
0N/A String alias = st.nextToken().trim();
0N/A n++;
0N/A Certificate cert = null;
0N/A // See if this alias's cert has already been cached
0N/A synchronized (newInfo.aliasMapping) {
0N/A cert = (Certificate)newInfo.aliasMapping.get(alias);
0N/A
0N/A if (cert == null && keyStore != null) {
0N/A
0N/A try {
0N/A cert = keyStore.getCertificate(alias);
0N/A } catch (KeyStoreException kse) {
0N/A // never happens, because keystore has already been loaded
0N/A // when we call this
0N/A }
0N/A if (cert != null) {
0N/A newInfo.aliasMapping.put(alias, cert);
0N/A newInfo.aliasMapping.put(cert, alias);
0N/A }
0N/A }
0N/A }
0N/A
0N/A if (cert != null) {
0N/A if (vcerts == null)
0N/A vcerts = new ArrayList<Certificate>();
0N/A vcerts.add(cert);
0N/A }
0N/A }
0N/A
0N/A // make sure n == vcerts.size, since we are doing a logical *and*
0N/A if (vcerts != null && n == vcerts.size()) {
0N/A Certificate[] certs = new Certificate[vcerts.size()];
0N/A vcerts.toArray(certs);
0N/A return certs;
0N/A } else {
0N/A return null;
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Refreshes the policy object by re-reading all the policy files.
0N/A */
0N/A public void refresh() {
0N/A init(url);
0N/A }
0N/A
0N/A /**
0N/A * Evaluates the the global policy for the permissions granted to
0N/A * the ProtectionDomain and tests whether the permission is
0N/A * granted.
0N/A *
0N/A * @param domain the ProtectionDomain to test
0N/A * @param permission the Permission object to be tested for implication.
0N/A *
0N/A * @return true if "permission" is a proper subset of a permission
0N/A * granted to this ProtectionDomain.
0N/A *
0N/A * @see java.security.ProtectionDomain
0N/A */
0N/A public boolean implies(ProtectionDomain pd, Permission p) {
0N/A PolicyInfo pi = policyInfo.get();
0N/A Map<ProtectionDomain, PermissionCollection> pdMap = pi.getPdMapping();
0N/A
0N/A PermissionCollection pc = pdMap.get(pd);
0N/A
0N/A if (pc != null) {
0N/A return pc.implies(p);
0N/A }
0N/A
0N/A pc = getPermissions(pd);
0N/A if (pc == null) {
0N/A return false;
0N/A }
0N/A
0N/A // cache mapping of protection domain to its PermissionCollection
0N/A pdMap.put(pd, pc);
0N/A return pc.implies(p);
0N/A }
0N/A
0N/A /**
0N/A * Examines this <code>Policy</code> and returns the permissions granted
0N/A * to the specified <code>ProtectionDomain</code>. This includes
0N/A * the permissions currently associated with the domain as well
0N/A * as the policy permissions granted to the domain's
0N/A * CodeSource, ClassLoader, and Principals.
0N/A *
0N/A * <p> Note that this <code>Policy</code> implementation has
0N/A * special handling for PrivateCredentialPermissions.
0N/A * When this method encounters a <code>PrivateCredentialPermission</code>
0N/A * which specifies "self" as the <code>Principal</code> class and name,
0N/A * it does not add that <code>Permission</code> to the returned
0N/A * <code>PermissionCollection</code>. Instead, it builds
0N/A * a new <code>PrivateCredentialPermission</code>
0N/A * for each <code>Principal</code> associated with the provided
0N/A * <code>Subject</code>. Each new <code>PrivateCredentialPermission</code>
0N/A * contains the same Credential class as specified in the
0N/A * originally granted permission, as well as the Class and name
0N/A * for the respective <code>Principal</code>.
0N/A *
0N/A * <p>
0N/A *
0N/A * @param domain the Permissions granted to this
0N/A * <code>ProtectionDomain</code> are returned.
0N/A *
0N/A * @return the Permissions granted to the provided
0N/A * <code>ProtectionDomain</code>.
0N/A */
0N/A public PermissionCollection getPermissions(ProtectionDomain domain) {
0N/A Permissions perms = new Permissions();
0N/A
0N/A if (domain == null)
0N/A return perms;
0N/A
0N/A // first get policy perms
0N/A getPermissions(perms, domain);
0N/A
0N/A // add static perms
0N/A // - adding static perms after policy perms is necessary
0N/A // to avoid a regression for 4301064
0N/A PermissionCollection pc = domain.getPermissions();
0N/A if (pc != null) {
0N/A synchronized (pc) {
0N/A Enumeration<Permission> e = pc.elements();
0N/A while (e.hasMoreElements()) {
0N/A perms.add(e.nextElement());
0N/A }
0N/A }
0N/A }
0N/A
0N/A return perms;
0N/A }
0N/A
0N/A /**
0N/A * Examines this Policy and creates a PermissionCollection object with
0N/A * the set of permissions for the specified CodeSource.
0N/A *
0N/A * @param CodeSource the codesource associated with the caller.
0N/A * This encapsulates the original location of the code (where the code
0N/A * came from) and the public key(s) of its signer.
0N/A *
0N/A * @return the set of permissions according to the policy.
0N/A */
0N/A public PermissionCollection getPermissions(CodeSource codesource) {
0N/A return getPermissions(new Permissions(), codesource);
0N/A }
0N/A
0N/A /**
0N/A * Examines the global policy and returns the provided Permissions
0N/A * object with additional permissions granted to the specified
0N/A * ProtectionDomain.
0N/A *
0N/A * @param perm the Permissions to populate
0N/A * @param pd the ProtectionDomain associated with the caller.
0N/A *
0N/A * @return the set of Permissions according to the policy.
0N/A */
0N/A private PermissionCollection getPermissions(Permissions perms,
0N/A ProtectionDomain pd ) {
0N/A if (debug != null) {
0N/A debug.println("getPermissions:\n\t" + printPD(pd));
0N/A }
0N/A
0N/A final CodeSource cs = pd.getCodeSource();
0N/A if (cs == null)
0N/A return perms;
0N/A
0N/A CodeSource canonCodeSource = AccessController.doPrivileged(
0N/A new java.security.PrivilegedAction<CodeSource>(){
0N/A public CodeSource run() {
0N/A return canonicalizeCodebase(cs, true);
0N/A }
0N/A });
0N/A return getPermissions(perms, canonCodeSource, pd.getPrincipals());
0N/A }
0N/A
0N/A /**
0N/A * Examines the global policy and returns the provided Permissions
0N/A * object with additional permissions granted to the specified
0N/A * CodeSource.
0N/A *
0N/A * @param permissions the permissions to populate
0N/A * @param codesource the codesource associated with the caller.
782N/A * This encapsulates the original location of the code (where the code
782N/A * came from) and the public key(s) of its signer.
782N/A *
0N/A * @return the set of permissions according to the policy.
0N/A */
0N/A private PermissionCollection getPermissions(Permissions perms,
0N/A final CodeSource cs) {
0N/A
0N/A CodeSource canonCodeSource = AccessController.doPrivileged(
0N/A new java.security.PrivilegedAction<CodeSource>(){
0N/A public CodeSource run() {
0N/A return canonicalizeCodebase(cs, true);
0N/A }
0N/A });
0N/A
0N/A return getPermissions(perms, canonCodeSource, null);
0N/A }
0N/A
0N/A private Permissions getPermissions(Permissions perms,
0N/A final CodeSource cs,
0N/A Principal[] principals) {
0N/A PolicyInfo pi = policyInfo.get();
0N/A
0N/A for (PolicyEntry entry : pi.policyEntries) {
0N/A addPermissions(perms, cs, principals, entry);
0N/A }
0N/A
0N/A // Go through policyEntries gotten from identity db; sync required
0N/A // because checkForTrustedIdentity (below) might update list
0N/A synchronized (pi.identityPolicyEntries) {
0N/A for (PolicyEntry entry : pi.identityPolicyEntries) {
0N/A addPermissions(perms, cs, principals, entry);
0N/A }
0N/A }
0N/A
0N/A // now see if any of the keys are trusted ids.
0N/A if (!ignoreIdentityScope) {
0N/A Certificate certs[] = cs.getCertificates();
0N/A if (certs != null) {
0N/A for (int k=0; k < certs.length; k++) {
0N/A Object idMap = pi.aliasMapping.get(certs[k]);
0N/A if (idMap == null &&
0N/A checkForTrustedIdentity(certs[k], pi)) {
782N/A // checkForTrustedIdentity added it
782N/A // to the policy for us. next time
782N/A // around we'll find it. This time
782N/A // around we need to add it.
0N/A perms.add(SecurityConstants.ALL_PERMISSION);
0N/A }
0N/A }
0N/A }
0N/A }
0N/A return perms;
0N/A }
0N/A
0N/A private void addPermissions(Permissions perms,
0N/A final CodeSource cs,
0N/A Principal[] principals,
0N/A final PolicyEntry entry) {
0N/A
0N/A if (debug != null) {
0N/A debug.println("evaluate codesources:\n" +
0N/A "\tPolicy CodeSource: " + entry.getCodeSource() + "\n" +
0N/A "\tActive CodeSource: " + cs);
0N/A }
0N/A
0N/A // check to see if the CodeSource implies
0N/A Boolean imp = AccessController.doPrivileged
0N/A (new PrivilegedAction<Boolean>() {
0N/A public Boolean run() {
0N/A return new Boolean(entry.getCodeSource().implies(cs));
0N/A }
0N/A });
0N/A if (!imp.booleanValue()) {
0N/A if (debug != null) {
0N/A debug.println("evaluation (codesource) failed");
0N/A }
0N/A
0N/A // CodeSource does not imply - return and try next policy entry
0N/A return;
0N/A }
0N/A
0N/A // check to see if the Principals imply
0N/A
0N/A List<PolicyParser.PrincipalEntry> entryPs = entry.getPrincipals();
0N/A if (debug != null) {
0N/A ArrayList<PolicyParser.PrincipalEntry> accPs =
0N/A new ArrayList<PolicyParser.PrincipalEntry>();
0N/A if (principals != null) {
0N/A for (int i = 0; i < principals.length; i++) {
0N/A accPs.add(new PolicyParser.PrincipalEntry
0N/A (principals[i].getClass().getName(),
0N/A principals[i].getName()));
0N/A }
0N/A }
0N/A debug.println("evaluate principals:\n" +
0N/A "\tPolicy Principals: " + entryPs + "\n" +
0N/A "\tActive Principals: " + accPs);
0N/A }
0N/A
0N/A if (entryPs == null || entryPs.size() == 0) {
0N/A
0N/A // policy entry has no principals -
0N/A // add perms regardless of principals in current ACC
0N/A
0N/A addPerms(perms, principals, entry);
0N/A if (debug != null) {
0N/A debug.println("evaluation (codesource/principals) passed");
0N/A }
0N/A return;
0N/A
0N/A } else if (principals == null || principals.length == 0) {
0N/A
0N/A // current thread has no principals but this policy entry
0N/A // has principals - perms are not added
0N/A
0N/A if (debug != null) {
0N/A debug.println("evaluation (principals) failed");
0N/A }
0N/A return;
0N/A }
0N/A
0N/A // current thread has principals and this policy entry
0N/A // has principals. see if policy entry principals match
0N/A // principals in current ACC
0N/A
0N/A for (int i = 0; i < entryPs.size(); i++) {
0N/A PolicyParser.PrincipalEntry pppe = entryPs.get(i);
0N/A
0N/A // see if principal entry is a PrincipalComparator
0N/A
0N/A try {
0N/A Class<?> pClass = Class.forName
0N/A (pppe.principalClass,
0N/A true,
0N/A Thread.currentThread().getContextClassLoader());
0N/A
0N/A if (!PrincipalComparator.class.isAssignableFrom(pClass)) {
0N/A
0N/A // common case - dealing with regular Principal class.
0N/A // see if policy entry principal is in current ACC
0N/A
0N/A if (!checkEntryPs(principals, pppe)) {
0N/A if (debug != null) {
0N/A debug.println("evaluation (principals) failed");
0N/A }
0N/A
0N/A // policy entry principal not in current ACC -
0N/A // immediately return and go to next policy entry
0N/A return;
0N/A }
0N/A
0N/A } else {
0N/A
0N/A // dealing with a PrincipalComparator
0N/A
0N/A Constructor<?> c = pClass.getConstructor(PARAMS1);
0N/A PrincipalComparator pc = (PrincipalComparator)c.newInstance
0N/A (new Object[] { pppe.principalName });
0N/A
0N/A if (debug != null) {
0N/A debug.println("found PrincipalComparator " +
0N/A pc.getClass().getName());
0N/A }
0N/A
0N/A // check if the PrincipalComparator
0N/A // implies the current thread's principals
0N/A
0N/A Set<Principal> pSet =
0N/A new HashSet<Principal>(principals.length);
0N/A for (int j = 0; j < principals.length; j++) {
0N/A pSet.add(principals[j]);
0N/A }
0N/A Subject subject = new Subject(true,
0N/A pSet,
0N/A Collections.EMPTY_SET,
0N/A Collections.EMPTY_SET);
0N/A
0N/A if (!pc.implies(subject)) {
0N/A if (debug != null) {
0N/A debug.println
0N/A ("evaluation (principal comparator) failed");
0N/A }
0N/A
0N/A // policy principal does not imply the current Subject -
0N/A // immediately return and go to next policy entry
0N/A return;
0N/A }
0N/A }
0N/A } catch (Exception e) {
0N/A // fall back to regular principal comparison.
0N/A // see if policy entry principal is in current ACC
0N/A
0N/A if (debug != null) {
0N/A e.printStackTrace();
0N/A }
0N/A
0N/A if (!checkEntryPs(principals, pppe)) {
0N/A if (debug != null) {
0N/A debug.println("evaluation (principals) failed");
0N/A }
0N/A
0N/A // policy entry principal not in current ACC -
0N/A // immediately return and go to next policy entry
0N/A return;
0N/A }
0N/A }
0N/A
0N/A // either the principal information matched,
0N/A // or the PrincipalComparator.implies succeeded.
0N/A // continue loop and test the next policy principal
0N/A }
0N/A
0N/A // all policy entry principals were found in the current ACC -
0N/A // grant the policy permissions
0N/A
0N/A if (debug != null) {
0N/A debug.println("evaluation (codesource/principals) passed");
0N/A }
0N/A addPerms(perms, principals, entry);
0N/A }
0N/A
0N/A private void addPerms(Permissions perms,
0N/A Principal[] accPs,
0N/A PolicyEntry entry) {
0N/A for (int i = 0; i < entry.permissions.size(); i++) {
0N/A Permission p = entry.permissions.get(i);
0N/A if (debug != null) {
0N/A debug.println(" granting " + p);
0N/A }
0N/A
0N/A if (p instanceof SelfPermission) {
0N/A // handle "SELF" permissions
782N/A expandSelf((SelfPermission)p,
782N/A entry.getPrincipals(),
782N/A accPs,
782N/A perms);
0N/A } else {
0N/A perms.add(p);
0N/A }
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * This method returns, true, if the principal in the policy entry,
0N/A * pppe, is part of the current thread's principal array, pList.
0N/A * This method also returns, true, if the policy entry's principal
0N/A * is appropriately wildcarded.
0N/A *
0N/A * Note that the provided <i>pppe</i> argument may have
0N/A * wildcards (*) for both the <code>Principal</code> class and name.
0N/A *
0N/A * @param pList an array of principals from the current thread's
0N/A * AccessControlContext.
0N/A *
0N/A * @param pppe a Principal specified in a policy grant entry.
0N/A *
0N/A * @return true if the current thread's pList "contains" the
0N/A * principal in the policy entry, pppe. This method
0N/A * also returns true if the policy entry's principal
0N/A * appropriately wildcarded.
0N/A */
0N/A private boolean checkEntryPs(Principal[] pList,
0N/A PolicyParser.PrincipalEntry pppe) {
0N/A
0N/A for (int i = 0; i < pList.length; i++) {
0N/A
0N/A if (pppe.principalClass.equals
0N/A (PolicyParser.PrincipalEntry.WILDCARD_CLASS) ||
0N/A pppe.principalClass.equals
0N/A (pList[i].getClass().getName())) {
0N/A
0N/A if (pppe.principalName.equals
0N/A (PolicyParser.PrincipalEntry.WILDCARD_NAME) ||
0N/A pppe.principalName.equals
0N/A (pList[i].getName())) {
0N/A
0N/A return true;
0N/A }
0N/A }
0N/A }
0N/A return false;
0N/A }
0N/A
0N/A /**
0N/A * <p>
0N/A *
0N/A * @param sp the SelfPermission that needs to be expanded <p>
0N/A *
0N/A * @param entryPs list of principals for the Policy entry.
0N/A *
0N/A * @param pdp Principal array from the current ProtectionDomain.
0N/A *
0N/A * @param perms the PermissionCollection where the individual
0N/A * Permissions will be added after expansion.
0N/A */
0N/A
0N/A private void expandSelf(SelfPermission sp,
0N/A List<PolicyParser.PrincipalEntry> entryPs,
0N/A Principal[] pdp,
0N/A Permissions perms) {
0N/A
0N/A if (entryPs == null || entryPs.size() == 0) {
0N/A // No principals in the grant to substitute
0N/A if (debug != null) {
0N/A debug.println("Ignoring permission "
0N/A + sp.getSelfType()
0N/A + " with target name ("
0N/A + sp.getSelfName() + "). "
0N/A + "No Principal(s) specified "
0N/A + "in the grant clause. "
0N/A + "SELF-based target names are "
0N/A + "only valid in the context "
0N/A + "of a Principal-based grant entry."
0N/A );
0N/A }
0N/A return;
0N/A }
0N/A int startIndex = 0;
0N/A int v;
0N/A StringBuilder sb = new StringBuilder();
0N/A while ((v = sp.getSelfName().indexOf(SELF, startIndex)) != -1) {
0N/A
0N/A // add non-SELF string
0N/A sb.append(sp.getSelfName().substring(startIndex, v));
0N/A
0N/A // expand SELF
0N/A ListIterator<PolicyParser.PrincipalEntry> pli =
0N/A entryPs.listIterator();
0N/A while (pli.hasNext()) {
0N/A PolicyParser.PrincipalEntry pppe = pli.next();
0N/A String[][] principalInfo = getPrincipalInfo(pppe,pdp);
0N/A for (int i = 0; i < principalInfo.length; i++) {
0N/A if (i != 0) {
0N/A sb.append(", ");
0N/A }
0N/A sb.append(principalInfo[i][0] + " " +
0N/A "\"" + principalInfo[i][1] + "\"");
0N/A }
0N/A if (pli.hasNext()) {
0N/A sb.append(", ");
0N/A }
0N/A }
0N/A startIndex = v + SELF.length();
0N/A }
0N/A // add remaining string (might be the entire string)
0N/A sb.append(sp.getSelfName().substring(startIndex));
0N/A
0N/A if (debug != null) {
0N/A debug.println(" expanded:\n\t" + sp.getSelfName()
0N/A + "\n into:\n\t" + sb.toString());
0N/A }
0N/A try {
0N/A // first try to instantiate the permission
0N/A perms.add(getInstance(sp.getSelfType(),
0N/A sb.toString(),
0N/A sp.getSelfActions()));
0N/A } catch (ClassNotFoundException cnfe) {
0N/A // ok, the permission is not in the bootclasspath.
0N/A // before we add an UnresolvedPermission, check to see
0N/A // whether this perm already belongs to the collection.
0N/A // if so, use that perm's ClassLoader to create a new
0N/A // one.
0N/A Class<?> pc = null;
0N/A synchronized (perms) {
0N/A Enumeration<Permission> e = perms.elements();
0N/A while (e.hasMoreElements()) {
0N/A Permission pElement = e.nextElement();
0N/A if (pElement.getClass().getName().equals(sp.getSelfType())) {
0N/A pc = pElement.getClass();
0N/A break;
0N/A }
0N/A }
0N/A }
0N/A if (pc == null) {
0N/A // create an UnresolvedPermission
0N/A perms.add(new UnresolvedPermission(sp.getSelfType(),
0N/A sb.toString(),
0N/A sp.getSelfActions(),
0N/A sp.getCerts()));
0N/A } else {
0N/A try {
0N/A // we found an instantiated permission.
0N/A // use its class loader to instantiate a new permission.
0N/A Constructor<?> c;
0N/A // name parameter can not be null
0N/A if (sp.getSelfActions() == null) {
0N/A try {
0N/A c = pc.getConstructor(PARAMS1);
0N/A perms.add((Permission)c.newInstance
0N/A (new Object[] {sb.toString()}));
0N/A } catch (NoSuchMethodException ne) {
0N/A c = pc.getConstructor(PARAMS2);
0N/A perms.add((Permission)c.newInstance
0N/A (new Object[] {sb.toString(),
0N/A sp.getSelfActions() }));
0N/A }
0N/A } else {
0N/A c = pc.getConstructor(PARAMS2);
0N/A perms.add((Permission)c.newInstance
0N/A (new Object[] {sb.toString(),
0N/A sp.getSelfActions()}));
0N/A }
0N/A } catch (Exception nme) {
0N/A if (debug != null) {
0N/A debug.println("self entry expansion " +
0N/A " instantiation failed: "
0N/A + nme.toString());
0N/A }
0N/A }
0N/A }
0N/A } catch (Exception e) {
0N/A if (debug != null) {
0N/A debug.println(e.toString());
0N/A }
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * return the principal class/name pair in the 2D array.
0N/A * array[x][y]: x corresponds to the array length.
0N/A * if (y == 0), it's the principal class.
0N/A * if (y == 1), it's the principal name.
0N/A */
0N/A private String[][] getPrincipalInfo
0N/A (PolicyParser.PrincipalEntry pe, Principal[] pdp) {
0N/A
0N/A // there are 3 possibilities:
0N/A // 1) the entry's Principal class and name are not wildcarded
0N/A // 2) the entry's Principal name is wildcarded only
0N/A // 3) the entry's Principal class and name are wildcarded
0N/A
0N/A if (!pe.principalClass.equals
0N/A (PolicyParser.PrincipalEntry.WILDCARD_CLASS) &&
0N/A !pe.principalName.equals
0N/A (PolicyParser.PrincipalEntry.WILDCARD_NAME)) {
0N/A
0N/A // build an info array for the principal
0N/A // from the Policy entry
0N/A String[][] info = new String[1][2];
0N/A info[0][0] = pe.principalClass;
0N/A info[0][1] = pe.principalName;
0N/A return info;
0N/A
0N/A } else if (!pe.principalClass.equals
0N/A (PolicyParser.PrincipalEntry.WILDCARD_CLASS) &&
0N/A pe.principalName.equals
0N/A (PolicyParser.PrincipalEntry.WILDCARD_NAME)) {
0N/A
0N/A // build an info array for every principal
0N/A // in the current domain which has a principal class
0N/A // that is equal to policy entry principal class name
0N/A List<Principal> plist = new ArrayList<Principal>();
0N/A for (int i = 0; i < pdp.length; i++) {
0N/A if(pe.principalClass.equals(pdp[i].getClass().getName()))
0N/A plist.add(pdp[i]);
0N/A }
0N/A String[][] info = new String[plist.size()][2];
0N/A int i = 0;
0N/A java.util.Iterator<Principal> pIterator = plist.iterator();
0N/A while (pIterator.hasNext()) {
0N/A Principal p = pIterator.next();
0N/A info[i][0] = p.getClass().getName();
0N/A info[i][1] = p.getName();
0N/A i++;
0N/A }
0N/A return info;
0N/A
0N/A } else {
0N/A
0N/A // build an info array for every
0N/A // one of the current Domain's principals
0N/A
0N/A String[][] info = new String[pdp.length][2];
0N/A
0N/A for (int i = 0; i < pdp.length; i++) {
0N/A info[i][0] = pdp[i].getClass().getName();
0N/A info[i][1] = pdp[i].getName();
0N/A }
0N/A return info;
0N/A }
0N/A }
0N/A
0N/A /*
0N/A * Returns the signer certificates from the list of certificates
0N/A * associated with the given code source.
0N/A *
0N/A * The signer certificates are those certificates that were used
0N/A * to verifysigned code originating from the codesource location.
0N/A *
0N/A * This method assumes that in the given code source, each signer
0N/A * certificate is followed by its supporting certificate chain
0N/A * (which may be empty), and that the signer certificate and its
0N/A * supporting certificate chain are ordered bottom-to-top
0N/A * (i.e., with the signer certificate first and the (root) certificate
0N/A * authority last).
0N/A */
0N/A protected Certificate[] getSignerCertificates(CodeSource cs) {
0N/A Certificate[] certs = null;
0N/A if ((certs = cs.getCertificates()) == null)
0N/A return null;
0N/A for (int i=0; i<certs.length; i++) {
0N/A if (!(certs[i] instanceof X509Certificate))
0N/A return cs.getCertificates();
0N/A }
0N/A
0N/A // Do we have to do anything?
0N/A int i = 0;
0N/A int count = 0;
0N/A while (i < certs.length) {
0N/A count++;
0N/A while (((i+1) < certs.length)
0N/A && ((X509Certificate)certs[i]).getIssuerDN().equals(
0N/A ((X509Certificate)certs[i+1]).getSubjectDN())) {
0N/A i++;
0N/A }
0N/A i++;
0N/A }
0N/A if (count == certs.length)
0N/A // Done
0N/A return certs;
0N/A
0N/A ArrayList<Certificate> userCertList = new ArrayList<Certificate>();
0N/A i = 0;
0N/A while (i < certs.length) {
0N/A userCertList.add(certs[i]);
0N/A while (((i+1) < certs.length)
0N/A && ((X509Certificate)certs[i]).getIssuerDN().equals(
0N/A ((X509Certificate)certs[i+1]).getSubjectDN())) {
0N/A i++;
0N/A }
0N/A i++;
0N/A }
0N/A Certificate[] userCerts = new Certificate[userCertList.size()];
0N/A userCertList.toArray(userCerts);
0N/A return userCerts;
0N/A }
0N/A
0N/A private CodeSource canonicalizeCodebase(CodeSource cs,
0N/A boolean extractSignerCerts) {
0N/A
0N/A String path = null;
0N/A
0N/A CodeSource canonCs = cs;
0N/A URL u = cs.getLocation();
0N/A if (u != null && u.getProtocol().equals("file")) {
0N/A boolean isLocalFile = false;
0N/A String host = u.getHost();
0N/A isLocalFile = (host == null || host.equals("") ||
0N/A host.equals("~") || host.equalsIgnoreCase("localhost"));
0N/A
0N/A if (isLocalFile) {
0N/A path = u.getFile().replace('/', File.separatorChar);
0N/A path = ParseUtil.decode(path);
0N/A }
0N/A }
0N/A
0N/A if (path != null) {
0N/A try {
0N/A URL csUrl = null;
0N/A path = canonPath(path);
0N/A csUrl = ParseUtil.fileToEncodedURL(new File(path));
0N/A
0N/A if (extractSignerCerts) {
0N/A canonCs = new CodeSource(csUrl,
0N/A getSignerCertificates(cs));
0N/A } else {
0N/A canonCs = new CodeSource(csUrl,
0N/A cs.getCertificates());
0N/A }
0N/A } catch (IOException ioe) {
0N/A // leave codesource as it is, unless we have to extract its
0N/A // signer certificates
0N/A if (extractSignerCerts) {
0N/A canonCs = new CodeSource(cs.getLocation(),
0N/A getSignerCertificates(cs));
0N/A }
0N/A }
0N/A } else {
0N/A if (extractSignerCerts) {
0N/A canonCs = new CodeSource(cs.getLocation(),
0N/A getSignerCertificates(cs));
0N/A }
0N/A }
0N/A return canonCs;
0N/A }
0N/A
0N/A // public for java.io.FilePermission
0N/A public static String canonPath(String path) throws IOException {
0N/A if (path.endsWith("*")) {
0N/A path = path.substring(0, path.length()-1) + "-";
0N/A path = new File(path).getCanonicalPath();
0N/A return path.substring(0, path.length()-1) + "*";
0N/A } else {
0N/A return new File(path).getCanonicalPath();
0N/A }
0N/A }
0N/A
0N/A private String printPD(ProtectionDomain pd) {
0N/A Principal[] principals = pd.getPrincipals();
String pals = "<no principals>";
if (principals != null && principals.length > 0) {
StringBuilder palBuf = new StringBuilder("(principals ");
for (int i = 0; i < principals.length; i++) {
palBuf.append(principals[i].getClass().getName() +
" \"" + principals[i].getName() +
"\"");
if (i < principals.length-1)
palBuf.append(", ");
else
palBuf.append(")");
}
pals = palBuf.toString();
}
return "PD CodeSource: "
+ pd.getCodeSource()
+"\n\t" + "PD ClassLoader: "
+ pd.getClassLoader()
+"\n\t" + "PD Principals: "
+ pals;
}
/**
* return true if no replacement was performed,
* or if replacement succeeded.
*/
private boolean replacePrincipals(
List<PolicyParser.PrincipalEntry> principals, KeyStore keystore) {
if (principals == null || principals.size() == 0 || keystore == null)
return true;
ListIterator<PolicyParser.PrincipalEntry> i = principals.listIterator();
while (i.hasNext()) {
PolicyParser.PrincipalEntry pppe = i.next();
if (pppe.principalClass.equals(PolicyParser.REPLACE_NAME)) {
// perform replacement
// (only X509 replacement is possible now)
String name;
if ((name = getDN(pppe.principalName, keystore)) == null) {
return false;
}
if (debug != null) {
debug.println(" Replacing \"" +
pppe.principalName +
"\" with " +
X500PRINCIPAL + "/\"" +
name +
"\"");
}
pppe.principalClass = X500PRINCIPAL;
pppe.principalName = name;
}
}
// return true if no replacement was performed,
// or if replacement succeeded
return true;
}
private void expandPermissionName(PolicyParser.PermissionEntry pe,
KeyStore keystore) throws Exception {
// short cut the common case
if (pe.name == null || pe.name.indexOf("${{", 0) == -1) {
return;
}
int startIndex = 0;
int b, e;
StringBuilder sb = new StringBuilder();
while ((b = pe.name.indexOf("${{", startIndex)) != -1) {
e = pe.name.indexOf("}}", b);
if (e < 1) {
break;
}
sb.append(pe.name.substring(startIndex, b));
// get the value in ${{...}}
String value = pe.name.substring(b+3, e);
// parse up to the first ':'
int colonIndex;
String prefix = value;
String suffix;
if ((colonIndex = value.indexOf(":")) != -1) {
prefix = value.substring(0, colonIndex);
}
// handle different prefix possibilities
if (prefix.equalsIgnoreCase("self")) {
// do nothing - handled later
sb.append(pe.name.substring(b, e+2));
startIndex = e+2;
continue;
} else if (prefix.equalsIgnoreCase("alias")) {
// get the suffix and perform keystore alias replacement
if (colonIndex == -1) {
MessageFormat form = new MessageFormat
(ResourcesMgr.getString
("alias name not provided (pe.name)"));
Object[] source = {pe.name};
throw new Exception(form.format(source));
}
suffix = value.substring(colonIndex+1);
if ((suffix = getDN(suffix, keystore)) == null) {
MessageFormat form = new MessageFormat
(ResourcesMgr.getString
("unable to perform substitution on alias, suffix"));
Object[] source = {value.substring(colonIndex+1)};
throw new Exception(form.format(source));
}
sb.append(X500PRINCIPAL + " \"" + suffix + "\"");
startIndex = e+2;
} else {
MessageFormat form = new MessageFormat
(ResourcesMgr.getString
("substitution value, prefix, unsupported"));
Object[] source = {prefix};
throw new Exception(form.format(source));
}
}
// copy the rest of the value
sb.append(pe.name.substring(startIndex));
// replace the name with expanded value
if (debug != null) {
debug.println(" Permission name expanded from:\n\t" +
pe.name + "\nto\n\t" + sb.toString());
}
pe.name = sb.toString();
}
private String getDN(String alias, KeyStore keystore) {
Certificate cert = null;
try {
cert = keystore.getCertificate(alias);
} catch (Exception e) {
if (debug != null) {
debug.println(" Error retrieving certificate for '" +
alias +
"': " +
e.toString());
}
return null;
}
if (cert == null || !(cert instanceof X509Certificate)) {
if (debug != null) {
debug.println(" -- No certificate for '" +
alias +
"' - ignoring entry");
}
return null;
} else {
X509Certificate x509Cert = (X509Certificate)cert;
// 4702543: X500 names with an EmailAddress
// were encoded incorrectly. create new
// X500Principal name with correct encoding
X500Principal p = new X500Principal
(x509Cert.getSubjectX500Principal().toString());
return p.getName();
}
}
/**
* Checks public key. If it is marked as trusted in
* the identity database, add it to the policy
* with the AllPermission.
*/
private boolean checkForTrustedIdentity(final Certificate cert,
PolicyInfo myInfo)
{
if (cert == null)
return false;
// see if we are ignoring the identity scope or not
if (ignoreIdentityScope)
return false;
// try to initialize scope
synchronized(PolicyFile.class) {
if (scope == null) {
IdentityScope is = IdentityScope.getSystemScope();
if (is instanceof sun.security.provider.IdentityDatabase) {
scope = is;
} else {
// leave scope null
}
}
}
if (scope == null) {
ignoreIdentityScope = true;
return false;
}
// need privileged block for getIdentity in case we are trying
// to get a signer
final Identity id = AccessController.doPrivileged(
new java.security.PrivilegedAction<Identity>() {
public Identity run() {
return scope.getIdentity(cert.getPublicKey());
}
});
if (isTrusted(id)) {
if (debug != null) {
debug.println("Adding policy entry for trusted Identity: ");
//needed for identity toString!
AccessController.doPrivileged(
new java.security.PrivilegedAction<Void>() {
public Void run() {
debug.println(" identity = " + id);
return null;
}
});
debug.println("");
}
// add it to the policy for future reference
Certificate certs[] = new Certificate[] {cert};
PolicyEntry pe = new PolicyEntry(new CodeSource(null, certs));
pe.add(SecurityConstants.ALL_PERMISSION);
myInfo.identityPolicyEntries.add(pe);
// add it to the mapping as well so
// we don't have to go through this again
myInfo.aliasMapping.put(cert, id.getName());
return true;
}
return false;
}
private static boolean isTrusted(Identity id) {
if (id instanceof SystemIdentity) {
SystemIdentity sysid = (SystemIdentity)id;
if (sysid.isTrusted()) {
return true;
}
} else if (id instanceof SystemSigner) {
SystemSigner sysid = (SystemSigner)id;
if (sysid.isTrusted()) {
return true;
}
}
return false;
}
/**
* Each entry in the policy configuration file is represented by a
* PolicyEntry object. <p>
*
* 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. <p>
*
* The Permission contains the (Type, Name, Action) triplet. <p>
*
* For now, the Policy object retrieves the public key from the
* X.509 certificate on disk that corresponds to the signedBy
* alias specified in the Policy config file. For reasons of
* efficiency, the Policy object keeps a hashtable of certs already
* read in. This could be replaced by a secure internal key
* store.
*
* <p>
* For example, the entry
* <pre>
* permission java.io.File "/tmp", "read,write",
* signedBy "Duke";
* </pre>
* is represented internally
* <pre>
*
* FilePermission f = new FilePermission("/tmp", "read,write");
* PublicKey p = publickeys.get("Duke");
* URL u = InetAddress.getLocalHost();
* CodeBase c = new CodeBase( p, u );
* pe = new PolicyEntry(f, c);
* </pre>
*
* @author Marianne Mueller
* @author Roland Schemers
* @see java.security.CodeSource
* @see java.security.Policy
* @see java.security.Permissions
* @see java.security.ProtectionDomain
*/
private static class PolicyEntry {
private final CodeSource codesource;
final List<Permission> permissions;
private final List<PolicyParser.PrincipalEntry> principals;
/**
* Given a Permission and a CodeSource, create a policy entry.
*
* XXX Decide if/how to add validity fields and "purpose" fields to
* XXX policy entries
*
* @param cs the CodeSource, which encapsulates the URL and the
* public key
* attributes from the policy config file. Validity checks
* are performed on the public key before PolicyEntry is
* called.
*
*/
PolicyEntry(CodeSource cs, List<PolicyParser.PrincipalEntry> principals)
{
this.codesource = cs;
this.permissions = new ArrayList<Permission>();
this.principals = principals; // can be null
}
PolicyEntry(CodeSource cs)
{
this(cs, null);
}
List<PolicyParser.PrincipalEntry> getPrincipals() {
return principals; // can be null
}
/**
* add a Permission object to this entry.
* No need to sync add op because perms are added to entry only
* while entry is being initialized
*/
void add(Permission p) {
permissions.add(p);
}
/**
* Return the CodeSource for this policy entry
*/
CodeSource getCodeSource() {
return codesource;
}
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append(ResourcesMgr.getString("("));
sb.append(getCodeSource());
sb.append("\n");
for (int j = 0; j < permissions.size(); j++) {
Permission p = permissions.get(j);
sb.append(ResourcesMgr.getString(" "));
sb.append(ResourcesMgr.getString(" "));
sb.append(p);
sb.append(ResourcesMgr.getString("\n"));
}
sb.append(ResourcesMgr.getString(")"));
sb.append(ResourcesMgr.getString("\n"));
return sb.toString();
}
}
private static class SelfPermission extends Permission {
private static final long serialVersionUID = -8315562579967246806L;
/**
* The class name of the Permission class that will be
* created when this self permission is expanded .
*
* @serial
*/
private String type;
/**
* The permission name.
*
* @serial
*/
private String name;
/**
* The actions of the permission.
*
* @serial
*/
private String actions;
/**
* The certs of the permission.
*
* @serial
*/
private Certificate certs[];
/**
* Creates a new SelfPermission containing the permission
* information needed later to expand the self
* @param type the class name of the Permission class that will be
* created when this permission is expanded and if necessary resolved.
* @param name the name of the permission.
* @param actions the actions of the permission.
* @param certs the certificates the permission's class was signed with.
* This is a list of certificate chains, where each chain is composed of
* a signer certificate and optionally its supporting certificate chain.
* Each chain is ordered bottom-to-top (i.e., with the signer
* certificate first and the (root) certificate authority last).
*/
public SelfPermission(String type, String name, String actions,
Certificate certs[])
{
super(type);
if (type == null) {
throw new NullPointerException
(ResourcesMgr.getString("type can't be null"));
}
this.type = type;
this.name = name;
this.actions = actions;
if (certs != null) {
// Extract the signer certs from the list of certificates.
for (int i=0; i<certs.length; i++) {
if (!(certs[i] instanceof X509Certificate)) {
// there is no concept of signer certs, so we store the
// entire cert array
this.certs = certs.clone();
break;
}
}
if (this.certs == null) {
// Go through the list of certs and see if all the certs are
// signer certs.
int i = 0;
int count = 0;
while (i < certs.length) {
count++;
while (((i+1) < certs.length) &&
((X509Certificate)certs[i]).getIssuerDN().equals(
((X509Certificate)certs[i+1]).getSubjectDN())) {
i++;
}
i++;
}
if (count == certs.length) {
// All the certs are signer certs, so we store the
// entire array
this.certs = certs.clone();
}
if (this.certs == null) {
// extract the signer certs
ArrayList<Certificate> signerCerts =
new ArrayList<Certificate>();
i = 0;
while (i < certs.length) {
signerCerts.add(certs[i]);
while (((i+1) < certs.length) &&
((X509Certificate)certs[i]).getIssuerDN().equals(
((X509Certificate)certs[i+1]).getSubjectDN())) {
i++;
}
i++;
}
this.certs = new Certificate[signerCerts.size()];
signerCerts.toArray(this.certs);
}
}
}
}
/**
* This method always returns false for SelfPermission permissions.
* That is, an SelfPermission never considered to
* imply another permission.
*
* @param p the permission to check against.
*
* @return false.
*/
public boolean implies(Permission p) {
return false;
}
/**
* Checks two SelfPermission objects for equality.
*
* Checks that <i>obj</i> is an SelfPermission, and has
* the same type (class) name, permission name, actions, and
* certificates as this object.
*
* @param obj the object we are testing for equality with this object.
*
* @return true if obj is an SelfPermission, and has the same
* type (class) name, permission name, actions, and
* certificates as this object.
*/
public boolean equals(Object obj) {
if (obj == this)
return true;
if (! (obj instanceof SelfPermission))
return false;
SelfPermission that = (SelfPermission) obj;
if (!(this.type.equals(that.type) &&
this.name.equals(that.name) &&
this.actions.equals(that.actions)))
return false;
if (this.certs.length != that.certs.length)
return false;
int i,j;
boolean match;
for (i = 0; i < this.certs.length; i++) {
match = false;
for (j = 0; j < that.certs.length; j++) {
if (this.certs[i].equals(that.certs[j])) {
match = true;
break;
}
}
if (!match) return false;
}
for (i = 0; i < that.certs.length; i++) {
match = false;
for (j = 0; j < this.certs.length; j++) {
if (that.certs[i].equals(this.certs[j])) {
match = true;
break;
}
}
if (!match) return false;
}
return true;
}
/**
* Returns the hash code value for this object.
*
* @return a hash code value for this object.
*/
public int hashCode() {
int hash = type.hashCode();
if (name != null)
hash ^= name.hashCode();
if (actions != null)
hash ^= actions.hashCode();
return hash;
}
/**
* Returns the canonical string representation of the actions,
* which currently is the empty string "", since there are no actions
* for an SelfPermission. That is, the actions for the
* permission that will be created when this SelfPermission
* is resolved may be non-null, but an SelfPermission
* itself is never considered to have any actions.
*
* @return the empty string "".
*/
public String getActions() {
return "";
}
public String getSelfType() {
return type;
}
public String getSelfName() {
return name;
}
public String getSelfActions() {
return actions;
}
public Certificate[] getCerts() {
return certs;
}
/**
* Returns a string describing this SelfPermission. The convention
* is to specify the class name, the permission name, and the actions,
* in the following format: '(unresolved "ClassName" "name" "actions")'.
*
* @return information about this SelfPermission.
*/
public String toString() {
return "(SelfPermission " + type + " " + name + " " + actions + ")";
}
}
/**
* holds policy information that we need to synch on
*/
private static class PolicyInfo {
private static final boolean verbose = false;
// Stores grant entries in the policy
final List<PolicyEntry> policyEntries;
// Stores grant entries gotten from identity database
// Use separate lists to avoid sync on policyEntries
final List<PolicyEntry> identityPolicyEntries;
// Maps aliases to certs
final Map aliasMapping;
// Maps ProtectionDomain to PermissionCollection
private final Map<ProtectionDomain, PermissionCollection>[] pdMapping;
private java.util.Random random;
PolicyInfo(int numCaches) {
policyEntries = new ArrayList<PolicyEntry>();
identityPolicyEntries =
Collections.synchronizedList(new ArrayList<PolicyEntry>(2));
aliasMapping = Collections.synchronizedMap(new HashMap(11));
pdMapping = new Map[numCaches];
for (int i = 0; i < numCaches; i++) {
pdMapping[i] = Collections.synchronizedMap
(new WeakHashMap<ProtectionDomain, PermissionCollection>());
}
if (numCaches > 1) {
random = new java.util.Random();
}
}
Map<ProtectionDomain, PermissionCollection> getPdMapping() {
if (pdMapping.length == 1) {
return pdMapping[0];
} else {
int i = java.lang.Math.abs(random.nextInt() % pdMapping.length);
return pdMapping[i];
}
}
}
}