/java-1.7.0-openjdk/openjdk/jdk/src/share/classes/sun/security/provider/PolicyFile.java
Java | 2437 lines | 1346 code | 216 blank | 875 comment | 352 complexity | 4ed42564499ce72815c47020216da703 MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause-No-Nuclear-License-2014, LGPL-3.0, LGPL-2.0
Large files files are truncated, but you can click here to view the full file
- /*
- * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
- package sun.security.provider;
- import java.io.*;
- import java.lang.RuntimePermission;
- import java.lang.reflect.*;
- import java.lang.ref.*;
- import java.net.MalformedURLException;
- import java.net.URL;
- import java.net.URI;
- import java.util.*;
- import java.util.Enumeration;
- import java.util.Hashtable;
- import java.util.List;
- import java.util.StringTokenizer;
- import java.util.PropertyPermission;
- import java.util.ArrayList;
- import java.util.ListIterator;
- import java.util.WeakHashMap;
- import java.text.MessageFormat;
- import com.sun.security.auth.PrincipalComparator;
- import java.security.*;
- import java.security.cert.Certificate;
- import java.security.cert.X509Certificate;
- import javax.security.auth.PrivateCredentialPermission;
- import javax.security.auth.Subject;
- import javax.security.auth.x500.X500Principal;
- import java.io.FilePermission;
- import java.net.SocketPermission;
- import java.net.NetPermission;
- import java.util.PropertyPermission;
- import java.util.concurrent.atomic.AtomicReference;
- /*
- import javax.security.auth.AuthPermission;
- import javax.security.auth.kerberos.ServicePermission;
- import javax.security.auth.kerberos.DelegationPermission;
- import java.io.SerializablePermission;
- import java.util.logging.LoggingPermission;
- import java.sql.SQLPermission;
- import java.lang.reflect.ReflectPermission;
- import javax.sound.sampled.AudioPermission;
- import javax.net.ssl.SSLPermission;
- */
- import sun.misc.JavaSecurityProtectionDomainAccess;
- import static sun.misc.JavaSecurityProtectionDomainAccess.ProtectionDomainCache;
- import sun.misc.SharedSecrets;
- import sun.security.util.Password;
- import sun.security.util.PolicyUtil;
- import sun.security.util.PropertyExpander;
- import sun.security.util.Debug;
- import sun.security.util.ResourcesMgr;
- import sun.security.util.SecurityConstants;
- import sun.net.www.ParseUtil;
- /**
- * This class represents a default implementation for
- * <code>java.security.Policy</code>.
- *
- * Note:
- * For backward compatibility with JAAS 1.0 it loads
- * both java.auth.policy and java.policy. However it
- * is recommended that java.auth.policy be not used
- * and the java.policy contain all grant entries including
- * that contain principal-based entries.
- *
- *
- * <p> This object stores the policy for entire Java runtime,
- * and is the amalgamation of multiple static policy
- * configurations that resides in files.
- * The algorithm for locating the policy file(s) and reading their
- * information into this <code>Policy</code> object is:
- *
- * <ol>
- * <li>
- * Loop through the <code>java.security.Security</code> properties,
- * <i>policy.url.1</i>, <i>policy.url.2</i>, ...,
- * <i>policy.url.X</i>" and
- * <i>auth.policy.url.1</i>, <i>auth.policy.url.2</i>, ...,
- * <i>auth.policy.url.X</i>". These properties are set
- * in the Java security properties file, which is located in the file named
- * <JAVA_HOME>/lib/security/java.security.
- * <JAVA_HOME> refers to the value of the java.home system property,
- * and specifies the directory where the JRE is installed.
- * Each property value specifies a <code>URL</code> pointing to a
- * policy file to be loaded. Read in and load each policy.
- *
- * <i>auth.policy.url</i> is supported only for backward compatibility.
- *
- * <li>
- * The <code>java.lang.System</code> property <i>java.security.policy</i>
- * may also be set to a <code>URL</code> pointing to another policy file
- * (which is the case when a user uses the -D switch at runtime).
- * If this property is defined, and its use is allowed by the
- * security property file (the Security property,
- * <i>policy.allowSystemProperty</i> is set to <i>true</i>),
- * also load that policy.
- *
- * <li>
- * The <code>java.lang.System</code> property
- * <i>java.security.auth.policy</i> may also be set to a
- * <code>URL</code> pointing to another policy file
- * (which is the case when a user uses the -D switch at runtime).
- * If this property is defined, and its use is allowed by the
- * security property file (the Security property,
- * <i>policy.allowSystemProperty</i> is set to <i>true</i>),
- * also load that policy.
- *
- * <i>java.security.auth.policy</i> is supported only for backward
- * compatibility.
- *
- * If the <i>java.security.policy</i> or
- * <i>java.security.auth.policy</i> property is defined using
- * "==" (rather than "="), then ignore all other specified
- * policies and only load this policy.
- * </ol>
- *
- * Each policy file consists of one or more grant entries, each of
- * which consists of a number of permission entries.
- *
- * <pre>
- * grant signedBy "<b>alias</b>", codeBase "<b>URL</b>",
- * principal <b>principalClass</b> "<b>principalName</b>",
- * principal <b>principalClass</b> "<b>principalName</b>",
- * ... {
- *
- * permission <b>Type</b> "<b>name</b> "<b>action</b>",
- * signedBy "<b>alias</b>";
- * permission <b>Type</b> "<b>name</b> "<b>action</b>",
- * signedBy "<b>alias</b>";
- * ....
- * };
- * </pre>
- *
- * All non-bold items above must appear as is (although case
- * doesn't matter and some are optional, as noted below).
- * principal entries are optional and need not be present.
- * Italicized items represent variable values.
- *
- * <p> A grant entry must begin with the word <code>grant</code>.
- * The <code>signedBy</code>,<code>codeBase</code> and <code>principal</code>
- * name/value pairs are optional.
- * If they are not present, then any signer (including unsigned code)
- * will match, and any codeBase will match.
- * Note that the <i>principalClass</i>
- * may be set to the wildcard value, *, which allows it to match
- * any <code>Principal</code> class. In addition, the <i>principalName</i>
- * may also be set to the wildcard value, *, allowing it to match
- * any <code>Principal</code> name. When setting the <i>principalName</i>
- * to the *, do not surround the * with quotes.
- *
- * <p> A permission entry must begin with the word <code>permission</code>.
- * The word <code><i>Type</i></code> in the template above is
- * a specific permission type, such as <code>java.io.FilePermission</code>
- * or <code>java.lang.RuntimePermission</code>.
- *
- * <p> The "<i>action</i>" is required for
- * many permission types, such as <code>java.io.FilePermission</code>
- * (where it specifies what type of file access that is permitted).
- * It is not required for categories such as
- * <code>java.lang.RuntimePermission</code>
- * where it is not necessary - you either have the
- * permission specified by the <code>"<i>name</i>"</code>
- * value following the type name or you don't.
- *
- * <p> The <code>signedBy</code> name/value pair for a permission entry
- * is optional. If present, it indicates a signed permission. That is,
- * the permission class itself must be signed by the given alias in
- * order for it to be granted. For example,
- * suppose you have the following grant entry:
- *
- * <pre>
- * grant principal foo.com.Principal "Duke" {
- * permission Foo "foobar", signedBy "FooSoft";
- * }
- * </pre>
- *
- * <p> Then this permission of type <i>Foo</i> is granted if the
- * <code>Foo.class</code> permission has been signed by the
- * "FooSoft" alias, or if XXX <code>Foo.class</code> is a
- * system class (i.e., is found on the CLASSPATH).
- *
- *
- * <p> Items that appear in an entry must appear in the specified order
- * (<code>permission</code>, <i>Type</i>, "<i>name</i>", and
- * "<i>action</i>"). An entry is terminated with a semicolon.
- *
- * <p> Case is unimportant for the identifiers (<code>permission</code>,
- * <code>signedBy</code>, <code>codeBase</code>, etc.) but is
- * significant for the <i>Type</i>
- * or for any string that is passed in as a value. <p>
- *
- * <p> An example of two entries in a policy configuration file is
- * <pre>
- * // if the code is comes from "foo.com" and is running as "Duke",
- * // grant it read/write to all files in /tmp.
- *
- * grant codeBase "foo.com", principal foo.com.Principal "Duke" {
- * permission java.io.FilePermission "/tmp/*", "read,write";
- * };
- *
- * // grant any code running as "Duke" permission to read
- * // the "java.vendor" Property.
- *
- * grant principal foo.com.Principal "Duke" {
- * permission java.util.PropertyPermission "java.vendor";
- *
- *
- * </pre>
- * This Policy implementation supports special handling of any
- * permission that contains the string, "<b>${{self}}</b>", as part of
- * its target name. When such a permission is evaluated
- * (such as during a security check), <b>${{self}}</b> is replaced
- * with one or more Principal class/name pairs. The exact
- * replacement performed depends upon the contents of the
- * grant clause to which the permission belongs.
- *<p>
- *
- * If the grant clause does not contain any principal information,
- * the permission will be ignored (permissions containing
- * <b>${{self}}</b> in their target names are only valid in the context
- * of a principal-based grant clause). For example, BarPermission
- * will always be ignored in the following grant clause:
- *
- *<pre>
- * grant codebase "www.foo.com", signedby "duke" {
- * permission BarPermission "... ${{self}} ...";
- * };
- *</pre>
- *
- * If the grant clause contains principal information, <b>${{self}}</b>
- * will be replaced with that same principal information.
- * For example, <b>${{self}}</b> in BarPermission will be replaced by
- * <b>javax.security.auth.x500.X500Principal "cn=Duke"</b>
- * in the following grant clause:
- *
- * <pre>
- * grant principal javax.security.auth.x500.X500Principal "cn=Duke" {
- * permission BarPermission "... ${{self}} ...";
- * };
- * </pre>
- *
- * If there is a comma-separated list of principals in the grant
- * clause, then <b>${{self}}</b> will be replaced by the same
- * comma-separated list or principals.
- * In the case where both the principal class and name are
- * wildcarded in the grant clause, <b>${{self}}</b> is replaced
- * with all the principals associated with the <code>Subject</code>
- * in the current <code>AccessControlContext</code>.
- *
- *
- * <p> For PrivateCredentialPermissions, you can also use "<b>self</b>"
- * instead of "<b>${{self}}</b>". However the use of "<b>self</b>" is
- * deprecated in favour of "<b>${{self}}</b>".
- *
- * @see java.security.CodeSource
- * @see java.security.Permissions
- * @see java.security.ProtectionDomain
- */
- public class PolicyFile extends java.security.Policy {
- private static final Debug debug = Debug.getInstance("policy");
- private static final String NONE = "NONE";
- private static final String P11KEYSTORE = "PKCS11";
- private static final String SELF = "${{self}}";
- private static final String X500PRINCIPAL =
- "javax.security.auth.x500.X500Principal";
- private static final String POLICY = "java.security.policy";
- private static final String SECURITY_MANAGER = "java.security.manager";
- private static final String POLICY_URL = "policy.url.";
- private static final String AUTH_POLICY = "java.security.auth.policy";
- private static final String AUTH_POLICY_URL = "auth.policy.url.";
- private static final int DEFAULT_CACHE_SIZE = 1;
- // contains the policy grant entries, PD cache, and alias mapping
- private AtomicReference<PolicyInfo> policyInfo = new AtomicReference<>();
- private boolean constructed = false;
- private boolean expandProperties = true;
- private boolean ignoreIdentityScope = true;
- private boolean allowSystemProperties = true;
- private boolean notUtf8 = false;
- private URL url;
- // for use with the reflection API
- private static final Class[] PARAMS0 = { };
- private static final Class[] PARAMS1 = { String.class };
- private static final Class[] PARAMS2 = { String.class, String.class };
- /**
- * Initializes the Policy object and reads the default policy
- * configuration file(s) into the Policy object.
- */
- public PolicyFile() {
- init((URL)null);
- }
- /**
- * Initializes the Policy object and reads the default policy
- * from the specified URL only.
- */
- public PolicyFile(URL url) {
- this.url = url;
- init(url);
- }
- /**
- * Initializes the Policy object and reads the default policy
- * configuration file(s) into the Policy object.
- *
- * The algorithm for locating the policy file(s) and reading their
- * information into the Policy object is:
- * <pre>
- * loop through the Security Properties named "policy.url.1",
- * ""policy.url.2", "auth.policy.url.1", "auth.policy.url.2" etc, until
- * you don't find one. Each of these specify a policy file.
- *
- * if none of these could be loaded, use a builtin static policy
- * equivalent to the default lib/security/java.policy file.
- *
- * if the system property "java.policy" or "java.auth.policy" is defined
- * (which is the
- * case when the user uses the -D switch at runtime), and
- * its use is allowed by the security property file,
- * also load it.
- * </pre>
- *
- * Each policy file consists of one or more grant entries, each of
- * which consists of a number of permission entries.
- * <pre>
- * grant signedBy "<i>alias</i>", codeBase "<i>URL</i>" {
- * permission <i>Type</i> "<i>name</i>", "<i>action</i>",
- * signedBy "<i>alias</i>";
- * ....
- * permission <i>Type</i> "<i>name</i>", "<i>action</i>",
- * signedBy "<i>alias</i>";
- * };
- *
- * </pre>
- *
- * All non-italicized items above must appear as is (although case
- * doesn't matter and some are optional, as noted below).
- * Italicized items represent variable values.
- *
- * <p> A grant entry must begin with the word <code>grant</code>.
- * The <code>signedBy</code> and <code>codeBase</code> name/value
- * pairs are optional.
- * If they are not present, then any signer (including unsigned code)
- * will match, and any codeBase will match.
- *
- * <p> A permission entry must begin with the word <code>permission</code>.
- * The word <code><i>Type</i></code> in the template above would actually
- * be a specific permission type, such as
- * <code>java.io.FilePermission</code> or
- * <code>java.lang.RuntimePermission</code>.
- *
- * <p>The "<i>action</i>" is required for
- * many permission types, such as <code>java.io.FilePermission</code>
- * (where it specifies what type of file access is permitted).
- * It is not required for categories such as
- * <code>java.lang.RuntimePermission</code>
- * where it is not necessary - you either have the
- * permission specified by the <code>"<i>name</i>"</code>
- * value following the type name or you don't.
- *
- * <p>The <code>signedBy</code> name/value pair for a permission entry
- * is optional. If present, it indicates a signed permission. That is,
- * the permission class itself must be signed by the given alias in
- * order for it to be granted. For example,
- * suppose you have the following grant entry:
- *
- * <pre>
- * grant {
- * permission Foo "foobar", signedBy "FooSoft";
- * }
- * </pre>
- *
- * <p>Then this permission of type <i>Foo</i> is granted if the
- * <code>Foo.class</code> permission has been signed by the
- * "FooSoft" alias, or if <code>Foo.class</code> is a
- * system class (i.e., is found on the CLASSPATH).
- *
- * <p>Items that appear in an entry must appear in the specified order
- * (<code>permission</code>, <i>Type</i>, "<i>name</i>", and
- * "<i>action</i>"). An entry is terminated with a semicolon.
- *
- * <p>Case is unimportant for the identifiers (<code>permission</code>,
- * <code>signedBy</code>, <code>codeBase</code>, etc.) but is
- * significant for the <i>Type</i>
- * or for any string that is passed in as a value. <p>
- *
- * <p>An example of two entries in a policy configuration file is
- * <pre>
- * // if the code is signed by "Duke", grant it read/write to all
- * // files in /tmp.
- *
- * grant signedBy "Duke" {
- * permission java.io.FilePermission "/tmp/*", "read,write";
- * };
- * <p>
- * // grant everyone the following permission
- *
- * grant {
- * permission java.util.PropertyPermission "java.vendor";
- * };
- * </pre>
- */
- private void init(URL url) {
- // Properties are set once for each init(); ignore changes between
- // between diff invocations of initPolicyFile(policy, url, info).
- String numCacheStr =
- AccessController.doPrivileged(new PrivilegedAction<String>() {
- public String run() {
- expandProperties = "true".equalsIgnoreCase
- (Security.getProperty("policy.expandProperties"));
- ignoreIdentityScope = "true".equalsIgnoreCase
- (Security.getProperty("policy.ignoreIdentityScope"));
- allowSystemProperties = "true".equalsIgnoreCase
- (Security.getProperty("policy.allowSystemProperty"));
- notUtf8 = "false".equalsIgnoreCase
- (System.getProperty("sun.security.policy.utf8"));
- return System.getProperty("sun.security.policy.numcaches");
- }});
- int numCaches;
- if (numCacheStr != null) {
- try {
- numCaches = Integer.parseInt(numCacheStr);
- } catch (NumberFormatException e) {
- numCaches = DEFAULT_CACHE_SIZE;
- }
- } else {
- numCaches = DEFAULT_CACHE_SIZE;
- }
- // System.out.println("number caches=" + numCaches);
- PolicyInfo newInfo = new PolicyInfo(numCaches);
- initPolicyFile(newInfo, url);
- policyInfo.set(newInfo);
- }
- private void initPolicyFile(final PolicyInfo newInfo, final URL url) {
- if (url != null) {
- /**
- * If the caller specified a URL via Policy.getInstance,
- * we only read from that URL
- */
- if (debug != null) {
- debug.println("reading "+url);
- }
- AccessController.doPrivileged(new PrivilegedAction<Void>() {
- public Void run() {
- if (init(url, newInfo) == false) {
- // use static policy if all else fails
- initStaticPolicy(newInfo);
- }
- return null;
- }
- });
- } else {
- /**
- * Caller did not specify URL via Policy.getInstance.
- * Read from URLs listed in the java.security properties file.
- *
- * We call initPolicyFile with POLICY , POLICY_URL and then
- * call it with AUTH_POLICY and AUTH_POLICY_URL
- * So first we will process the JAVA standard policy
- * and then process the JAVA AUTH Policy.
- * This is for backward compatibility as well as to handle
- * cases where the user has a single unified policyfile
- * with both java policy entries and auth entries
- */
- boolean loaded_one = initPolicyFile(POLICY, POLICY_URL, newInfo);
- // To maintain strict backward compatibility
- // we load the static policy only if POLICY load failed
- if (!loaded_one) {
- // use static policy if all else fails
- initStaticPolicy(newInfo);
- }
- initPolicyFile(AUTH_POLICY, AUTH_POLICY_URL, newInfo);
- }
- }
- private boolean initPolicyFile(final String propname, final String urlname,
- final PolicyInfo newInfo) {
- Boolean loadedPolicy =
- AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
- public Boolean run() {
- boolean loaded_policy = false;
- if (allowSystemProperties) {
- String extra_policy = System.getProperty(propname);
- if (extra_policy != null) {
- boolean overrideAll = false;
- if (extra_policy.startsWith("=")) {
- overrideAll = true;
- extra_policy = extra_policy.substring(1);
- }
- try {
- extra_policy =
- PropertyExpander.expand(extra_policy);
- URL policyURL;
- File policyFile = new File(extra_policy);
- if (policyFile.exists()) {
- policyURL = ParseUtil.fileToEncodedURL
- (new File(policyFile.getCanonicalPath()));
- } else {
- policyURL = new URL(extra_policy);
- }
- if (debug != null)
- debug.println("reading "+policyURL);
- if (init(policyURL, newInfo))
- loaded_policy = true;
- } catch (Exception e) {
- // ignore.
- if (debug != null) {
- debug.println("caught exception: "+e);
- }
- }
- if (overrideAll) {
- if (debug != null) {
- debug.println("overriding other policies!");
- }
- return Boolean.valueOf(loaded_policy);
- }
- }
- }
- int n = 1;
- String policy_uri;
- while ((policy_uri = Security.getProperty(urlname+n)) != null) {
- try {
- URL policy_url = null;
- String expanded_uri = PropertyExpander.expand
- (policy_uri).replace(File.separatorChar, '/');
- if (policy_uri.startsWith("file:${java.home}/") ||
- policy_uri.startsWith("file:${user.home}/")) {
- // this special case accommodates
- // the situation java.home/user.home
- // expand to a single slash, resulting in
- // a file://foo URI
- policy_url = new File
- (expanded_uri.substring(5)).toURI().toURL();
- } else {
- policy_url = new URI(expanded_uri).toURL();
- }
- if (debug != null)
- debug.println("reading "+policy_url);
- if (init(policy_url, newInfo))
- loaded_policy = true;
- } catch (Exception e) {
- if (debug != null) {
- debug.println("error reading policy "+e);
- e.printStackTrace();
- }
- // ignore that policy
- }
- n++;
- }
- return Boolean.valueOf(loaded_policy);
- }
- });
- return loadedPolicy.booleanValue();
- }
- /**
- * Reads a policy configuration into the Policy object using a
- * Reader object.
- *
- * @param policyFile the policy Reader object.
- */
- private boolean init(URL policy, PolicyInfo newInfo) {
- boolean success = false;
- PolicyParser pp = new PolicyParser(expandProperties);
- InputStreamReader isr = null;
- try {
- // read in policy using UTF-8 by default
- //
- // check non-standard system property to see if
- // the default encoding should be used instead
- if (notUtf8) {
- isr = new InputStreamReader
- (PolicyUtil.getInputStream(policy));
- } else {
- isr = new InputStreamReader
- (PolicyUtil.getInputStream(policy), "UTF-8");
- }
- pp.read(isr);
- KeyStore keyStore = null;
- try {
- keyStore = PolicyUtil.getKeyStore
- (policy,
- pp.getKeyStoreUrl(),
- pp.getKeyStoreType(),
- pp.getKeyStoreProvider(),
- pp.getStorePassURL(),
- debug);
- } catch (Exception e) {
- // ignore, treat it like we have no keystore
- if (debug != null) {
- e.printStackTrace();
- }
- }
- Enumeration<PolicyParser.GrantEntry> enum_ = pp.grantElements();
- while (enum_.hasMoreElements()) {
- PolicyParser.GrantEntry ge = enum_.nextElement();
- addGrantEntry(ge, keyStore, newInfo);
- }
- } catch (PolicyParser.ParsingException pe) {
- MessageFormat form = new MessageFormat(ResourcesMgr.getString
- (POLICY + ".error.parsing.policy.message"));
- Object[] source = {policy, pe.getLocalizedMessage()};
- System.err.println(form.format(source));
- if (debug != null)
- pe.printStackTrace();
- } catch (Exception e) {
- if (debug != null) {
- debug.println("error parsing "+policy);
- debug.println(e.toString());
- e.printStackTrace();
- }
- } finally {
- if (isr != null) {
- try {
- isr.close();
- success = true;
- } catch (IOException e) {
- // ignore the exception
- }
- } else {
- success = true;
- }
- }
- return success;
- }
- private void initStaticPolicy(final PolicyInfo newInfo) {
- AccessController.doPrivileged(new PrivilegedAction<Void>() {
- public Void run() {
- PolicyEntry pe = new PolicyEntry(new CodeSource(null,
- (Certificate[]) null));
- pe.add(SecurityConstants.LOCAL_LISTEN_PERMISSION);
- pe.add(new PropertyPermission("java.version",
- SecurityConstants.PROPERTY_READ_ACTION));
- pe.add(new PropertyPermission("java.vendor",
- SecurityConstants.PROPERTY_READ_ACTION));
- pe.add(new PropertyPermission("java.vendor.url",
- SecurityConstants.PROPERTY_READ_ACTION));
- pe.add(new PropertyPermission("java.class.version",
- SecurityConstants.PROPERTY_READ_ACTION));
- pe.add(new PropertyPermission("os.name",
- SecurityConstants.PROPERTY_READ_ACTION));
- pe.add(new PropertyPermission("os.version",
- SecurityConstants.PROPERTY_READ_ACTION));
- pe.add(new PropertyPermission("os.arch",
- SecurityConstants.PROPERTY_READ_ACTION));
- pe.add(new PropertyPermission("file.separator",
- SecurityConstants.PROPERTY_READ_ACTION));
- pe.add(new PropertyPermission("path.separator",
- SecurityConstants.PROPERTY_READ_ACTION));
- pe.add(new PropertyPermission("line.separator",
- SecurityConstants.PROPERTY_READ_ACTION));
- pe.add(new PropertyPermission
- ("java.specification.version",
- SecurityConstants.PROPERTY_READ_ACTION));
- pe.add(new PropertyPermission
- ("java.specification.vendor",
- SecurityConstants.PROPERTY_READ_ACTION));
- pe.add(new PropertyPermission
- ("java.specification.name",
- SecurityConstants.PROPERTY_READ_ACTION));
- pe.add(new PropertyPermission
- ("java.vm.specification.version",
- SecurityConstants.PROPERTY_READ_ACTION));
- pe.add(new PropertyPermission
- ("java.vm.specification.vendor",
- SecurityConstants.PROPERTY_READ_ACTION));
- pe.add(new PropertyPermission
- ("java.vm.specification.name",
- SecurityConstants.PROPERTY_READ_ACTION));
- pe.add(new PropertyPermission("java.vm.version",
- SecurityConstants.PROPERTY_READ_ACTION));
- pe.add(new PropertyPermission("java.vm.vendor",
- SecurityConstants.PROPERTY_READ_ACTION));
- pe.add(new PropertyPermission("java.vm.name",
- SecurityConstants.PROPERTY_READ_ACTION));
- // No need to sync because noone has access to newInfo yet
- newInfo.policyEntries.add(pe);
- // Add AllPermissions for standard extensions
- String[] extCodebases = PolicyParser.parseExtDirs(
- PolicyParser.EXTDIRS_EXPANSION, 0);
- if (extCodebases != null && extCodebases.length > 0) {
- for (int i = 0; i < extCodebases.length; i++) {
- try {
- pe = new PolicyEntry(canonicalizeCodebase(
- new CodeSource(new URL(extCodebases[i]),
- (Certificate[]) null), false ));
- pe.add(SecurityConstants.ALL_PERMISSION);
- // No need to sync because noone has access to
- // newInfo yet
- newInfo.policyEntries.add(pe);
- } catch (Exception e) {
- // this is probably bad (though not dangerous).
- // What should we do?
- }
- }
- }
- return null;
- }
- });
- }
- /**
- * Given a GrantEntry, create a codeSource.
- *
- * @return null if signedBy alias is not recognized
- */
- private CodeSource getCodeSource(PolicyParser.GrantEntry ge, KeyStore keyStore,
- PolicyInfo newInfo) throws java.net.MalformedURLException
- {
- Certificate[] certs = null;
- if (ge.signedBy != null) {
- certs = getCertificates(keyStore, ge.signedBy, newInfo);
- if (certs == null) {
- // we don't have a key for this alias,
- // just return
- if (debug != null) {
- debug.println(" -- No certs for alias '" +
- ge.signedBy + "' - ignoring entry");
- }
- return null;
- }
- }
- URL location;
- if (ge.codeBase != null)
- location = new URL(ge.codeBase);
- else
- location = null;
- return (canonicalizeCodebase(new CodeSource(location, certs),false));
- }
- /**
- * Add one policy entry to the list.
- */
- private void addGrantEntry(PolicyParser.GrantEntry ge,
- KeyStore keyStore, PolicyInfo newInfo) {
- if (debug != null) {
- debug.println("Adding policy entry: ");
- debug.println(" signedBy " + ge.signedBy);
- debug.println(" codeBase " + ge.codeBase);
- if (ge.principals != null && ge.principals.size() > 0) {
- ListIterator<PolicyParser.PrincipalEntry> li =
- ge.principals.listIterator();
- while (li.hasNext()) {
- PolicyParser.PrincipalEntry pppe = li.next();
- debug.println(" " + pppe.toString());
- }
- }
- }
- try {
- CodeSource codesource = getCodeSource(ge, keyStore, newInfo);
- // skip if signedBy alias was unknown...
- if (codesource == null) return;
- // perform keystore alias principal replacement.
- // for example, if alias resolves to X509 certificate,
- // replace principal with: <X500Principal class> <SubjectDN>
- // -- skip if alias is unknown
- if (replacePrincipals(ge.principals, keyStore) == false)
- return;
- PolicyEntry entry = new PolicyEntry(codesource, ge.principals);
- Enumeration<PolicyParser.PermissionEntry> enum_ =
- ge.permissionElements();
- while (enum_.hasMoreElements()) {
- PolicyParser.PermissionEntry pe = enum_.nextElement();
- try {
- // perform ${{ ... }} expansions within permission name
- expandPermissionName(pe, keyStore);
- // XXX special case PrivateCredentialPermission-SELF
- Permission perm;
- if (pe.permission.equals
- ("javax.security.auth.PrivateCredentialPermission") &&
- pe.name.endsWith(" self")) {
- pe.name = pe.name.substring(0, pe.name.indexOf("self"))
- + SELF;
- }
- // check for self
- if (pe.name != null && pe.name.indexOf(SELF) != -1) {
- // Create a "SelfPermission" , it could be an
- // an unresolved permission which will be resolved
- // when implies is called
- // Add it to entry
- Certificate certs[];
- if (pe.signedBy != null) {
- certs = getCertificates(keyStore,
- pe.signedBy,
- newInfo);
- } else {
- certs = null;
- }
- perm = new SelfPermission(pe.permission,
- pe.name,
- pe.action,
- certs);
- } else {
- perm = getInstance(pe.permission,
- pe.name,
- pe.action);
- }
- entry.add(perm);
- if (debug != null) {
- debug.println(" "+perm);
- }
- } catch (ClassNotFoundException cnfe) {
- Certificate certs[];
- if (pe.signedBy != null) {
- certs = getCertificates(keyStore,
- pe.signedBy,
- newInfo);
- } else {
- certs = null;
- }
- // only add if we had no signer or we had a
- // a signer and found the keys for it.
- if (certs != null || pe.signedBy == null) {
- Permission perm = new UnresolvedPermission(
- pe.permission,
- pe.name,
- pe.action,
- certs);
- entry.add(perm);
- if (debug != null) {
- debug.println(" "+perm);
- }
- }
- } catch (java.lang.reflect.InvocationTargetException ite) {
- MessageFormat form = new MessageFormat
- (ResourcesMgr.getString
- (POLICY +
- ".error.adding.Permission.perm.message"));
- Object[] source = {pe.permission,
- ite.getTargetException().toString()};
- System.err.println(form.format(source));
- } catch (Exception e) {
- MessageFormat form = new MessageFormat
- (ResourcesMgr.getString
- (POLICY +
- ".error.adding.Permission.perm.message"));
- Object[] source = {pe.permission,
- e.toString()};
- System.err.println(form.format(source));
- }
- }
- // No need to sync because noone has access to newInfo yet
- newInfo.policyEntries.add(entry);
- } catch (Exception e) {
- MessageFormat form = new MessageFormat(ResourcesMgr.getString
- (POLICY
- + ".error.adding.Entry.message"));
- Object[] source = {e.toString()};
- System.err.println(form.format(source));
- }
- if (debug != null)
- debug.println();
- }
- /**
- * Returns a new Permission object of the given Type. The Permission is
- * created by getting the
- * Class object using the <code>Class.forName</code> method, and using
- * the reflection API to invoke the (String name, String actions)
- * constructor on the
- * object.
- *
- * @param type the type of Permission being created.
- * @param name the name of the Permission being created.
- * @param actions the actions of the Permission being created.
- *
- * @exception ClassNotFoundException if the particular Permission
- * class could not be found.
- *
- * @exception IllegalAccessException if the class or initializer is
- * not accessible.
- *
- * @exception InstantiationException if getInstance tries to
- * instantiate an abstract class or an interface, or if the
- * instantiation fails for some other reason.
- *
- * @exception NoSuchMethodException if the (String, String) constructor
- * is not found.
- *
- * @exception InvocationTargetException if the underlying Permission
- * constructor throws an exception.
- *
- */
- private static final Permission getInstance(String type,
- String name,
- String actions)
- throws ClassNotFoundException,
- InstantiationException,
- IllegalAccessException,
- NoSuchMethodException,
- InvocationTargetException
- {
- //XXX we might want to keep a hash of created factories...
- Class<?> pc = Class.forName(type);
- Permission answer = getKnownInstance(pc, name, actions);
- if (answer != null) {
- return answer;
- }
- if (name == null && actions == null) {
- try {
- Constructor<?> c = pc.getConstructor(PARAMS0);
- return (Permission) c.newInstance(new Object[] {});
- } catch (NoSuchMethodException ne) {
- try {
- Constructor<?> c = pc.getConstructor(PARAMS1);
- return (Permission) c.newInstance(
- new Object[] { name});
- } catch (NoSuchMethodException ne1 ) {
- Constructor<?> c = pc.getConstructor(PARAMS2);
- return (Permission) c.newInstance(
- new Object[] { name, actions });
- }
- }
- } else {
- if (name != null && actions == null) {
- try {
- Constructor<?> c = pc.getConstructor(PARAMS1);
- return (Permission) c.newInstance(new Object[] { name});
- } catch (NoSuchMethodException ne) {
- Constructor<?> c = pc.getConstructor(PARAMS2);
- return (Permission) c.newInstance(
- new Object[] { name, actions });
- }
- } else {
- Constructor<?> c = pc.getConstructor(PARAMS2);
- return (Permission) c.newInstance(
- new Object[] { name, actions });
- }
- }
- }
- /**
- * Creates one of the well-known permissions directly instead of
- * via reflection. Keep list short to not penalize non-JDK-defined
- * permissions.
- */
- private static final Permission getKnownInstance(Class claz,
- String name, String actions) {
- // XXX shorten list to most popular ones?
- if (claz.equals(FilePermission.class)) {
- return new FilePermission(name, actions);
- } else if (claz.equals(SocketPermission.class)) {
- return new SocketPermission(name, actions);
- } else if (claz.equals(RuntimePermission.class)) {
- return new RuntimePermission(name, actions);
- } else if (claz.equals(PropertyPermission.class)) {
- return new PropertyPermission(name, actions);
- } else if (claz.equals(NetPermission.class)) {
- return new NetPermission(name, actions);
- } else if (claz.equals(AllPermission.class)) {
- return SecurityConstants.ALL_PERMISSION;
- /*
- } else if (claz.equals(ReflectPermission.class)) {
- return new ReflectPermission(name, actions);
- } else if (claz.equals(SecurityPermission.class)) {
- return new SecurityPermission(name, actions);
- } else if (claz.equals(PrivateCredentialPermission.class)) {
- return new PrivateCredentialPermission(name, actions);
- } else if (claz.equals(AuthPermission.class)) {
- return new AuthPermission(name, actions);
- } else if (claz.equals(ServicePermission.class)) {
- return new ServicePermission(name, actions);
- } else if (claz.equals(DelegationPermission.class)) {
- return new DelegationPermission(name, actions);
- } else if (claz.equals(SerializablePermission.class)) {
- return new SerializablePermission(name, actions);
- } else if (claz.equals(AudioPermission.class)) {
- return new AudioPermission(name, actions);
- } else if (claz.equals(SSLPermission.class)) {
- return new SSLPermission(name, actions);
- } else if (claz.equals(LoggingPermission.class)) {
- return new LoggingPermission(name, actions);
- } else if (claz.equals(SQLPermission.class)) {
- return new SQLPermission(name, actions);
- */
- } else {
- return null;
- }
- }
- /**
- * Fetch all certs associated with this alias.
- */
- private Certificate[] getCertificates
- (KeyStore keyStore, String aliases, PolicyInfo newInfo) {
- List<Certificate> vcerts = null;
- StringTokenizer st = new StringTokenizer(aliases, ",");
- int n = 0;
- while (st.hasMoreTokens()) {
- String alias = st.nextToken().trim();
- n++;
- Certificate cert = null;
- // See if this alias's cert has already been cached
- synchronized (newInfo.aliasMapping) {
- cert = (Certificate)newInfo.aliasMapping.get(alias);
- if (cert == null && keyStore != null) {
- try {
- cert = keyStore.getCertificate(alias);
- } catch (KeyStoreException kse) {
- // never happens, because keystore has already been loaded
- // when we call this
- }
- if (cert != null) {
- newInfo.aliasMapping.put(alias, cert);
- newInfo.aliasMapping.put(cert, alias);
- }
- }
- }
- if (cert != null) {
- if (vcerts == null)
- vcerts = new ArrayList<Certificate>();
- vcerts.add(cert);
- }
- }
- // make sure n == vcerts.size, since we are doing a logical *and*
- if (vcerts != null && n == vcerts.size()) {
- Certificate[] certs = new Certificate[vcerts.size()];
- vcerts.toArray(certs);
- return certs;
- } else {
- return null;
- }
- }
- /**
- * Refreshes the policy object by re-reading all the policy files.
- */
- @Override public void refresh() {
- init(url);
- }
- /**
- * Evaluates the the global policy for the permissions granted to
- * the ProtectionDomain and tests whether the permission is
- * granted.
- *
- * @param domain the ProtectionDomain to test
- * @param permission the Permission object to be tested for implication.
- *
- * @return true if "permission" is a proper subset of a permission
- * granted to this ProtectionDomain.
- *
- * @see java.security.ProtectionDomain
- */
- @Override
- public boolean implies(ProtectionDomain pd, Permission p) {
- PolicyInfo pi = policyInfo.get();
- ProtectionDomainCache pdMap = pi.getPdMapping();
- PermissionCollection pc = pdMap.get(pd);
- if (pc != null) {
- return pc.implies(p);
- }
- pc = getPermissions(pd);
- if (pc == null) {
- return false;
- }
- // cache mapping of protection domain to its PermissionCollection
- pdMap.put(pd, pc);
- return pc.implies(p);
- }
- /**
- * Examines this <code>Policy</code> and returns the permissions granted
- * to the specified <code>ProtectionDomain</code>. This includes
- * the permissions currently associated with the domain as well
- * as the policy permissions granted to the domain's
- * CodeSource, ClassLoader, and Principals.
- *
- * <p> Note that this <code>Policy</code> implementation has
- * special handling for PrivateCredentialPermissions.
- * When this method encounters a <code>PrivateCredentialPermission</code>
- * which specifies "self" as the <code>Principal</code> class and name,
- * it does not add that <code>Permission</code> to the returned
- * <code>PermissionCollection</code>. Instead, it builds
- * a new <code>PrivateCredentialPermission</code>
- * for each <code>Principal</code> associated with the provided
- * <code>Subject</code>. Each new <code>PrivateCredentialPermission</code>
- * contains the same Credential class as specified in the
- * originally granted permission, as well as the Class and name
- * for the respective <code>Principal</code>.
- *
- * <p>
- *
- * @param domain the Permissions granted to this
- * <code>ProtectionDomain</code> are returned.
- *
- * @return the Permissions granted to the provided
- * <code>ProtectionDomain</code>.
- */
- @Override
- public PermissionCollection getPermissions(ProtectionDomain domain) {
- Permissions perms = new Permissions();
- if (domain == null)
- return perms;
- // first get policy perms
- getPermissions(perms, domain);
- // add static perms
- // - adding static perms after policy perms is necessary
- // to avoid a regression for 4301064
- PermissionCollection pc = domain.getPermissions();
- if (pc != null) {
- synchronized (pc) {
- Enumeration<Permission> e = pc.elements();
- while (e.hasMoreElements()) {
- perms.add(e.nextElement());
- }
- }
- }
- return perms;
- }
- /**
- * Examines this Policy and creates a PermissionCollection object with
- * the set of permissions for the specified CodeSource.
- *
- * @param CodeSource the codesource associated with the caller.
- * This encapsulates the original location of the code (where the code
- * came from) and the public key(s) of its signer.
- *
- * @return the set of permissions according to the policy.
- */
- @Overr…
Large files files are truncated, but you can click here to view the full file