0N/A/*
3909N/A * Copyright (c) 1997, 2011, Oracle and/or its affiliates. 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
2362N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle 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 *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * 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/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*/
2262N/Aimport sun.misc.JavaSecurityProtectionDomainAccess;
2262N/Aimport static sun.misc.JavaSecurityProtectionDomainAccess.ProtectionDomainCache;
2262N/Aimport sun.misc.SharedSecrets;
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 // contains the policy grant entries, PD cache, and alias mapping
3384N/A private AtomicReference<PolicyInfo> policyInfo = new AtomicReference<>();
0N/A private boolean constructed = false;
0N/A
0N/A private boolean expandProperties = true;
1955N/A private boolean ignoreIdentityScope = true;
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;
0N/A } catch (Exception e) {
0N/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 }
0N/A return Boolean.valueOf(loaded_policy);
0N/A }
0N/A }
0N/A }
0N/A
0N/A int n = 1;
0N/A String policy_uri;
0N/A
0N/A while ((policy_uri = Security.getProperty(urlname+n)) != null) {
0N/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
0N/A if (debug != null)
0N/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
0N/A }
0N/A n++;
0N/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
3050N/A (POLICY + ".error.parsing.policy.message"));
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 +
3050N/A ".error.adding.Permission.perm.message"));
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 +
3050N/A ".error.adding.Permission.perm.message"));
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
3050N/A + ".error.adding.Entry.message"));
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/*
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 */
2262N/A @Override 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 */
2262N/A @Override
0N/A public boolean implies(ProtectionDomain pd, Permission p) {
0N/A PolicyInfo pi = policyInfo.get();
2262N/A ProtectionDomainCache 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 */
2262N/A @Override
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 */
2262N/A @Override
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.
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 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)) {
0N/A // checkForTrustedIdentity added it
0N/A // to the policy for us. next time
0N/A // around we'll find it. This time
0N/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) {
3384N/A ArrayList<PolicyParser.PrincipalEntry> accPs = new ArrayList<>();
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
3384N/A Set<Principal> pSet = new HashSet<>(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
0N/A expandSelf((SelfPermission)p,
0N/A entry.getPrincipals(),
0N/A accPs,
0N/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
3384N/A List<Principal> plist = new ArrayList<>();
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
3384N/A ArrayList<Certificate> userCertList = new ArrayList<>();
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();
4269N/A if (u != null) {
4269N/A if (u.getProtocol().equals("jar")) {
4269N/A // unwrap url embedded inside jar url
4269N/A String spec = u.getFile();
4269N/A int separator = spec.indexOf("!/");
4269N/A if (separator != -1) {
4269N/A try {
4269N/A u = new URL(spec.substring(0, separator));
4269N/A } catch (MalformedURLException e) {
4269N/A // Fail silently. In this case, url stays what
4269N/A // it was above
4269N/A }
4269N/A }
4269N/A }
4269N/A if (u.getProtocol().equals("file")) {
4269N/A boolean isLocalFile = false;
4269N/A String host = u.getHost();
4269N/A isLocalFile = (host == null || host.equals("") ||
4269N/A host.equals("~") || host.equalsIgnoreCase("localhost"));
0N/A
4269N/A if (isLocalFile) {
4269N/A path = u.getFile().replace('/', File.separatorChar);
4269N/A path = ParseUtil.decode(path);
4269N/A }
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
1760N/A // Wrapper to return a canonical path that avoids calling getCanonicalPath()
1760N/A // with paths that are intended to match all entries in the directory
1760N/A private 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();
0N/A String pals = "<no principals>";
0N/A if (principals != null && principals.length > 0) {
0N/A StringBuilder palBuf = new StringBuilder("(principals ");
0N/A for (int i = 0; i < principals.length; i++) {
0N/A palBuf.append(principals[i].getClass().getName() +
0N/A " \"" + principals[i].getName() +
0N/A "\"");
0N/A if (i < principals.length-1)
0N/A palBuf.append(", ");
0N/A else
0N/A palBuf.append(")");
0N/A }
0N/A pals = palBuf.toString();
0N/A }
0N/A return "PD CodeSource: "
0N/A + pd.getCodeSource()
0N/A +"\n\t" + "PD ClassLoader: "
0N/A + pd.getClassLoader()
0N/A +"\n\t" + "PD Principals: "
0N/A + pals;
0N/A }
0N/A
0N/A /**
0N/A * return true if no replacement was performed,
0N/A * or if replacement succeeded.
0N/A */
0N/A private boolean replacePrincipals(
0N/A List<PolicyParser.PrincipalEntry> principals, KeyStore keystore) {
0N/A
0N/A if (principals == null || principals.size() == 0 || keystore == null)
0N/A return true;
0N/A
0N/A ListIterator<PolicyParser.PrincipalEntry> i = principals.listIterator();
0N/A while (i.hasNext()) {
0N/A PolicyParser.PrincipalEntry pppe = i.next();
0N/A if (pppe.principalClass.equals(PolicyParser.REPLACE_NAME)) {
0N/A
0N/A // perform replacement
0N/A // (only X509 replacement is possible now)
0N/A String name;
0N/A if ((name = getDN(pppe.principalName, keystore)) == null) {
0N/A return false;
0N/A }
0N/A
0N/A if (debug != null) {
0N/A debug.println(" Replacing \"" +
0N/A pppe.principalName +
0N/A "\" with " +
0N/A X500PRINCIPAL + "/\"" +
0N/A name +
0N/A "\"");
0N/A }
0N/A
0N/A pppe.principalClass = X500PRINCIPAL;
0N/A pppe.principalName = name;
0N/A }
0N/A }
0N/A // return true if no replacement was performed,
0N/A // or if replacement succeeded
0N/A return true;
0N/A }
0N/A
0N/A private void expandPermissionName(PolicyParser.PermissionEntry pe,
0N/A KeyStore keystore) throws Exception {
0N/A // short cut the common case
0N/A if (pe.name == null || pe.name.indexOf("${{", 0) == -1) {
0N/A return;
0N/A }
0N/A
0N/A int startIndex = 0;
0N/A int b, e;
0N/A StringBuilder sb = new StringBuilder();
0N/A while ((b = pe.name.indexOf("${{", startIndex)) != -1) {
0N/A e = pe.name.indexOf("}}", b);
0N/A if (e < 1) {
0N/A break;
0N/A }
0N/A sb.append(pe.name.substring(startIndex, b));
0N/A
0N/A // get the value in ${{...}}
0N/A String value = pe.name.substring(b+3, e);
0N/A
0N/A // parse up to the first ':'
0N/A int colonIndex;
0N/A String prefix = value;
0N/A String suffix;
0N/A if ((colonIndex = value.indexOf(":")) != -1) {
0N/A prefix = value.substring(0, colonIndex);
0N/A }
0N/A
0N/A // handle different prefix possibilities
0N/A if (prefix.equalsIgnoreCase("self")) {
0N/A // do nothing - handled later
0N/A sb.append(pe.name.substring(b, e+2));
0N/A startIndex = e+2;
0N/A continue;
0N/A } else if (prefix.equalsIgnoreCase("alias")) {
0N/A // get the suffix and perform keystore alias replacement
0N/A if (colonIndex == -1) {
0N/A MessageFormat form = new MessageFormat
0N/A (ResourcesMgr.getString
3050N/A ("alias.name.not.provided.pe.name."));
0N/A Object[] source = {pe.name};
0N/A throw new Exception(form.format(source));
0N/A }
0N/A suffix = value.substring(colonIndex+1);
0N/A if ((suffix = getDN(suffix, keystore)) == null) {
0N/A MessageFormat form = new MessageFormat
0N/A (ResourcesMgr.getString
3050N/A ("unable.to.perform.substitution.on.alias.suffix"));
0N/A Object[] source = {value.substring(colonIndex+1)};
0N/A throw new Exception(form.format(source));
0N/A }
0N/A
0N/A sb.append(X500PRINCIPAL + " \"" + suffix + "\"");
0N/A startIndex = e+2;
0N/A } else {
0N/A MessageFormat form = new MessageFormat
0N/A (ResourcesMgr.getString
3050N/A ("substitution.value.prefix.unsupported"));
0N/A Object[] source = {prefix};
0N/A throw new Exception(form.format(source));
0N/A }
0N/A }
0N/A
0N/A // copy the rest of the value
0N/A sb.append(pe.name.substring(startIndex));
0N/A
0N/A // replace the name with expanded value
0N/A if (debug != null) {
0N/A debug.println(" Permission name expanded from:\n\t" +
0N/A pe.name + "\nto\n\t" + sb.toString());
0N/A }
0N/A pe.name = sb.toString();
0N/A }
0N/A
0N/A private String getDN(String alias, KeyStore keystore) {
0N/A Certificate cert = null;
0N/A try {
0N/A cert = keystore.getCertificate(alias);
0N/A } catch (Exception e) {
0N/A if (debug != null) {
0N/A debug.println(" Error retrieving certificate for '" +
0N/A alias +
0N/A "': " +
0N/A e.toString());
0N/A }
0N/A return null;
0N/A }
0N/A
0N/A if (cert == null || !(cert instanceof X509Certificate)) {
0N/A if (debug != null) {
0N/A debug.println(" -- No certificate for '" +
0N/A alias +
0N/A "' - ignoring entry");
0N/A }
0N/A return null;
0N/A } else {
0N/A X509Certificate x509Cert = (X509Certificate)cert;
0N/A
0N/A // 4702543: X500 names with an EmailAddress
0N/A // were encoded incorrectly. create new
0N/A // X500Principal name with correct encoding
0N/A
0N/A X500Principal p = new X500Principal
0N/A (x509Cert.getSubjectX500Principal().toString());
0N/A return p.getName();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Checks public key. If it is marked as trusted in
0N/A * the identity database, add it to the policy
0N/A * with the AllPermission.
0N/A */
0N/A private boolean checkForTrustedIdentity(final Certificate cert,
0N/A PolicyInfo myInfo)
0N/A {
0N/A return false;
0N/A }
0N/A
0N/A /**
0N/A * Each entry in the policy configuration file is represented by a
0N/A * PolicyEntry object. <p>
0N/A *
0N/A * A PolicyEntry is a (CodeSource,Permission) pair. The
0N/A * CodeSource contains the (URL, PublicKey) that together identify
0N/A * where the Java bytecodes come from and who (if anyone) signed
0N/A * them. The URL could refer to localhost. The URL could also be
0N/A * null, meaning that this policy entry is given to all comers, as
0N/A * long as they match the signer field. The signer could be null,
0N/A * meaning the code is not signed. <p>
0N/A *
0N/A * The Permission contains the (Type, Name, Action) triplet. <p>
0N/A *
0N/A * For now, the Policy object retrieves the public key from the
0N/A * X.509 certificate on disk that corresponds to the signedBy
0N/A * alias specified in the Policy config file. For reasons of
0N/A * efficiency, the Policy object keeps a hashtable of certs already
0N/A * read in. This could be replaced by a secure internal key
0N/A * store.
0N/A *
0N/A * <p>
0N/A * For example, the entry
0N/A * <pre>
0N/A * permission java.io.File "/tmp", "read,write",
0N/A * signedBy "Duke";
0N/A * </pre>
0N/A * is represented internally
0N/A * <pre>
0N/A *
0N/A * FilePermission f = new FilePermission("/tmp", "read,write");
0N/A * PublicKey p = publickeys.get("Duke");
0N/A * URL u = InetAddress.getLocalHost();
0N/A * CodeBase c = new CodeBase( p, u );
0N/A * pe = new PolicyEntry(f, c);
0N/A * </pre>
0N/A *
0N/A * @author Marianne Mueller
0N/A * @author Roland Schemers
0N/A * @see java.security.CodeSource
0N/A * @see java.security.Policy
0N/A * @see java.security.Permissions
0N/A * @see java.security.ProtectionDomain
0N/A */
0N/A private static class PolicyEntry {
0N/A
0N/A private final CodeSource codesource;
0N/A final List<Permission> permissions;
0N/A private final List<PolicyParser.PrincipalEntry> principals;
0N/A
0N/A /**
0N/A * Given a Permission and a CodeSource, create a policy entry.
0N/A *
0N/A * XXX Decide if/how to add validity fields and "purpose" fields to
0N/A * XXX policy entries
0N/A *
0N/A * @param cs the CodeSource, which encapsulates the URL and the
0N/A * public key
0N/A * attributes from the policy config file. Validity checks
0N/A * are performed on the public key before PolicyEntry is
0N/A * called.
0N/A *
0N/A */
0N/A PolicyEntry(CodeSource cs, List<PolicyParser.PrincipalEntry> principals)
0N/A {
0N/A this.codesource = cs;
0N/A this.permissions = new ArrayList<Permission>();
0N/A this.principals = principals; // can be null
0N/A }
0N/A
0N/A PolicyEntry(CodeSource cs)
0N/A {
0N/A this(cs, null);
0N/A }
0N/A
0N/A List<PolicyParser.PrincipalEntry> getPrincipals() {
0N/A return principals; // can be null
0N/A }
0N/A
0N/A /**
0N/A * add a Permission object to this entry.
0N/A * No need to sync add op because perms are added to entry only
0N/A * while entry is being initialized
0N/A */
0N/A void add(Permission p) {
0N/A permissions.add(p);
0N/A }
0N/A
0N/A /**
0N/A * Return the CodeSource for this policy entry
0N/A */
0N/A CodeSource getCodeSource() {
0N/A return codesource;
0N/A }
0N/A
2262N/A @Override public String toString(){
0N/A StringBuilder sb = new StringBuilder();
3050N/A sb.append(ResourcesMgr.getString("LPARAM"));
0N/A sb.append(getCodeSource());
0N/A sb.append("\n");
0N/A for (int j = 0; j < permissions.size(); j++) {
0N/A Permission p = permissions.get(j);
3050N/A sb.append(ResourcesMgr.getString("SPACE"));
3050N/A sb.append(ResourcesMgr.getString("SPACE"));
0N/A sb.append(p);
3050N/A sb.append(ResourcesMgr.getString("NEWLINE"));
0N/A }
3050N/A sb.append(ResourcesMgr.getString("RPARAM"));
3050N/A sb.append(ResourcesMgr.getString("NEWLINE"));
0N/A return sb.toString();
0N/A }
0N/A }
0N/A
0N/A private static class SelfPermission extends Permission {
0N/A
0N/A private static final long serialVersionUID = -8315562579967246806L;
0N/A
0N/A /**
0N/A * The class name of the Permission class that will be
0N/A * created when this self permission is expanded .
0N/A *
0N/A * @serial
0N/A */
0N/A private String type;
0N/A
0N/A /**
0N/A * The permission name.
0N/A *
0N/A * @serial
0N/A */
0N/A private String name;
0N/A
0N/A /**
0N/A * The actions of the permission.
0N/A *
0N/A * @serial
0N/A */
0N/A private String actions;
0N/A
0N/A /**
0N/A * The certs of the permission.
0N/A *
0N/A * @serial
0N/A */
0N/A private Certificate certs[];
0N/A
0N/A /**
0N/A * Creates a new SelfPermission containing the permission
0N/A * information needed later to expand the self
0N/A * @param type the class name of the Permission class that will be
0N/A * created when this permission is expanded and if necessary resolved.
0N/A * @param name the name of the permission.
0N/A * @param actions the actions of the permission.
0N/A * @param certs the certificates the permission's class was signed with.
0N/A * This is a list of certificate chains, where each chain is composed of
0N/A * a signer certificate and optionally its supporting certificate chain.
0N/A * Each chain is ordered bottom-to-top (i.e., with the signer
0N/A * certificate first and the (root) certificate authority last).
0N/A */
0N/A public SelfPermission(String type, String name, String actions,
0N/A Certificate certs[])
0N/A {
0N/A super(type);
0N/A if (type == null) {
0N/A throw new NullPointerException
3050N/A (ResourcesMgr.getString("type.can.t.be.null"));
0N/A }
0N/A this.type = type;
0N/A this.name = name;
0N/A this.actions = actions;
0N/A if (certs != null) {
0N/A // Extract the signer certs from the list of certificates.
0N/A for (int i=0; i<certs.length; i++) {
0N/A if (!(certs[i] instanceof X509Certificate)) {
0N/A // there is no concept of signer certs, so we store the
0N/A // entire cert array
0N/A this.certs = certs.clone();
0N/A break;
0N/A }
0N/A }
0N/A
0N/A if (this.certs == null) {
0N/A // Go through the list of certs and see if all the certs are
0N/A // signer certs.
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 // All the certs are signer certs, so we store the
0N/A // entire array
0N/A this.certs = certs.clone();
0N/A }
0N/A
0N/A if (this.certs == null) {
0N/A // extract the signer certs
0N/A ArrayList<Certificate> signerCerts =
3384N/A new ArrayList<>();
0N/A i = 0;
0N/A while (i < certs.length) {
0N/A signerCerts.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 this.certs = new Certificate[signerCerts.size()];
0N/A signerCerts.toArray(this.certs);
0N/A }
0N/A }
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * This method always returns false for SelfPermission permissions.
0N/A * That is, an SelfPermission never considered to
0N/A * imply another permission.
0N/A *
0N/A * @param p the permission to check against.
0N/A *
0N/A * @return false.
0N/A */
2262N/A @Override public boolean implies(Permission p) {
0N/A return false;
0N/A }
0N/A
0N/A /**
0N/A * Checks two SelfPermission objects for equality.
0N/A *
0N/A * Checks that <i>obj</i> is an SelfPermission, and has
0N/A * the same type (class) name, permission name, actions, and
0N/A * certificates as this object.
0N/A *
0N/A * @param obj the object we are testing for equality with this object.
0N/A *
0N/A * @return true if obj is an SelfPermission, and has the same
0N/A * type (class) name, permission name, actions, and
0N/A * certificates as this object.
0N/A */
2262N/A @Override public boolean equals(Object obj) {
0N/A if (obj == this)
0N/A return true;
0N/A
0N/A if (! (obj instanceof SelfPermission))
0N/A return false;
0N/A SelfPermission that = (SelfPermission) obj;
0N/A
0N/A if (!(this.type.equals(that.type) &&
0N/A this.name.equals(that.name) &&
0N/A this.actions.equals(that.actions)))
0N/A return false;
0N/A
0N/A if (this.certs.length != that.certs.length)
0N/A return false;
0N/A
0N/A int i,j;
0N/A boolean match;
0N/A
0N/A for (i = 0; i < this.certs.length; i++) {
0N/A match = false;
0N/A for (j = 0; j < that.certs.length; j++) {
0N/A if (this.certs[i].equals(that.certs[j])) {
0N/A match = true;
0N/A break;
0N/A }
0N/A }
0N/A if (!match) return false;
0N/A }
0N/A
0N/A for (i = 0; i < that.certs.length; i++) {
0N/A match = false;
0N/A for (j = 0; j < this.certs.length; j++) {
0N/A if (that.certs[i].equals(this.certs[j])) {
0N/A match = true;
0N/A break;
0N/A }
0N/A }
0N/A if (!match) return false;
0N/A }
0N/A return true;
0N/A }
0N/A
0N/A /**
0N/A * Returns the hash code value for this object.
0N/A *
0N/A * @return a hash code value for this object.
0N/A */
2262N/A @Override public int hashCode() {
0N/A int hash = type.hashCode();
0N/A if (name != null)
0N/A hash ^= name.hashCode();
0N/A if (actions != null)
0N/A hash ^= actions.hashCode();
0N/A return hash;
0N/A }
0N/A
0N/A /**
0N/A * Returns the canonical string representation of the actions,
0N/A * which currently is the empty string "", since there are no actions
0N/A * for an SelfPermission. That is, the actions for the
0N/A * permission that will be created when this SelfPermission
0N/A * is resolved may be non-null, but an SelfPermission
0N/A * itself is never considered to have any actions.
0N/A *
0N/A * @return the empty string "".
0N/A */
2262N/A @Override public String getActions() {
0N/A return "";
0N/A }
0N/A
0N/A public String getSelfType() {
0N/A return type;
0N/A }
0N/A
0N/A public String getSelfName() {
0N/A return name;
0N/A }
0N/A
0N/A public String getSelfActions() {
0N/A return actions;
0N/A }
0N/A
0N/A public Certificate[] getCerts() {
0N/A return certs;
0N/A }
0N/A
0N/A /**
0N/A * Returns a string describing this SelfPermission. The convention
0N/A * is to specify the class name, the permission name, and the actions,
0N/A * in the following format: '(unresolved "ClassName" "name" "actions")'.
0N/A *
0N/A * @return information about this SelfPermission.
0N/A */
2262N/A @Override public String toString() {
0N/A return "(SelfPermission " + type + " " + name + " " + actions + ")";
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * holds policy information that we need to synch on
0N/A */
0N/A private static class PolicyInfo {
0N/A private static final boolean verbose = false;
0N/A
0N/A // Stores grant entries in the policy
0N/A final List<PolicyEntry> policyEntries;
0N/A
0N/A // Stores grant entries gotten from identity database
0N/A // Use separate lists to avoid sync on policyEntries
0N/A final List<PolicyEntry> identityPolicyEntries;
0N/A
0N/A // Maps aliases to certs
0N/A final Map aliasMapping;
0N/A
0N/A // Maps ProtectionDomain to PermissionCollection
2262N/A private final ProtectionDomainCache[] pdMapping;
0N/A private java.util.Random random;
0N/A
0N/A PolicyInfo(int numCaches) {
0N/A policyEntries = new ArrayList<PolicyEntry>();
0N/A identityPolicyEntries =
0N/A Collections.synchronizedList(new ArrayList<PolicyEntry>(2));
0N/A aliasMapping = Collections.synchronizedMap(new HashMap(11));
0N/A
2262N/A pdMapping = new ProtectionDomainCache[numCaches];
2262N/A JavaSecurityProtectionDomainAccess jspda
2262N/A = SharedSecrets.getJavaSecurityProtectionDomainAccess();
0N/A for (int i = 0; i < numCaches; i++) {
2262N/A pdMapping[i] = jspda.getProtectionDomainCache();
0N/A }
0N/A if (numCaches > 1) {
0N/A random = new java.util.Random();
0N/A }
0N/A }
2262N/A ProtectionDomainCache getPdMapping() {
0N/A if (pdMapping.length == 1) {
0N/A return pdMapping[0];
0N/A } else {
0N/A int i = java.lang.Math.abs(random.nextInt() % pdMapping.length);
0N/A return pdMapping[i];
0N/A }
0N/A }
0N/A }
0N/A}