Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/security/Policy.java
38829 views
/*1* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/242526package java.security;2728import java.util.Enumeration;29import java.util.WeakHashMap;30import java.util.concurrent.atomic.AtomicReference;31import sun.security.jca.GetInstance;32import sun.security.util.Debug;33import sun.security.util.SecurityConstants;343536/**37* A Policy object is responsible for determining whether code executing38* in the Java runtime environment has permission to perform a39* security-sensitive operation.40*41* <p> There is only one Policy object installed in the runtime at any42* given time. A Policy object can be installed by calling the43* {@code setPolicy} method. The installed Policy object can be44* obtained by calling the {@code getPolicy} method.45*46* <p> If no Policy object has been installed in the runtime, a call to47* {@code getPolicy} installs an instance of the default Policy48* implementation (a default subclass implementation of this abstract class).49* The default Policy implementation can be changed by setting the value50* of the {@code policy.provider} security property to the fully qualified51* name of the desired Policy subclass implementation.52*53* <p> Application code can directly subclass Policy to provide a custom54* implementation. In addition, an instance of a Policy object can be55* constructed by invoking one of the {@code getInstance} factory methods56* with a standard type. The default policy type is "JavaPolicy".57*58* <p> Once a Policy instance has been installed (either by default, or by59* calling {@code setPolicy}), the Java runtime invokes its60* {@code implies} method when it needs to61* determine whether executing code (encapsulated in a ProtectionDomain)62* can perform SecurityManager-protected operations. How a Policy object63* retrieves its policy data is up to the Policy implementation itself.64* The policy data may be stored, for example, in a flat ASCII file,65* in a serialized binary file of the Policy class, or in a database.66*67* <p> The {@code refresh} method causes the policy object to68* refresh/reload its data. This operation is implementation-dependent.69* For example, if the policy object stores its data in configuration files,70* calling {@code refresh} will cause it to re-read the configuration71* policy files. If a refresh operation is not supported, this method does72* nothing. Note that refreshed policy may not have an effect on classes73* in a particular ProtectionDomain. This is dependent on the Policy74* provider's implementation of the {@code implies}75* method and its PermissionCollection caching strategy.76*77* @author Roland Schemers78* @author Gary Ellison79* @see java.security.Provider80* @see java.security.ProtectionDomain81* @see java.security.Permission82* @see java.security.Security security properties83*/8485public abstract class Policy {8687/**88* A read-only empty PermissionCollection instance.89* @since 1.690*/91public static final PermissionCollection UNSUPPORTED_EMPTY_COLLECTION =92new UnsupportedEmptyCollection();9394// Information about the system-wide policy.95private static class PolicyInfo {96// the system-wide policy97final Policy policy;98// a flag indicating if the system-wide policy has been initialized99final boolean initialized;100101PolicyInfo(Policy policy, boolean initialized) {102this.policy = policy;103this.initialized = initialized;104}105}106107// PolicyInfo is stored in an AtomicReference108private static AtomicReference<PolicyInfo> policy =109new AtomicReference<>(new PolicyInfo(null, false));110111private static final Debug debug = Debug.getInstance("policy");112113// Cache mapping ProtectionDomain.Key to PermissionCollection114private WeakHashMap<ProtectionDomain.Key, PermissionCollection> pdMapping;115116/** package private for AccessControlContext and ProtectionDomain */117static boolean isSet()118{119PolicyInfo pi = policy.get();120return pi.policy != null && pi.initialized == true;121}122123private static void checkPermission(String type) {124SecurityManager sm = System.getSecurityManager();125if (sm != null) {126sm.checkPermission(new SecurityPermission("createPolicy." + type));127}128}129130/**131* Returns the installed Policy object. This value should not be cached,132* as it may be changed by a call to {@code setPolicy}.133* This method first calls134* {@code SecurityManager.checkPermission} with a135* {@code SecurityPermission("getPolicy")} permission136* to ensure it's ok to get the Policy object.137*138* @return the installed Policy.139*140* @throws SecurityException141* if a security manager exists and its142* {@code checkPermission} method doesn't allow143* getting the Policy object.144*145* @see SecurityManager#checkPermission(Permission)146* @see #setPolicy(java.security.Policy)147*/148public static Policy getPolicy()149{150SecurityManager sm = System.getSecurityManager();151if (sm != null)152sm.checkPermission(SecurityConstants.GET_POLICY_PERMISSION);153return getPolicyNoCheck();154}155156/**157* Returns the installed Policy object, skipping the security check.158* Used by ProtectionDomain and getPolicy.159*160* @return the installed Policy.161*/162static Policy getPolicyNoCheck()163{164PolicyInfo pi = policy.get();165// Use double-check idiom to avoid locking if system-wide policy is166// already initialized167if (pi.initialized == false || pi.policy == null) {168synchronized (Policy.class) {169PolicyInfo pinfo = policy.get();170if (pinfo.policy == null) {171String policy_class = AccessController.doPrivileged(172new PrivilegedAction<String>() {173public String run() {174return Security.getProperty("policy.provider");175}176});177if (policy_class == null) {178policy_class = "sun.security.provider.PolicyFile";179}180181try {182pinfo = new PolicyInfo(183(Policy) Class.forName(policy_class).newInstance(),184true);185} catch (Exception e) {186/*187* The policy_class seems to be an extension188* so we have to bootstrap loading it via a policy189* provider that is on the bootclasspath.190* If it loads then shift gears to using the configured191* provider.192*/193194// install the bootstrap provider to avoid recursion195Policy polFile = new sun.security.provider.PolicyFile();196pinfo = new PolicyInfo(polFile, false);197policy.set(pinfo);198199final String pc = policy_class;200Policy pol = AccessController.doPrivileged(201new PrivilegedAction<Policy>() {202public Policy run() {203try {204ClassLoader cl =205ClassLoader.getSystemClassLoader();206// we want the extension loader207ClassLoader extcl = null;208while (cl != null) {209extcl = cl;210cl = cl.getParent();211}212return (extcl != null ? (Policy)Class.forName(213pc, true, extcl).newInstance() : null);214} catch (Exception e) {215if (debug != null) {216debug.println("policy provider " +217pc +218" not available");219e.printStackTrace();220}221return null;222}223}224});225/*226* if it loaded install it as the policy provider. Otherwise227* continue to use the system default implementation228*/229if (pol != null) {230pinfo = new PolicyInfo(pol, true);231} else {232if (debug != null) {233debug.println("using sun.security.provider.PolicyFile");234}235pinfo = new PolicyInfo(polFile, true);236}237}238policy.set(pinfo);239}240return pinfo.policy;241}242}243return pi.policy;244}245246/**247* Sets the system-wide Policy object. This method first calls248* {@code SecurityManager.checkPermission} with a249* {@code SecurityPermission("setPolicy")}250* permission to ensure it's ok to set the Policy.251*252* @param p the new system Policy object.253*254* @throws SecurityException255* if a security manager exists and its256* {@code checkPermission} method doesn't allow257* setting the Policy.258*259* @see SecurityManager#checkPermission(Permission)260* @see #getPolicy()261*262*/263public static void setPolicy(Policy p)264{265SecurityManager sm = System.getSecurityManager();266if (sm != null) sm.checkPermission(267new SecurityPermission("setPolicy"));268if (p != null) {269initPolicy(p);270}271synchronized (Policy.class) {272policy.set(new PolicyInfo(p, p != null));273}274}275276/**277* Initialize superclass state such that a legacy provider can278* handle queries for itself.279*280* @since 1.4281*/282private static void initPolicy (final Policy p) {283/*284* A policy provider not on the bootclasspath could trigger285* security checks fulfilling a call to either Policy.implies286* or Policy.getPermissions. If this does occur the provider287* must be able to answer for it's own ProtectionDomain288* without triggering additional security checks, otherwise289* the policy implementation will end up in an infinite290* recursion.291*292* To mitigate this, the provider can collect it's own293* ProtectionDomain and associate a PermissionCollection while294* it is being installed. The currently installed policy295* provider (if there is one) will handle calls to296* Policy.implies or Policy.getPermissions during this297* process.298*299* This Policy superclass caches away the ProtectionDomain and300* statically binds permissions so that legacy Policy301* implementations will continue to function.302*/303304ProtectionDomain policyDomain =305AccessController.doPrivileged(new PrivilegedAction<ProtectionDomain>() {306public ProtectionDomain run() {307return p.getClass().getProtectionDomain();308}309});310311/*312* Collect the permissions granted to this protection domain313* so that the provider can be security checked while processing314* calls to Policy.implies or Policy.getPermissions.315*/316PermissionCollection policyPerms = null;317synchronized (p) {318if (p.pdMapping == null) {319p.pdMapping = new WeakHashMap<>();320}321}322323if (policyDomain.getCodeSource() != null) {324Policy pol = policy.get().policy;325if (pol != null) {326policyPerms = pol.getPermissions(policyDomain);327}328329if (policyPerms == null) { // assume it has all330policyPerms = new Permissions();331policyPerms.add(SecurityConstants.ALL_PERMISSION);332}333334synchronized (p.pdMapping) {335// cache of pd to permissions336p.pdMapping.put(policyDomain.key, policyPerms);337}338}339return;340}341342343/**344* Returns a Policy object of the specified type.345*346* <p> This method traverses the list of registered security providers,347* starting with the most preferred Provider.348* A new Policy object encapsulating the349* PolicySpi implementation from the first350* Provider that supports the specified type is returned.351*352* <p> Note that the list of registered providers may be retrieved via353* the {@link Security#getProviders() Security.getProviders()} method.354*355* @param type the specified Policy type. See the Policy section in the356* <a href=357* "{@docRoot}/../technotes/guides/security/StandardNames.html#Policy">358* Java Cryptography Architecture Standard Algorithm Name Documentation</a>359* for a list of standard Policy types.360*361* @param params parameters for the Policy, which may be null.362*363* @return the new Policy object.364*365* @exception SecurityException if the caller does not have permission366* to get a Policy instance for the specified type.367*368* @exception NullPointerException if the specified type is null.369*370* @exception IllegalArgumentException if the specified parameters371* are not understood by the PolicySpi implementation372* from the selected Provider.373*374* @exception NoSuchAlgorithmException if no Provider supports a PolicySpi375* implementation for the specified type.376*377* @see Provider378* @since 1.6379*/380public static Policy getInstance(String type, Policy.Parameters params)381throws NoSuchAlgorithmException {382383checkPermission(type);384try {385GetInstance.Instance instance = GetInstance.getInstance("Policy",386PolicySpi.class,387type,388params);389return new PolicyDelegate((PolicySpi)instance.impl,390instance.provider,391type,392params);393} catch (NoSuchAlgorithmException nsae) {394return handleException(nsae);395}396}397398/**399* Returns a Policy object of the specified type.400*401* <p> A new Policy object encapsulating the402* PolicySpi implementation from the specified provider403* is returned. The specified provider must be registered404* in the provider list.405*406* <p> Note that the list of registered providers may be retrieved via407* the {@link Security#getProviders() Security.getProviders()} method.408*409* @param type the specified Policy type. See the Policy section in the410* <a href=411* "{@docRoot}/../technotes/guides/security/StandardNames.html#Policy">412* Java Cryptography Architecture Standard Algorithm Name Documentation</a>413* for a list of standard Policy types.414*415* @param params parameters for the Policy, which may be null.416*417* @param provider the provider.418*419* @return the new Policy object.420*421* @exception SecurityException if the caller does not have permission422* to get a Policy instance for the specified type.423*424* @exception NullPointerException if the specified type is null.425*426* @exception IllegalArgumentException if the specified provider427* is null or empty,428* or if the specified parameters are not understood by429* the PolicySpi implementation from the specified provider.430*431* @exception NoSuchProviderException if the specified provider is not432* registered in the security provider list.433*434* @exception NoSuchAlgorithmException if the specified provider does not435* support a PolicySpi implementation for the specified type.436*437* @see Provider438* @since 1.6439*/440public static Policy getInstance(String type,441Policy.Parameters params,442String provider)443throws NoSuchProviderException, NoSuchAlgorithmException {444445if (provider == null || provider.length() == 0) {446throw new IllegalArgumentException("missing provider");447}448449checkPermission(type);450try {451GetInstance.Instance instance = GetInstance.getInstance("Policy",452PolicySpi.class,453type,454params,455provider);456return new PolicyDelegate((PolicySpi)instance.impl,457instance.provider,458type,459params);460} catch (NoSuchAlgorithmException nsae) {461return handleException(nsae);462}463}464465/**466* Returns a Policy object of the specified type.467*468* <p> A new Policy object encapsulating the469* PolicySpi implementation from the specified Provider470* object is returned. Note that the specified Provider object471* does not have to be registered in the provider list.472*473* @param type the specified Policy type. See the Policy section in the474* <a href=475* "{@docRoot}/../technotes/guides/security/StandardNames.html#Policy">476* Java Cryptography Architecture Standard Algorithm Name Documentation</a>477* for a list of standard Policy types.478*479* @param params parameters for the Policy, which may be null.480*481* @param provider the Provider.482*483* @return the new Policy object.484*485* @exception SecurityException if the caller does not have permission486* to get a Policy instance for the specified type.487*488* @exception NullPointerException if the specified type is null.489*490* @exception IllegalArgumentException if the specified Provider is null,491* or if the specified parameters are not understood by492* the PolicySpi implementation from the specified Provider.493*494* @exception NoSuchAlgorithmException if the specified Provider does not495* support a PolicySpi implementation for the specified type.496*497* @see Provider498* @since 1.6499*/500public static Policy getInstance(String type,501Policy.Parameters params,502Provider provider)503throws NoSuchAlgorithmException {504505if (provider == null) {506throw new IllegalArgumentException("missing provider");507}508509checkPermission(type);510try {511GetInstance.Instance instance = GetInstance.getInstance("Policy",512PolicySpi.class,513type,514params,515provider);516return new PolicyDelegate((PolicySpi)instance.impl,517instance.provider,518type,519params);520} catch (NoSuchAlgorithmException nsae) {521return handleException(nsae);522}523}524525private static Policy handleException(NoSuchAlgorithmException nsae)526throws NoSuchAlgorithmException {527Throwable cause = nsae.getCause();528if (cause instanceof IllegalArgumentException) {529throw (IllegalArgumentException)cause;530}531throw nsae;532}533534/**535* Return the Provider of this Policy.536*537* <p> This Policy instance will only have a Provider if it538* was obtained via a call to {@code Policy.getInstance}.539* Otherwise this method returns null.540*541* @return the Provider of this Policy, or null.542*543* @since 1.6544*/545public Provider getProvider() {546return null;547}548549/**550* Return the type of this Policy.551*552* <p> This Policy instance will only have a type if it553* was obtained via a call to {@code Policy.getInstance}.554* Otherwise this method returns null.555*556* @return the type of this Policy, or null.557*558* @since 1.6559*/560public String getType() {561return null;562}563564/**565* Return Policy parameters.566*567* <p> This Policy instance will only have parameters if it568* was obtained via a call to {@code Policy.getInstance}.569* Otherwise this method returns null.570*571* @return Policy parameters, or null.572*573* @since 1.6574*/575public Policy.Parameters getParameters() {576return null;577}578579/**580* Return a PermissionCollection object containing the set of581* permissions granted to the specified CodeSource.582*583* <p> Applications are discouraged from calling this method584* since this operation may not be supported by all policy implementations.585* Applications should solely rely on the {@code implies} method586* to perform policy checks. If an application absolutely must call587* a getPermissions method, it should call588* {@code getPermissions(ProtectionDomain)}.589*590* <p> The default implementation of this method returns591* Policy.UNSUPPORTED_EMPTY_COLLECTION. This method can be592* overridden if the policy implementation can return a set of593* permissions granted to a CodeSource.594*595* @param codesource the CodeSource to which the returned596* PermissionCollection has been granted.597*598* @return a set of permissions granted to the specified CodeSource.599* If this operation is supported, the returned600* set of permissions must be a new mutable instance601* and it must support heterogeneous Permission types.602* If this operation is not supported,603* Policy.UNSUPPORTED_EMPTY_COLLECTION is returned.604*/605public PermissionCollection getPermissions(CodeSource codesource) {606return Policy.UNSUPPORTED_EMPTY_COLLECTION;607}608609/**610* Return a PermissionCollection object containing the set of611* permissions granted to the specified ProtectionDomain.612*613* <p> Applications are discouraged from calling this method614* since this operation may not be supported by all policy implementations.615* Applications should rely on the {@code implies} method616* to perform policy checks.617*618* <p> The default implementation of this method first retrieves619* the permissions returned via {@code getPermissions(CodeSource)}620* (the CodeSource is taken from the specified ProtectionDomain),621* as well as the permissions located inside the specified ProtectionDomain.622* All of these permissions are then combined and returned in a new623* PermissionCollection object. If {@code getPermissions(CodeSource)}624* returns Policy.UNSUPPORTED_EMPTY_COLLECTION, then this method625* returns the permissions contained inside the specified ProtectionDomain626* in a new PermissionCollection object.627*628* <p> This method can be overridden if the policy implementation629* supports returning a set of permissions granted to a ProtectionDomain.630*631* @param domain the ProtectionDomain to which the returned632* PermissionCollection has been granted.633*634* @return a set of permissions granted to the specified ProtectionDomain.635* If this operation is supported, the returned636* set of permissions must be a new mutable instance637* and it must support heterogeneous Permission types.638* If this operation is not supported,639* Policy.UNSUPPORTED_EMPTY_COLLECTION is returned.640*641* @since 1.4642*/643public PermissionCollection getPermissions(ProtectionDomain domain) {644PermissionCollection pc = null;645646if (domain == null)647return new Permissions();648649if (pdMapping == null) {650initPolicy(this);651}652653synchronized (pdMapping) {654pc = pdMapping.get(domain.key);655}656657if (pc != null) {658Permissions perms = new Permissions();659synchronized (pc) {660for (Enumeration<Permission> e = pc.elements() ; e.hasMoreElements() ;) {661perms.add(e.nextElement());662}663}664return perms;665}666667pc = getPermissions(domain.getCodeSource());668if (pc == null || pc == UNSUPPORTED_EMPTY_COLLECTION) {669pc = new Permissions();670}671672addStaticPerms(pc, domain.getPermissions());673return pc;674}675676/**677* add static permissions to provided permission collection678*/679private void addStaticPerms(PermissionCollection perms,680PermissionCollection statics) {681if (statics != null) {682synchronized (statics) {683Enumeration<Permission> e = statics.elements();684while (e.hasMoreElements()) {685perms.add(e.nextElement());686}687}688}689}690691/**692* Evaluates the global policy for the permissions granted to693* the ProtectionDomain and tests whether the permission is694* granted.695*696* @param domain the ProtectionDomain to test697* @param permission the Permission object to be tested for implication.698*699* @return true if "permission" is a proper subset of a permission700* granted to this ProtectionDomain.701*702* @see java.security.ProtectionDomain703* @since 1.4704*/705public boolean implies(ProtectionDomain domain, Permission permission) {706PermissionCollection pc;707708if (pdMapping == null) {709initPolicy(this);710}711712synchronized (pdMapping) {713pc = pdMapping.get(domain.key);714}715716if (pc != null) {717return pc.implies(permission);718}719720pc = getPermissions(domain);721if (pc == null) {722return false;723}724725synchronized (pdMapping) {726// cache it727pdMapping.put(domain.key, pc);728}729730return pc.implies(permission);731}732733/**734* Refreshes/reloads the policy configuration. The behavior of this method735* depends on the implementation. For example, calling {@code refresh}736* on a file-based policy will cause the file to be re-read.737*738* <p> The default implementation of this method does nothing.739* This method should be overridden if a refresh operation is supported740* by the policy implementation.741*/742public void refresh() { }743744/**745* This subclass is returned by the getInstance calls. All Policy calls746* are delegated to the underlying PolicySpi.747*/748private static class PolicyDelegate extends Policy {749750private PolicySpi spi;751private Provider p;752private String type;753private Policy.Parameters params;754755private PolicyDelegate(PolicySpi spi, Provider p,756String type, Policy.Parameters params) {757this.spi = spi;758this.p = p;759this.type = type;760this.params = params;761}762763@Override public String getType() { return type; }764765@Override public Policy.Parameters getParameters() { return params; }766767@Override public Provider getProvider() { return p; }768769@Override770public PermissionCollection getPermissions(CodeSource codesource) {771return spi.engineGetPermissions(codesource);772}773@Override774public PermissionCollection getPermissions(ProtectionDomain domain) {775return spi.engineGetPermissions(domain);776}777@Override778public boolean implies(ProtectionDomain domain, Permission perm) {779return spi.engineImplies(domain, perm);780}781@Override782public void refresh() {783spi.engineRefresh();784}785}786787/**788* This represents a marker interface for Policy parameters.789*790* @since 1.6791*/792public static interface Parameters { }793794/**795* This class represents a read-only empty PermissionCollection object that796* is returned from the {@code getPermissions(CodeSource)} and797* {@code getPermissions(ProtectionDomain)}798* methods in the Policy class when those operations are not799* supported by the Policy implementation.800*/801private static class UnsupportedEmptyCollection802extends PermissionCollection {803804private static final long serialVersionUID = -8492269157353014774L;805806private Permissions perms;807808/**809* Create a read-only empty PermissionCollection object.810*/811public UnsupportedEmptyCollection() {812this.perms = new Permissions();813perms.setReadOnly();814}815816/**817* Adds a permission object to the current collection of permission818* objects.819*820* @param permission the Permission object to add.821*822* @exception SecurityException - if this PermissionCollection object823* has been marked readonly824*/825@Override public void add(Permission permission) {826perms.add(permission);827}828829/**830* Checks to see if the specified permission is implied by the831* collection of Permission objects held in this PermissionCollection.832*833* @param permission the Permission object to compare.834*835* @return true if "permission" is implied by the permissions in836* the collection, false if not.837*/838@Override public boolean implies(Permission permission) {839return perms.implies(permission);840}841842/**843* Returns an enumeration of all the Permission objects in the844* collection.845*846* @return an enumeration of all the Permissions.847*/848@Override public Enumeration<Permission> elements() {849return perms.elements();850}851}852}853854855