Path: blob/master/src/java.base/share/classes/sun/security/provider/PolicyFile.java
41159 views
/*1* Copyright (c) 1997, 2021, 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*/2425package sun.security.provider;2627import java.io.*;28import java.lang.reflect.*;29import java.net.MalformedURLException;30import java.net.URL;31import java.net.URI;32import java.nio.file.Files;33import java.nio.file.Path;34import java.util.*;35import java.security.*;36import java.security.cert.Certificate;37import java.security.cert.X509Certificate;38import javax.security.auth.Subject;39import javax.security.auth.x500.X500Principal;40import java.net.SocketPermission;41import java.net.NetPermission;42import java.util.concurrent.ConcurrentHashMap;43import jdk.internal.access.JavaSecurityAccess;44import jdk.internal.access.SharedSecrets;45import jdk.internal.util.StaticProperty;46import sun.security.util.*;47import sun.net.www.ParseUtil;4849import static java.nio.charset.StandardCharsets.UTF_8;50import static jdk.internal.access.JavaSecurityAccess.ProtectionDomainCache;5152/**53* This class represents a default Policy implementation for the54* "JavaPolicy" type.55*56* <p> This object stores the policy for the entire Java runtime,57* and is the amalgamation of multiple static policy58* configurations that resides in files.59* The algorithm for locating the policy file(s) and reading their60* information into this <code>Policy</code> object is:61*62* <ol>63* <li>64* Read in and load the default policy file named65* <JAVA_HOME>/lib/security/default.policy. <JAVA_HOME> refers66* to the value of the java.home system property, and specifies the directory67* where the JRE is installed. This policy file grants permissions to the68* modules loaded by the platform class loader. If the default policy file69* cannot be loaded, a fatal InternalError is thrown as these permissions70* are needed in order for the runtime to operate correctly.71* <li>72* Loop through the <code>java.security.Security</code> properties,73* and <i>policy.url.1</i>, <i>policy.url.2</i>, ...,74* <i>policy.url.X</i>". These properties are set75* in the Java security properties file, which is located in the file named76* <JAVA_HOME>/conf/security/java.security.77* Each property value specifies a <code>URL</code> pointing to a78* policy file to be loaded. Read in and load each policy.79*80* If none of these could be loaded, use a builtin static policy81* equivalent to the conf/security/java.policy file.82*83* <li>84* The <code>java.lang.System</code> property <i>java.security.policy</i>85* may also be set to a <code>URL</code> pointing to another policy file86* (which is the case when a user uses the -D switch at runtime).87* If this property is defined, and its use is allowed by the88* security property file (the Security property,89* <i>policy.allowSystemProperty</i> is set to <i>true</i>),90* also load that policy.91*92* If the <i>java.security.policy</i> property is defined using93* "==" (rather than "="), then load the specified policy file and ignore94* all other configured policies. Note, that the default.policy file is95* also loaded, as specified in the first step of the algorithm above.96* If the specified policy file cannot be loaded, use a builtin static policy97* equivalent to the default conf/security/java.policy file.98* </ol>99*100* Each policy file consists of one or more grant entries, each of101* which consists of a number of permission entries.102*103* <pre>104* grant signedBy "<b>alias</b>", codeBase "<b>URL</b>",105* principal <b>principalClass</b> "<b>principalName</b>",106* principal <b>principalClass</b> "<b>principalName</b>",107* ... {108*109* permission <b>Type</b> "<b>name</b> "<b>action</b>",110* signedBy "<b>alias</b>";111* permission <b>Type</b> "<b>name</b> "<b>action</b>",112* signedBy "<b>alias</b>";113* ....114* };115* </pre>116*117* All non-bold items above must appear as is (although case118* doesn't matter and some are optional, as noted below).119* principal entries are optional and need not be present.120* Italicized items represent variable values.121*122* <p> A grant entry must begin with the word <code>grant</code>.123* The <code>signedBy</code>,<code>codeBase</code> and <code>principal</code>124* name/value pairs are optional.125* If they are not present, then any signer (including unsigned code)126* will match, and any codeBase will match.127* Note that the <i>principalClass</i>128* may be set to the wildcard value, *, which allows it to match129* any <code>Principal</code> class. In addition, the <i>principalName</i>130* may also be set to the wildcard value, *, allowing it to match131* any <code>Principal</code> name. When setting the <i>principalName</i>132* to the *, do not surround the * with quotes.133*134* <p> A permission entry must begin with the word <code>permission</code>.135* The word <code><i>Type</i></code> in the template above is136* a specific permission type, such as <code>java.io.FilePermission</code>137* or <code>java.lang.RuntimePermission</code>.138*139* <p> The "<i>action</i>" is required for140* many permission types, such as <code>java.io.FilePermission</code>141* (where it specifies what type of file access that is permitted).142* It is not required for categories such as143* <code>java.lang.RuntimePermission</code>144* where it is not necessary - you either have the145* permission specified by the <code>"<i>name</i>"</code>146* value following the type name or you don't.147*148* <p> The <code>signedBy</code> name/value pair for a permission entry149* is optional. If present, it indicates a signed permission. That is,150* the permission class itself must be signed by the given alias in151* order for it to be granted. For example,152* suppose you have the following grant entry:153*154* <pre>155* grant principal foo.com.Principal "Duke" {156* permission Foo "foobar", signedBy "FooSoft";157* }158* </pre>159*160* <p> Then this permission of type <i>Foo</i> is granted if the161* <code>Foo.class</code> permission has been signed by the162* "FooSoft" alias, or if XXX <code>Foo.class</code> is a163* system class (i.e., is found on the CLASSPATH).164*165* <p> Items that appear in an entry must appear in the specified order166* (<code>permission</code>, <i>Type</i>, "<i>name</i>", and167* "<i>action</i>"). An entry is terminated with a semicolon.168*169* <p> Case is unimportant for the identifiers (<code>permission</code>,170* <code>signedBy</code>, <code>codeBase</code>, etc.) but is171* significant for the <i>Type</i>172* or for any string that is passed in as a value.173*174* <p> An example of two entries in a policy configuration file is175* <pre>176* // if the code is comes from "foo.com" and is running as "Duke",177* // grant it read/write to all files in /tmp.178*179* grant codeBase "foo.com", principal foo.com.Principal "Duke" {180* permission java.io.FilePermission "/tmp/*", "read,write";181* };182*183* // grant any code running as "Duke" permission to read184* // the "java.vendor" Property.185*186* grant principal foo.com.Principal "Duke" {187* permission java.util.PropertyPermission "java.vendor";188*189*190* </pre>191* This Policy implementation supports special handling of any192* permission that contains the string, "<b>${{self}}</b>", as part of193* its target name. When such a permission is evaluated194* (such as during a security check), <b>${{self}}</b> is replaced195* with one or more Principal class/name pairs. The exact196* replacement performed depends upon the contents of the197* grant clause to which the permission belongs.198* <p>199*200* If the grant clause does not contain any principal information,201* the permission will be ignored (permissions containing202* <b>${{self}}</b> in their target names are only valid in the context203* of a principal-based grant clause). For example, BarPermission204* will always be ignored in the following grant clause:205*206* <pre>207* grant codebase "www.foo.com", signedby "duke" {208* permission BarPermission "... ${{self}} ...";209* };210* </pre>211*212* If the grant clause contains principal information, <b>${{self}}</b>213* will be replaced with that same principal information.214* For example, <b>${{self}}</b> in BarPermission will be replaced by215* <b>javax.security.auth.x500.X500Principal "cn=Duke"</b>216* in the following grant clause:217*218* <pre>219* grant principal javax.security.auth.x500.X500Principal "cn=Duke" {220* permission BarPermission "... ${{self}} ...";221* };222* </pre>223*224* If there is a comma-separated list of principals in the grant225* clause, then <b>${{self}}</b> will be replaced by the same226* comma-separated list or principals.227* In the case where both the principal class and name are228* wildcarded in the grant clause, <b>${{self}}</b> is replaced229* with all the principals associated with the <code>Subject</code>230* in the current <code>AccessControlContext</code>.231*232* <p> For PrivateCredentialPermissions, you can also use "<b>self</b>"233* instead of "<b>${{self}}</b>". However the use of "<b>self</b>" is234* deprecated in favour of "<b>${{self}}</b>".235*236* @see java.security.CodeSource237* @see java.security.Permissions238* @see java.security.ProtectionDomain239*/240@SuppressWarnings("removal")241public class PolicyFile extends java.security.Policy {242243private static final Debug debug = Debug.getInstance("policy");244245private static final String SELF = "${{self}}";246private static final String X500PRINCIPAL =247"javax.security.auth.x500.X500Principal";248private static final String POLICY = "java.security.policy";249private static final String POLICY_URL = "policy.url.";250251private static final int DEFAULT_CACHE_SIZE = 1;252253// contains the policy grant entries, PD cache, and alias mapping254// can be updated if refresh() is called255private volatile PolicyInfo policyInfo;256257private boolean expandProperties = true;258private boolean allowSystemProperties = true;259private boolean notUtf8 = false;260private URL url;261262// for use with the reflection API263private static final Class<?>[] PARAMS0 = { };264private static final Class<?>[] PARAMS1 = { String.class };265private static final Class<?>[] PARAMS2 = { String.class, String.class };266267/**268* When a policy file has a syntax error, the exception code may generate269* another permission check and this can cause the policy file to be parsed270* repeatedly, leading to a StackOverflowError or ClassCircularityError.271* To avoid this, this set is populated with policy files that have been272* previously parsed and have syntax errors, so that they can be273* subsequently ignored.274*/275private static Set<URL> badPolicyURLs =276Collections.newSetFromMap(new ConcurrentHashMap<URL,Boolean>());277278/**279* Initializes the Policy object and reads the default policy280* configuration file(s) into the Policy object.281*/282public PolicyFile() {283init((URL)null);284}285286/**287* Initializes the Policy object and reads the default policy288* from the specified URL only.289*/290public PolicyFile(URL url) {291this.url = url;292init(url);293}294295/**296* Initializes the Policy object and reads the default policy297* configuration file(s) into the Policy object.298*299* See the class description for details on the algorithm used to300* initialize the Policy object.301*/302private void init(URL url) {303// Properties are set once for each init(); ignore changes304// between diff invocations of initPolicyFile(policy, url, info).305String numCacheStr =306AccessController.doPrivileged(new PrivilegedAction<>() {307@Override308public String run() {309expandProperties = "true".equalsIgnoreCase310(Security.getProperty("policy.expandProperties"));311allowSystemProperties = "true".equalsIgnoreCase312(Security.getProperty("policy.allowSystemProperty"));313notUtf8 = "false".equalsIgnoreCase314(System.getProperty("sun.security.policy.utf8"));315return System.getProperty("sun.security.policy.numcaches");316}});317318int numCaches;319if (numCacheStr != null) {320try {321numCaches = Integer.parseInt(numCacheStr);322} catch (NumberFormatException e) {323numCaches = DEFAULT_CACHE_SIZE;324}325} else {326numCaches = DEFAULT_CACHE_SIZE;327}328PolicyInfo newInfo = new PolicyInfo(numCaches);329initPolicyFile(newInfo, url);330policyInfo = newInfo;331}332333private void initPolicyFile(final PolicyInfo newInfo, final URL url) {334335// always load default.policy336AccessController.doPrivileged(new PrivilegedAction<>() {337@Override338public Void run() {339initDefaultPolicy(newInfo);340return null;341}342});343344if (url != null) {345346/**347* If the caller specified a URL via Policy.getInstance,348* we only read from default.policy and that URL.349*/350351if (debug != null) {352debug.println("reading " + url);353}354AccessController.doPrivileged(new PrivilegedAction<>() {355@Override356public Void run() {357if (init(url, newInfo) == false) {358// use static policy if all else fails359initStaticPolicy(newInfo);360}361return null;362}363});364365} else {366367/**368* Caller did not specify URL via Policy.getInstance.369* Read from URLs listed in the java.security properties file.370*/371372boolean loaded_one = initPolicyFile(POLICY, POLICY_URL, newInfo);373// To maintain strict backward compatibility374// we load the static policy only if POLICY load failed375if (!loaded_one) {376// use static policy if all else fails377initStaticPolicy(newInfo);378}379}380}381382private boolean initPolicyFile(final String propname, final String urlname,383final PolicyInfo newInfo) {384boolean loadedPolicy =385AccessController.doPrivileged(new PrivilegedAction<>() {386@Override387public Boolean run() {388boolean loaded_policy = false;389390if (allowSystemProperties) {391String extra_policy = System.getProperty(propname);392if (extra_policy != null) {393boolean overrideAll = false;394if (extra_policy.startsWith("=")) {395overrideAll = true;396extra_policy = extra_policy.substring(1);397}398try {399extra_policy =400PropertyExpander.expand(extra_policy);401URL policyURL;402403File policyFile = new File(extra_policy);404if (policyFile.exists()) {405policyURL = ParseUtil.fileToEncodedURL406(new File(policyFile.getCanonicalPath()));407} else {408policyURL = new URL(extra_policy);409}410if (debug != null) {411debug.println("reading "+policyURL);412}413if (init(policyURL, newInfo)) {414loaded_policy = true;415}416} catch (Exception e) {417// ignore.418if (debug != null) {419debug.println("caught exception: "+e);420}421}422if (overrideAll) {423if (debug != null) {424debug.println("overriding other policies!");425}426return Boolean.valueOf(loaded_policy);427}428}429}430431int n = 1;432String policy_uri;433434while ((policy_uri = Security.getProperty(urlname+n)) != null) {435try {436URL policy_url = null;437String expanded_uri = PropertyExpander.expand438(policy_uri).replace(File.separatorChar, '/');439440if (policy_uri.startsWith("file:${java.home}/") ||441policy_uri.startsWith("file:${user.home}/")) {442443// this special case accommodates444// the situation java.home/user.home445// expand to a single slash, resulting in446// a file://foo URI447policy_url = new File448(expanded_uri.substring(5)).toURI().toURL();449} else {450policy_url = new URI(expanded_uri).toURL();451}452453if (debug != null) {454debug.println("reading " + policy_url);455}456if (init(policy_url, newInfo)) {457loaded_policy = true;458}459} catch (Exception e) {460if (debug != null) {461debug.println(462"Debug info only. Error reading policy " +e);463e.printStackTrace();464}465// ignore that policy466}467n++;468}469return Boolean.valueOf(loaded_policy);470}471});472473return loadedPolicy;474}475476private void initDefaultPolicy(PolicyInfo newInfo) {477Path defaultPolicy = Path.of(StaticProperty.javaHome(),478"lib",479"security",480"default.policy");481if (debug != null) {482debug.println("reading " + defaultPolicy);483}484try (BufferedReader br = Files.newBufferedReader(defaultPolicy)) {485486PolicyParser pp = new PolicyParser(expandProperties);487pp.read(br);488489Enumeration<PolicyParser.GrantEntry> enum_ = pp.grantElements();490while (enum_.hasMoreElements()) {491PolicyParser.GrantEntry ge = enum_.nextElement();492addGrantEntry(ge, null, newInfo);493}494} catch (Exception e) {495throw new InternalError("Failed to load default.policy", e);496}497}498499/**500* Reads a policy configuration into the Policy object using a501* Reader object.502*/503private boolean init(URL policy, PolicyInfo newInfo) {504505// skip parsing policy file if it has been previously parsed and506// has syntax errors507if (badPolicyURLs.contains(policy)) {508if (debug != null) {509debug.println("skipping bad policy file: " + policy);510}511return false;512}513514try (InputStreamReader isr =515getInputStreamReader(PolicyUtil.getInputStream(policy))) {516517PolicyParser pp = new PolicyParser(expandProperties);518pp.read(isr);519520KeyStore keyStore = null;521try {522keyStore = PolicyUtil.getKeyStore523(policy,524pp.getKeyStoreUrl(),525pp.getKeyStoreType(),526pp.getKeyStoreProvider(),527pp.getStorePassURL(),528debug);529} catch (Exception e) {530// ignore, treat it like we have no keystore531if (debug != null) {532debug.println("Debug info only. Ignoring exception.");533e.printStackTrace();534}535}536537Enumeration<PolicyParser.GrantEntry> enum_ = pp.grantElements();538while (enum_.hasMoreElements()) {539PolicyParser.GrantEntry ge = enum_.nextElement();540addGrantEntry(ge, keyStore, newInfo);541}542return true;543} catch (PolicyParser.ParsingException pe) {544// record bad policy file to avoid later reparsing it545badPolicyURLs.add(policy);546Object[] source = {policy, pe.getNonlocalizedMessage()};547System.err.println(LocalizedMessage.getNonlocalized548(POLICY + ".error.parsing.policy.message", source));549if (debug != null) {550pe.printStackTrace();551}552} catch (Exception e) {553if (debug != null) {554debug.println("error parsing "+policy);555debug.println(e.toString());556e.printStackTrace();557}558}559560return false;561}562563private InputStreamReader getInputStreamReader(InputStream is) {564/*565* Read in policy using UTF-8 by default.566*567* Check non-standard system property to see if the default encoding568* should be used instead.569*/570return (notUtf8)571? new InputStreamReader(is)572: new InputStreamReader(is, UTF_8);573}574575private void initStaticPolicy(final PolicyInfo newInfo) {576if (debug != null) {577debug.println("Initializing with static permissions");578}579AccessController.doPrivileged(new PrivilegedAction<>() {580@Override581public Void run() {582PolicyEntry pe = new PolicyEntry(new CodeSource(null,583(Certificate[]) null));584pe.add(SecurityConstants.LOCAL_LISTEN_PERMISSION);585pe.add(new PropertyPermission("java.version",586SecurityConstants.PROPERTY_READ_ACTION));587pe.add(new PropertyPermission("java.vendor",588SecurityConstants.PROPERTY_READ_ACTION));589pe.add(new PropertyPermission("java.vendor.url",590SecurityConstants.PROPERTY_READ_ACTION));591pe.add(new PropertyPermission("java.class.version",592SecurityConstants.PROPERTY_READ_ACTION));593pe.add(new PropertyPermission("os.name",594SecurityConstants.PROPERTY_READ_ACTION));595pe.add(new PropertyPermission("os.version",596SecurityConstants.PROPERTY_READ_ACTION));597pe.add(new PropertyPermission("os.arch",598SecurityConstants.PROPERTY_READ_ACTION));599pe.add(new PropertyPermission("file.separator",600SecurityConstants.PROPERTY_READ_ACTION));601pe.add(new PropertyPermission("path.separator",602SecurityConstants.PROPERTY_READ_ACTION));603pe.add(new PropertyPermission("line.separator",604SecurityConstants.PROPERTY_READ_ACTION));605pe.add(new PropertyPermission606("java.specification.version",607SecurityConstants.PROPERTY_READ_ACTION));608pe.add(new PropertyPermission609("java.specification.vendor",610SecurityConstants.PROPERTY_READ_ACTION));611pe.add(new PropertyPermission612("java.specification.name",613SecurityConstants.PROPERTY_READ_ACTION));614pe.add(new PropertyPermission615("java.vm.specification.version",616SecurityConstants.PROPERTY_READ_ACTION));617pe.add(new PropertyPermission618("java.vm.specification.vendor",619SecurityConstants.PROPERTY_READ_ACTION));620pe.add(new PropertyPermission621("java.vm.specification.name",622SecurityConstants.PROPERTY_READ_ACTION));623pe.add(new PropertyPermission("java.vm.version",624SecurityConstants.PROPERTY_READ_ACTION));625pe.add(new PropertyPermission("java.vm.vendor",626SecurityConstants.PROPERTY_READ_ACTION));627pe.add(new PropertyPermission("java.vm.name",628SecurityConstants.PROPERTY_READ_ACTION));629630// No need to sync because noone has access to newInfo yet631newInfo.policyEntries.add(pe);632633return null;634}635});636}637638/**639* Given a GrantEntry, create a codeSource.640*641* @return null if signedBy alias is not recognized642*/643private CodeSource getCodeSource(PolicyParser.GrantEntry ge, KeyStore keyStore,644PolicyInfo newInfo) throws java.net.MalformedURLException645{646Certificate[] certs = null;647if (ge.signedBy != null) {648certs = getCertificates(keyStore, ge.signedBy, newInfo);649if (certs == null) {650// we don't have a key for this alias,651// just return652if (debug != null) {653debug.println(" -- No certs for alias '" +654ge.signedBy + "' - ignoring entry");655}656return null;657}658}659660URL location;661662if (ge.codeBase != null)663location = new URL(ge.codeBase);664else665location = null;666667return (canonicalizeCodebase(new CodeSource(location, certs),false));668}669670/**671* Add one policy entry to the list.672*/673private void addGrantEntry(PolicyParser.GrantEntry ge,674KeyStore keyStore, PolicyInfo newInfo) {675676if (debug != null) {677debug.println("Adding policy entry: ");678debug.println(" signedBy " + ge.signedBy);679debug.println(" codeBase " + ge.codeBase);680if (ge.principals != null) {681for (PolicyParser.PrincipalEntry pppe : ge.principals) {682debug.println(" " + pppe.toString());683}684}685}686687try {688CodeSource codesource = getCodeSource(ge, keyStore, newInfo);689// skip if signedBy alias was unknown...690if (codesource == null) return;691692// perform keystore alias principal replacement.693// for example, if alias resolves to X509 certificate,694// replace principal with: <X500Principal class> <SubjectDN>695// -- skip if alias is unknown696if (replacePrincipals(ge.principals, keyStore) == false)697return;698PolicyEntry entry = new PolicyEntry(codesource, ge.principals);699Enumeration<PolicyParser.PermissionEntry> enum_ =700ge.permissionElements();701while (enum_.hasMoreElements()) {702PolicyParser.PermissionEntry pe = enum_.nextElement();703704try {705// perform ${{ ... }} expansions within permission name706expandPermissionName(pe, keyStore);707708// XXX special case PrivateCredentialPermission-SELF709Permission perm;710if (pe.permission.equals711("javax.security.auth.PrivateCredentialPermission") &&712pe.name.endsWith(" self")) {713pe.name = pe.name.substring(0, pe.name.indexOf("self"))714+ SELF;715}716// check for self717if (pe.name != null && pe.name.indexOf(SELF) != -1) {718// Create a "SelfPermission" , it could be an719// an unresolved permission which will be resolved720// when implies is called721// Add it to entry722Certificate[] certs;723if (pe.signedBy != null) {724certs = getCertificates(keyStore,725pe.signedBy,726newInfo);727} else {728certs = null;729}730perm = new SelfPermission(pe.permission,731pe.name,732pe.action,733certs);734} else {735perm = getInstance(pe.permission,736pe.name,737pe.action);738}739entry.add(perm);740if (debug != null) {741debug.println(" "+perm);742}743} catch (ClassNotFoundException cnfe) {744Certificate[] certs;745if (pe.signedBy != null) {746certs = getCertificates(keyStore,747pe.signedBy,748newInfo);749} else {750certs = null;751}752753// only add if we had no signer or we had754// a signer and found the keys for it.755if (certs != null || pe.signedBy == null) {756Permission perm = new UnresolvedPermission(757pe.permission,758pe.name,759pe.action,760certs);761entry.add(perm);762if (debug != null) {763debug.println(" "+perm);764}765}766} catch (java.lang.reflect.InvocationTargetException ite) {767Object[] source = {pe.permission,768ite.getCause().toString()};769System.err.println(770LocalizedMessage.getNonlocalized(771POLICY + ".error.adding.Permission.perm.message",772source));773} catch (Exception e) {774Object[] source = {pe.permission,775e.toString()};776System.err.println(777LocalizedMessage.getNonlocalized(778POLICY + ".error.adding.Permission.perm.message",779source));780}781}782783// No need to sync because noone has access to newInfo yet784newInfo.policyEntries.add(entry);785} catch (Exception e) {786Object[] source = {e.toString()};787System.err.println(788LocalizedMessage.getNonlocalized(789POLICY + ".error.adding.Entry.message",790source));791}792if (debug != null)793debug.println();794}795796/**797* Returns a new Permission object of the given Type. The Permission is798* created by getting the799* Class object using the <code>Class.forName</code> method, and using800* the reflection API to invoke the (String name, String actions)801* constructor on the802* object.803*804* @param type the type of Permission being created.805* @param name the name of the Permission being created.806* @param actions the actions of the Permission being created.807*808* @exception ClassNotFoundException if the particular Permission809* class could not be found.810*811* @exception IllegalAccessException if the class or initializer is812* not accessible.813*814* @exception InstantiationException if getInstance tries to815* instantiate an abstract class or an interface, or if the816* instantiation fails for some other reason.817*818* @exception NoSuchMethodException if the (String, String) constructor819* is not found.820*821* @exception InvocationTargetException if the underlying Permission822* constructor throws an exception.823*824*/825826private static final Permission getInstance(String type,827String name,828String actions)829throws ClassNotFoundException,830InstantiationException,831IllegalAccessException,832NoSuchMethodException,833InvocationTargetException834{835Class<?> pc = Class.forName(type, false, null);836Permission answer = getKnownPermission(pc, name, actions);837if (answer != null) {838return answer;839}840if (!Permission.class.isAssignableFrom(pc)) {841// not the right subtype842throw new ClassCastException(type + " is not a Permission");843}844845if (name == null && actions == null) {846try {847Constructor<?> c = pc.getConstructor(PARAMS0);848return (Permission) c.newInstance(new Object[] {});849} catch (NoSuchMethodException ne) {850try {851Constructor<?> c = pc.getConstructor(PARAMS1);852return (Permission) c.newInstance(853new Object[] { name});854} catch (NoSuchMethodException ne1 ) {855Constructor<?> c = pc.getConstructor(PARAMS2);856return (Permission) c.newInstance(857new Object[] { name, actions });858}859}860} else {861if (name != null && actions == null) {862try {863Constructor<?> c = pc.getConstructor(PARAMS1);864return (Permission) c.newInstance(new Object[] { name});865} catch (NoSuchMethodException ne) {866Constructor<?> c = pc.getConstructor(PARAMS2);867return (Permission) c.newInstance(868new Object[] { name, actions });869}870} else {871Constructor<?> c = pc.getConstructor(PARAMS2);872return (Permission) c.newInstance(873new Object[] { name, actions });874}875}876}877878/**879* Creates one of the well-known permissions in the java.base module880* directly instead of via reflection. Keep list short to not penalize881* permissions from other modules.882*/883private static Permission getKnownPermission(Class<?> claz, String name,884String actions) {885if (claz.equals(FilePermission.class)) {886return new FilePermission(name, actions);887} else if (claz.equals(SocketPermission.class)) {888return new SocketPermission(name, actions);889} else if (claz.equals(RuntimePermission.class)) {890return new RuntimePermission(name, actions);891} else if (claz.equals(PropertyPermission.class)) {892return new PropertyPermission(name, actions);893} else if (claz.equals(NetPermission.class)) {894return new NetPermission(name, actions);895} else if (claz.equals(AllPermission.class)) {896return SecurityConstants.ALL_PERMISSION;897} else if (claz.equals(SecurityPermission.class)) {898return new SecurityPermission(name, actions);899} else {900return null;901}902}903904/**905* Creates one of the well-known principals in the java.base module906* directly instead of via reflection. Keep list short to not penalize907* principals from other modules.908*/909private static Principal getKnownPrincipal(Class<?> claz, String name) {910if (claz.equals(X500Principal.class)) {911return new X500Principal(name);912} else {913return null;914}915}916917/**918* Fetch all certs associated with this alias.919*/920private Certificate[] getCertificates921(KeyStore keyStore, String aliases, PolicyInfo newInfo) {922923List<Certificate> vcerts = null;924925StringTokenizer st = new StringTokenizer(aliases, ",");926int n = 0;927928while (st.hasMoreTokens()) {929String alias = st.nextToken().trim();930n++;931Certificate cert = null;932// See if this alias's cert has already been cached933synchronized (newInfo.aliasMapping) {934cert = (Certificate)newInfo.aliasMapping.get(alias);935936if (cert == null && keyStore != null) {937938try {939cert = keyStore.getCertificate(alias);940} catch (KeyStoreException kse) {941// never happens, because keystore has already been loaded942// when we call this943}944if (cert != null) {945newInfo.aliasMapping.put(alias, cert);946newInfo.aliasMapping.put(cert, alias);947}948}949}950951if (cert != null) {952if (vcerts == null)953vcerts = new ArrayList<>();954vcerts.add(cert);955}956}957958// make sure n == vcerts.size, since we are doing a logical *and*959if (vcerts != null && n == vcerts.size()) {960Certificate[] certs = new Certificate[vcerts.size()];961vcerts.toArray(certs);962return certs;963} else {964return null;965}966}967968/**969* Refreshes the policy object by re-reading all the policy files.970*/971@Override public void refresh() {972init(url);973}974975/**976* Evaluates the global policy for the permissions granted to977* the ProtectionDomain and tests whether the permission is978* granted.979*980* @param pd the ProtectionDomain to test981* @param p the Permission object to be tested for implication.982*983* @return true if "permission" is a proper subset of a permission984* granted to this ProtectionDomain.985*986* @see java.security.ProtectionDomain987*/988@Override989public boolean implies(ProtectionDomain pd, Permission p) {990ProtectionDomainCache pdMap = policyInfo.getPdMapping();991PermissionCollection pc = pdMap.get(pd);992993if (pc != null) {994return pc.implies(p);995}996997pc = getPermissions(pd);998if (pc == null) {999return false;1000}10011002// cache mapping of protection domain to its PermissionCollection1003pdMap.put(pd, pc);1004return pc.implies(p);1005}10061007/**1008* Examines this <code>Policy</code> and returns the permissions granted1009* to the specified <code>ProtectionDomain</code>. This includes1010* the permissions currently associated with the domain as well1011* as the policy permissions granted to the domain's1012* CodeSource, ClassLoader, and Principals.1013*1014* <p> Note that this <code>Policy</code> implementation has1015* special handling for PrivateCredentialPermissions.1016* When this method encounters a <code>PrivateCredentialPermission</code>1017* which specifies "self" as the <code>Principal</code> class and name,1018* it does not add that <code>Permission</code> to the returned1019* <code>PermissionCollection</code>. Instead, it builds1020* a new <code>PrivateCredentialPermission</code>1021* for each <code>Principal</code> associated with the provided1022* <code>Subject</code>. Each new <code>PrivateCredentialPermission</code>1023* contains the same Credential class as specified in the1024* originally granted permission, as well as the Class and name1025* for the respective <code>Principal</code>.1026*1027* @param domain the Permissions granted to this1028* <code>ProtectionDomain</code> are returned.1029*1030* @return the Permissions granted to the provided1031* <code>ProtectionDomain</code>.1032*/1033@Override1034public PermissionCollection getPermissions(ProtectionDomain domain) {1035Permissions perms = new Permissions();10361037if (domain == null)1038return perms;10391040// first get policy perms1041getPermissions(perms, domain);10421043// add static perms1044// - adding static perms after policy perms is necessary1045// to avoid a regression for 43010641046PermissionCollection pc = domain.getPermissions();1047if (pc != null) {1048synchronized (pc) {1049Enumeration<Permission> e = pc.elements();1050while (e.hasMoreElements()) {1051perms.add(FilePermCompat.newPermPlusAltPath(e.nextElement()));1052}1053}1054}10551056return perms;1057}10581059/**1060* Examines this Policy and creates a PermissionCollection object with1061* the set of permissions for the specified CodeSource.1062*1063* @param codesource the CodeSource associated with the caller.1064* This encapsulates the original location of the code (where the code1065* came from) and the public key(s) of its signer.1066*1067* @return the set of permissions according to the policy.1068*/1069@Override1070public PermissionCollection getPermissions(CodeSource codesource) {1071return getPermissions(new Permissions(), codesource);1072}10731074/**1075* Examines the global policy and returns the provided Permissions1076* object with additional permissions granted to the specified1077* ProtectionDomain.1078*1079* @param perms the Permissions to populate1080* @param pd the ProtectionDomain associated with the caller.1081*1082* @return the set of Permissions according to the policy.1083*/1084private PermissionCollection getPermissions(Permissions perms,1085ProtectionDomain pd ) {1086if (debug != null) {1087debug.println("getPermissions:\n\t" + printPD(pd));1088}10891090final CodeSource cs = pd.getCodeSource();1091if (cs == null)1092return perms;10931094CodeSource canonCodeSource = AccessController.doPrivileged(1095new java.security.PrivilegedAction<>(){1096@Override1097public CodeSource run() {1098return canonicalizeCodebase(cs, true);1099}1100});1101return getPermissions(perms, canonCodeSource, pd.getPrincipals());1102}11031104/**1105* Examines the global policy and returns the provided Permissions1106* object with additional permissions granted to the specified1107* CodeSource.1108*1109* @param perms the permissions to populate1110* @param cs the codesource associated with the caller.1111* This encapsulates the original location of the code (where the code1112* came from) and the public key(s) of its signer.1113*1114* @return the set of permissions according to the policy.1115*/1116private PermissionCollection getPermissions(Permissions perms,1117final CodeSource cs) {11181119if (cs == null)1120return perms;11211122CodeSource canonCodeSource = AccessController.doPrivileged(1123new PrivilegedAction<>(){1124@Override1125public CodeSource run() {1126return canonicalizeCodebase(cs, true);1127}1128});11291130return getPermissions(perms, canonCodeSource, null);1131}11321133private Permissions getPermissions(Permissions perms,1134final CodeSource cs,1135Principal[] principals) {1136for (PolicyEntry entry : policyInfo.policyEntries) {1137addPermissions(perms, cs, principals, entry);1138}11391140return perms;1141}11421143private void addPermissions(Permissions perms,1144final CodeSource cs,1145Principal[] principals,1146final PolicyEntry entry) {11471148if (debug != null) {1149debug.println("evaluate codesources:\n" +1150"\tPolicy CodeSource: " + entry.getCodeSource() + "\n" +1151"\tActive CodeSource: " + cs);1152}11531154// check to see if the CodeSource implies1155Boolean imp = AccessController.doPrivileged1156(new PrivilegedAction<>() {1157@Override1158public Boolean run() {1159return entry.getCodeSource().implies(cs);1160}1161});1162if (!imp.booleanValue()) {1163if (debug != null) {1164debug.println("evaluation (codesource) failed");1165}11661167// CodeSource does not imply - return and try next policy entry1168return;1169}11701171// check to see if the Principals imply11721173List<PolicyParser.PrincipalEntry> entryPs = entry.getPrincipals();1174if (debug != null) {1175List<PolicyParser.PrincipalEntry> accPs = new ArrayList<>();1176if (principals != null) {1177for (int i = 0; i < principals.length; i++) {1178accPs.add(new PolicyParser.PrincipalEntry1179(principals[i].getClass().getName(),1180principals[i].getName()));1181}1182}1183debug.println("evaluate principals:\n" +1184"\tPolicy Principals: " + entryPs + "\n" +1185"\tActive Principals: " + accPs);1186}11871188if (entryPs == null || entryPs.isEmpty()) {11891190// policy entry has no principals -1191// add perms regardless of principals in current ACC11921193addPerms(perms, principals, entry);1194if (debug != null) {1195debug.println("evaluation (codesource/principals) passed");1196}1197return;11981199} else if (principals == null || principals.length == 0) {12001201// current thread has no principals but this policy entry1202// has principals - perms are not added12031204if (debug != null) {1205debug.println("evaluation (principals) failed");1206}1207return;1208}12091210// current thread has principals and this policy entry1211// has principals. see if policy entry principals match1212// principals in current ACC12131214for (PolicyParser.PrincipalEntry pppe : entryPs) {12151216// Check for wildcards1217if (pppe.isWildcardClass()) {1218// a wildcard class matches all principals in current ACC1219continue;1220}12211222if (pppe.isWildcardName()) {1223// a wildcard name matches any principal with the same class1224if (wildcardPrincipalNameImplies(pppe.principalClass,1225principals)) {1226continue;1227}1228if (debug != null) {1229debug.println("evaluation (principal name wildcard) failed");1230}1231// policy entry principal not in current ACC -1232// immediately return and go to next policy entry1233return;1234}12351236Set<Principal> pSet = new HashSet<>(Arrays.asList(principals));1237Subject subject = new Subject(true, pSet,1238Collections.EMPTY_SET,1239Collections.EMPTY_SET);1240try {1241ClassLoader cl = Thread.currentThread().getContextClassLoader();1242Class<?> pClass = Class.forName(pppe.principalClass, false, cl);1243Principal p = getKnownPrincipal(pClass, pppe.principalName);1244if (p == null) {1245if (!Principal.class.isAssignableFrom(pClass)) {1246// not the right subtype1247throw new ClassCastException(pppe.principalClass +1248" is not a Principal");1249}12501251Constructor<?> c = pClass.getConstructor(PARAMS1);1252p = (Principal)c.newInstance(new Object[] {1253pppe.principalName });12541255}12561257if (debug != null) {1258debug.println("found Principal " + p.getClass().getName());1259}12601261// check if the Principal implies the current1262// thread's principals1263if (!p.implies(subject)) {1264if (debug != null) {1265debug.println("evaluation (principal implies) failed");1266}12671268// policy principal does not imply the current Subject -1269// immediately return and go to next policy entry1270return;1271}1272} catch (Exception e) {1273// fall back to default principal comparison.1274// see if policy entry principal is in current ACC12751276if (debug != null) {1277e.printStackTrace();1278}12791280if (!pppe.implies(subject)) {1281if (debug != null) {1282debug.println("evaluation (default principal implies) failed");1283}12841285// policy entry principal not in current ACC -1286// immediately return and go to next policy entry1287return;1288}1289}12901291// either the principal information matched,1292// or the Principal.implies succeeded.1293// continue loop and test the next policy principal1294}12951296// all policy entry principals were found in the current ACC -1297// grant the policy permissions12981299if (debug != null) {1300debug.println("evaluation (codesource/principals) passed");1301}1302addPerms(perms, principals, entry);1303}13041305/**1306* Returns true if the array of principals contains at least one1307* principal of the specified class.1308*/1309private static boolean wildcardPrincipalNameImplies(String principalClass,1310Principal[] principals)1311{1312for (Principal p : principals) {1313if (principalClass.equals(p.getClass().getName())) {1314return true;1315}1316}1317return false;1318}13191320private void addPerms(Permissions perms,1321Principal[] accPs,1322PolicyEntry entry) {1323for (int i = 0; i < entry.permissions.size(); i++) {1324Permission p = entry.permissions.get(i);1325if (debug != null) {1326debug.println(" granting " + p);1327}13281329if (p instanceof SelfPermission) {1330// handle "SELF" permissions1331expandSelf((SelfPermission)p,1332entry.getPrincipals(),1333accPs,1334perms);1335} else {1336perms.add(FilePermCompat.newPermPlusAltPath(p));1337}1338}1339}13401341/**1342* @param sp the SelfPermission that needs to be expanded.1343*1344* @param entryPs list of principals for the Policy entry.1345*1346* @param pdp Principal array from the current ProtectionDomain.1347*1348* @param perms the PermissionCollection where the individual1349* Permissions will be added after expansion.1350*/13511352private void expandSelf(SelfPermission sp,1353List<PolicyParser.PrincipalEntry> entryPs,1354Principal[] pdp,1355Permissions perms) {13561357if (entryPs == null || entryPs.isEmpty()) {1358// No principals in the grant to substitute1359if (debug != null) {1360debug.println("Ignoring permission "1361+ sp.getSelfType()1362+ " with target name ("1363+ sp.getSelfName() + "). "1364+ "No Principal(s) specified "1365+ "in the grant clause. "1366+ "SELF-based target names are "1367+ "only valid in the context "1368+ "of a Principal-based grant entry."1369);1370}1371return;1372}1373int startIndex = 0;1374int v;1375StringBuilder sb = new StringBuilder();1376while ((v = sp.getSelfName().indexOf(SELF, startIndex)) != -1) {13771378// add non-SELF string1379sb.append(sp.getSelfName().substring(startIndex, v));13801381// expand SELF1382Iterator<PolicyParser.PrincipalEntry> pli = entryPs.iterator();1383while (pli.hasNext()) {1384PolicyParser.PrincipalEntry pppe = pli.next();1385String[][] principalInfo = getPrincipalInfo(pppe,pdp);1386for (int i = 0; i < principalInfo.length; i++) {1387if (i != 0) {1388sb.append(", ");1389}1390sb.append(principalInfo[i][0] + " " +1391"\"" + principalInfo[i][1] + "\"");1392}1393if (pli.hasNext()) {1394sb.append(", ");1395}1396}1397startIndex = v + SELF.length();1398}1399// add remaining string (might be the entire string)1400sb.append(sp.getSelfName().substring(startIndex));14011402if (debug != null) {1403debug.println(" expanded:\n\t" + sp.getSelfName()1404+ "\n into:\n\t" + sb.toString());1405}1406try {1407// first try to instantiate the permission1408perms.add(FilePermCompat.newPermPlusAltPath(getInstance(sp.getSelfType(),1409sb.toString(),1410sp.getSelfActions())));1411} catch (ClassNotFoundException cnfe) {1412// ok, the permission is not in the bootclasspath.1413// before we add an UnresolvedPermission, check to see1414// whether this perm already belongs to the collection.1415// if so, use that perm's ClassLoader to create a new1416// one.1417Class<?> pc = null;1418synchronized (perms) {1419Enumeration<Permission> e = perms.elements();1420while (e.hasMoreElements()) {1421Permission pElement = e.nextElement();1422if (pElement.getClass().getName().equals(sp.getSelfType())) {1423pc = pElement.getClass();1424break;1425}1426}1427}1428if (pc == null) {1429// create an UnresolvedPermission1430perms.add(new UnresolvedPermission(sp.getSelfType(),1431sb.toString(),1432sp.getSelfActions(),1433sp.getCerts()));1434} else {1435try {1436// we found an instantiated permission.1437// use its class loader to instantiate a new permission.1438Constructor<?> c;1439// name parameter can not be null1440if (sp.getSelfActions() == null) {1441try {1442c = pc.getConstructor(PARAMS1);1443perms.add((Permission)c.newInstance1444(new Object[] {sb.toString()}));1445} catch (NoSuchMethodException ne) {1446c = pc.getConstructor(PARAMS2);1447perms.add((Permission)c.newInstance1448(new Object[] {sb.toString(),1449sp.getSelfActions() }));1450}1451} else {1452c = pc.getConstructor(PARAMS2);1453perms.add((Permission)c.newInstance1454(new Object[] {sb.toString(),1455sp.getSelfActions()}));1456}1457} catch (Exception nme) {1458if (debug != null) {1459debug.println("self entry expansion " +1460" instantiation failed: "1461+ nme.toString());1462}1463}1464}1465} catch (Exception e) {1466if (debug != null) {1467debug.println(e.toString());1468}1469}1470}14711472/**1473* return the principal class/name pair in the 2D array.1474* array[x][y]: x corresponds to the array length.1475* if (y == 0), it's the principal class.1476* if (y == 1), it's the principal name.1477*/1478private String[][] getPrincipalInfo1479(PolicyParser.PrincipalEntry pe, Principal[] pdp) {14801481// there are 3 possibilities:1482// 1) the entry's Principal class and name are not wildcarded1483// 2) the entry's Principal name is wildcarded only1484// 3) the entry's Principal class and name are wildcarded14851486if (!pe.isWildcardClass() && !pe.isWildcardName()) {14871488// build an info array for the principal1489// from the Policy entry1490String[][] info = new String[1][2];1491info[0][0] = pe.principalClass;1492info[0][1] = pe.principalName;1493return info;14941495} else if (!pe.isWildcardClass() && pe.isWildcardName()) {14961497// build an info array for every principal1498// in the current domain which has a principal class1499// that is equal to policy entry principal class name1500List<Principal> plist = new ArrayList<>();1501for (int i = 0; i < pdp.length; i++) {1502if (pe.principalClass.equals(pdp[i].getClass().getName()))1503plist.add(pdp[i]);1504}1505String[][] info = new String[plist.size()][2];1506int i = 0;1507for (Principal p : plist) {1508info[i][0] = p.getClass().getName();1509info[i][1] = p.getName();1510i++;1511}1512return info;15131514} else {15151516// build an info array for every1517// one of the current Domain's principals15181519String[][] info = new String[pdp.length][2];15201521for (int i = 0; i < pdp.length; i++) {1522info[i][0] = pdp[i].getClass().getName();1523info[i][1] = pdp[i].getName();1524}1525return info;1526}1527}15281529/*1530* Returns the signer certificates from the list of certificates1531* associated with the given code source.1532*1533* The signer certificates are those certificates that were used1534* to verify signed code originating from the codesource location.1535*1536* This method assumes that in the given code source, each signer1537* certificate is followed by its supporting certificate chain1538* (which may be empty), and that the signer certificate and its1539* supporting certificate chain are ordered bottom-to-top1540* (i.e., with the signer certificate first and the (root) certificate1541* authority last).1542*/1543protected Certificate[] getSignerCertificates(CodeSource cs) {1544Certificate[] certs = null;1545if ((certs = cs.getCertificates()) == null)1546return null;1547for (int i=0; i<certs.length; i++) {1548if (!(certs[i] instanceof X509Certificate))1549return cs.getCertificates();1550}15511552// Do we have to do anything?1553int i = 0;1554int count = 0;1555while (i < certs.length) {1556count++;1557while (((i+1) < certs.length)1558&& ((X509Certificate)certs[i]).getIssuerX500Principal().equals(1559((X509Certificate)certs[i+1]).getSubjectX500Principal())) {1560i++;1561}1562i++;1563}1564if (count == certs.length)1565// Done1566return certs;15671568List<Certificate> userCertList = new ArrayList<>();1569i = 0;1570while (i < certs.length) {1571userCertList.add(certs[i]);1572while (((i+1) < certs.length)1573&& ((X509Certificate)certs[i]).getIssuerX500Principal().equals(1574((X509Certificate)certs[i+1]).getSubjectX500Principal())) {1575i++;1576}1577i++;1578}1579Certificate[] userCerts = new Certificate[userCertList.size()];1580userCertList.toArray(userCerts);1581return userCerts;1582}15831584private CodeSource canonicalizeCodebase(CodeSource cs,1585boolean extractSignerCerts) {15861587String path = null;15881589CodeSource canonCs = cs;1590URL u = cs.getLocation();1591if (u != null) {1592if (u.getProtocol().equals("jar")) {1593// unwrap url embedded inside jar url1594String spec = u.getFile();1595int separator = spec.indexOf("!/");1596if (separator != -1) {1597try {1598u = new URL(spec.substring(0, separator));1599} catch (MalformedURLException e) {1600// Fail silently. In this case, url stays what1601// it was above1602}1603}1604}1605if (u.getProtocol().equals("file")) {1606boolean isLocalFile = false;1607String host = u.getHost();1608isLocalFile = (host == null || host.isEmpty() ||1609host.equals("~") || host.equalsIgnoreCase("localhost"));16101611if (isLocalFile) {1612path = u.getFile().replace('/', File.separatorChar);1613path = ParseUtil.decode(path);1614}1615}1616}16171618if (path != null) {1619try {1620URL csUrl = null;1621path = canonPath(path);1622csUrl = ParseUtil.fileToEncodedURL(new File(path));16231624if (extractSignerCerts) {1625canonCs = new CodeSource(csUrl,1626getSignerCertificates(cs));1627} else {1628canonCs = new CodeSource(csUrl,1629cs.getCertificates());1630}1631} catch (IOException ioe) {1632// leave codesource as it is, unless we have to extract its1633// signer certificates1634if (extractSignerCerts) {1635canonCs = new CodeSource(cs.getLocation(),1636getSignerCertificates(cs));1637}1638}1639} else {1640if (extractSignerCerts) {1641canonCs = new CodeSource(cs.getLocation(),1642getSignerCertificates(cs));1643}1644}1645return canonCs;1646}16471648// Wrapper to return a canonical path that avoids calling getCanonicalPath()1649// with paths that are intended to match all entries in the directory1650private static String canonPath(String path) throws IOException {1651if (path.endsWith("*")) {1652path = path.substring(0, path.length()-1) + "-";1653path = new File(path).getCanonicalPath();1654return path.substring(0, path.length()-1) + "*";1655} else {1656return new File(path).getCanonicalPath();1657}1658}16591660private String printPD(ProtectionDomain pd) {1661Principal[] principals = pd.getPrincipals();1662String pals = "<no principals>";1663if (principals != null && principals.length > 0) {1664StringBuilder palBuf = new StringBuilder("(principals ");1665for (int i = 0; i < principals.length; i++) {1666palBuf.append(principals[i].getClass().getName() +1667" \"" + principals[i].getName() +1668"\"");1669if (i < principals.length-1)1670palBuf.append(", ");1671else1672palBuf.append(")");1673}1674pals = palBuf.toString();1675}1676return "PD CodeSource: "1677+ pd.getCodeSource()1678+"\n\t" + "PD ClassLoader: "1679+ pd.getClassLoader()1680+"\n\t" + "PD Principals: "1681+ pals;1682}16831684/**1685* return true if no replacement was performed,1686* or if replacement succeeded.1687*/1688private boolean replacePrincipals(1689List<PolicyParser.PrincipalEntry> principals, KeyStore keystore) {16901691if (principals == null || principals.isEmpty() || keystore == null)1692return true;16931694for (PolicyParser.PrincipalEntry pppe : principals) {1695if (pppe.isReplaceName()) {16961697// perform replacement1698// (only X509 replacement is possible now)1699String name;1700if ((name = getDN(pppe.principalName, keystore)) == null) {1701return false;1702}17031704if (debug != null) {1705debug.println(" Replacing \"" +1706pppe.principalName +1707"\" with " +1708X500PRINCIPAL + "/\"" +1709name +1710"\"");1711}17121713pppe.principalClass = X500PRINCIPAL;1714pppe.principalName = name;1715}1716}1717// return true if no replacement was performed,1718// or if replacement succeeded1719return true;1720}17211722private void expandPermissionName(PolicyParser.PermissionEntry pe,1723KeyStore keystore) throws Exception {1724// short cut the common case1725if (pe.name == null || pe.name.indexOf("${{", 0) == -1) {1726return;1727}17281729int startIndex = 0;1730int b, e;1731StringBuilder sb = new StringBuilder();1732while ((b = pe.name.indexOf("${{", startIndex)) != -1) {1733e = pe.name.indexOf("}}", b);1734if (e < 1) {1735break;1736}1737sb.append(pe.name.substring(startIndex, b));17381739// get the value in ${{...}}1740String value = pe.name.substring(b+3, e);17411742// parse up to the first ':'1743int colonIndex;1744String prefix = value;1745String suffix;1746if ((colonIndex = value.indexOf(':')) != -1) {1747prefix = value.substring(0, colonIndex);1748}17491750// handle different prefix possibilities1751if (prefix.equalsIgnoreCase("self")) {1752// do nothing - handled later1753sb.append(pe.name.substring(b, e+2));1754startIndex = e+2;1755continue;1756} else if (prefix.equalsIgnoreCase("alias")) {1757// get the suffix and perform keystore alias replacement1758if (colonIndex == -1) {1759Object[] source = {pe.name};1760throw new Exception(1761LocalizedMessage.getNonlocalized(1762"alias.name.not.provided.pe.name.",1763source));1764}1765suffix = value.substring(colonIndex+1);1766if ((suffix = getDN(suffix, keystore)) == null) {1767Object[] source = {value.substring(colonIndex+1)};1768throw new Exception(1769LocalizedMessage.getNonlocalized(1770"unable.to.perform.substitution.on.alias.suffix",1771source));1772}17731774sb.append(X500PRINCIPAL + " \"" + suffix + "\"");1775startIndex = e+2;1776} else {1777Object[] source = {prefix};1778throw new Exception(1779LocalizedMessage.getNonlocalized(1780"substitution.value.prefix.unsupported",1781source));1782}1783}17841785// copy the rest of the value1786sb.append(pe.name.substring(startIndex));17871788// replace the name with expanded value1789if (debug != null) {1790debug.println(" Permission name expanded from:\n\t" +1791pe.name + "\nto\n\t" + sb.toString());1792}1793pe.name = sb.toString();1794}17951796private String getDN(String alias, KeyStore keystore) {1797Certificate cert = null;1798try {1799cert = keystore.getCertificate(alias);1800} catch (Exception e) {1801if (debug != null) {1802debug.println(" Error retrieving certificate for '" +1803alias +1804"': " +1805e.toString());1806}1807return null;1808}18091810if (cert == null || !(cert instanceof X509Certificate)) {1811if (debug != null) {1812debug.println(" -- No certificate for '" +1813alias +1814"' - ignoring entry");1815}1816return null;1817} else {1818X509Certificate x509Cert = (X509Certificate)cert;18191820// 4702543: X500 names with an EmailAddress1821// were encoded incorrectly. create new1822// X500Principal name with correct encoding18231824X500Principal p = new X500Principal1825(x509Cert.getSubjectX500Principal().toString());1826return p.getName();1827}1828}18291830/**1831* Each entry in the policy configuration file is represented by a1832* PolicyEntry object. <p>1833*1834* A PolicyEntry is a (CodeSource,Permission) pair. The1835* CodeSource contains the (URL, PublicKey) that together identify1836* where the Java bytecodes come from and who (if anyone) signed1837* them. The URL could refer to localhost. The URL could also be1838* null, meaning that this policy entry is given to all comers, as1839* long as they match the signer field. The signer could be null,1840* meaning the code is not signed. <p>1841*1842* The Permission contains the (Type, Name, Action) triplet. <p>1843*1844* For now, the Policy object retrieves the public key from the1845* X.509 certificate on disk that corresponds to the signedBy1846* alias specified in the Policy config file. For reasons of1847* efficiency, the Policy object keeps a hashtable of certs already1848* read in. This could be replaced by a secure internal key1849* store.1850*1851* <p>1852* For example, the entry1853* <pre>1854* permission java.io.File "/tmp", "read,write",1855* signedBy "Duke";1856* </pre>1857* is represented internally1858* <pre>1859*1860* FilePermission f = new FilePermission("/tmp", "read,write");1861* PublicKey p = publickeys.get("Duke");1862* URL u = InetAddress.getLocalHost();1863* CodeBase c = new CodeBase( p, u );1864* pe = new PolicyEntry(f, c);1865* </pre>1866*1867* @author Marianne Mueller1868* @author Roland Schemers1869* @see java.security.CodeSource1870* @see java.security.Policy1871* @see java.security.Permissions1872* @see java.security.ProtectionDomain1873*/1874private static class PolicyEntry {18751876private final CodeSource codesource;1877final List<Permission> permissions;1878private final List<PolicyParser.PrincipalEntry> principals;18791880/**1881* Given a Permission and a CodeSource, create a policy entry.1882*1883* XXX Decide if/how to add validity fields and "purpose" fields to1884* XXX policy entries1885*1886* @param cs the CodeSource, which encapsulates the URL and the1887* public key1888* attributes from the policy config file. Validity checks1889* are performed on the public key before PolicyEntry is1890* called.1891*1892*/1893PolicyEntry(CodeSource cs, List<PolicyParser.PrincipalEntry> principals)1894{1895this.codesource = cs;1896this.permissions = new ArrayList<Permission>();1897this.principals = principals; // can be null1898}18991900PolicyEntry(CodeSource cs)1901{1902this(cs, null);1903}19041905List<PolicyParser.PrincipalEntry> getPrincipals() {1906return principals; // can be null1907}19081909/**1910* add a Permission object to this entry.1911* No need to sync add op because perms are added to entry only1912* while entry is being initialized1913*/1914void add(Permission p) {1915permissions.add(p);1916}19171918/**1919* Return the CodeSource for this policy entry1920*/1921CodeSource getCodeSource() {1922return codesource;1923}19241925@Override public String toString(){1926StringBuilder sb = new StringBuilder();1927sb.append(ResourcesMgr.getString("LPARAM"));1928sb.append(getCodeSource());1929sb.append("\n");1930for (int j = 0; j < permissions.size(); j++) {1931Permission p = permissions.get(j);1932sb.append(ResourcesMgr.getString("SPACE"));1933sb.append(ResourcesMgr.getString("SPACE"));1934sb.append(p);1935sb.append(ResourcesMgr.getString("NEWLINE"));1936}1937sb.append(ResourcesMgr.getString("RPARAM"));1938sb.append(ResourcesMgr.getString("NEWLINE"));1939return sb.toString();1940}1941}19421943private static class SelfPermission extends Permission {19441945@java.io.Serial1946private static final long serialVersionUID = -8315562579967246806L;19471948/**1949* The class name of the Permission class that will be1950* created when this self permission is expanded .1951*1952* @serial1953*/1954private String type;19551956/**1957* The permission name.1958*1959* @serial1960*/1961private String name;19621963/**1964* The actions of the permission.1965*1966* @serial1967*/1968private String actions;19691970/**1971* The certs of the permission.1972*1973* @serial1974*/1975private Certificate[] certs;19761977/**1978* Creates a new SelfPermission containing the permission1979* information needed later to expand the self1980* @param type the class name of the Permission class that will be1981* created when this permission is expanded and if necessary resolved.1982* @param name the name of the permission.1983* @param actions the actions of the permission.1984* @param certs the certificates the permission's class was signed with.1985* This is a list of certificate chains, where each chain is composed of1986* a signer certificate and optionally its supporting certificate chain.1987* Each chain is ordered bottom-to-top (i.e., with the signer1988* certificate first and the (root) certificate authority last).1989*/1990public SelfPermission(String type, String name, String actions,1991Certificate[] certs)1992{1993super(type);1994if (type == null) {1995throw new NullPointerException1996(LocalizedMessage.getNonlocalized("type.can.t.be.null"));1997}1998this.type = type;1999this.name = name;2000this.actions = actions;2001if (certs != null) {2002// Extract the signer certs from the list of certificates.2003for (int i=0; i<certs.length; i++) {2004if (!(certs[i] instanceof X509Certificate)) {2005// there is no concept of signer certs, so we store the2006// entire cert array2007this.certs = certs.clone();2008break;2009}2010}20112012if (this.certs == null) {2013// Go through the list of certs and see if all the certs are2014// signer certs.2015int i = 0;2016int count = 0;2017while (i < certs.length) {2018count++;2019while (((i+1) < certs.length) &&2020((X509Certificate)certs[i]).getIssuerX500Principal().equals(2021((X509Certificate)certs[i+1]).getSubjectX500Principal())) {2022i++;2023}2024i++;2025}2026if (count == certs.length) {2027// All the certs are signer certs, so we store the2028// entire array2029this.certs = certs.clone();2030}20312032if (this.certs == null) {2033// extract the signer certs2034List<Certificate> signerCerts = new ArrayList<>();2035i = 0;2036while (i < certs.length) {2037signerCerts.add(certs[i]);2038while (((i+1) < certs.length) &&2039((X509Certificate)certs[i]).getIssuerX500Principal().equals(2040((X509Certificate)certs[i+1]).getSubjectX500Principal())) {2041i++;2042}2043i++;2044}2045this.certs = new Certificate[signerCerts.size()];2046signerCerts.toArray(this.certs);2047}2048}2049}2050}20512052/**2053* This method always returns false for SelfPermission permissions.2054* That is, an SelfPermission never considered to2055* imply another permission.2056*2057* @param p the permission to check against.2058*2059* @return false.2060*/2061@Override public boolean implies(Permission p) {2062return false;2063}20642065/**2066* Checks two SelfPermission objects for equality.2067*2068* Checks that <i>obj</i> is an SelfPermission, and has2069* the same type (class) name, permission name, actions, and2070* certificates as this object.2071*2072* @param obj the object we are testing for equality with this object.2073*2074* @return true if obj is an SelfPermission, and has the same2075* type (class) name, permission name, actions, and2076* certificates as this object.2077*/2078@Override public boolean equals(Object obj) {2079if (obj == this)2080return true;20812082if (! (obj instanceof SelfPermission))2083return false;2084SelfPermission that = (SelfPermission) obj;20852086if (!(this.type.equals(that.type) &&2087this.name.equals(that.name) &&2088this.actions.equals(that.actions)))2089return false;20902091if (this.certs.length != that.certs.length)2092return false;20932094int i,j;2095boolean match;20962097for (i = 0; i < this.certs.length; i++) {2098match = false;2099for (j = 0; j < that.certs.length; j++) {2100if (this.certs[i].equals(that.certs[j])) {2101match = true;2102break;2103}2104}2105if (!match) return false;2106}21072108for (i = 0; i < that.certs.length; i++) {2109match = false;2110for (j = 0; j < this.certs.length; j++) {2111if (that.certs[i].equals(this.certs[j])) {2112match = true;2113break;2114}2115}2116if (!match) return false;2117}2118return true;2119}21202121/**2122* Returns the hash code value for this object.2123*2124* @return a hash code value for this object.2125*/2126@Override public int hashCode() {2127int hash = type.hashCode();2128if (name != null)2129hash ^= name.hashCode();2130if (actions != null)2131hash ^= actions.hashCode();2132return hash;2133}21342135/**2136* Returns the canonical string representation of the actions,2137* which currently is the empty string "", since there are no actions2138* for an SelfPermission. That is, the actions for the2139* permission that will be created when this SelfPermission2140* is resolved may be non-null, but an SelfPermission2141* itself is never considered to have any actions.2142*2143* @return the empty string "".2144*/2145@Override public String getActions() {2146return "";2147}21482149public String getSelfType() {2150return type;2151}21522153public String getSelfName() {2154return name;2155}21562157public String getSelfActions() {2158return actions;2159}21602161public Certificate[] getCerts() {2162return certs;2163}21642165/**2166* Returns a string describing this SelfPermission. The convention2167* is to specify the class name, the permission name, and the actions,2168* in the following format: '(unresolved "ClassName" "name" "actions")'.2169*2170* @return information about this SelfPermission.2171*/2172@Override public String toString() {2173return "(SelfPermission " + type + " " + name + " " + actions + ")";2174}2175}21762177/**2178* holds policy information that we need to synch on2179*/2180private static class PolicyInfo {2181private static final boolean verbose = false;21822183// Stores grant entries in the policy2184final List<PolicyEntry> policyEntries;21852186// Maps aliases to certs2187final Map<Object, Object> aliasMapping;21882189// Maps ProtectionDomain to PermissionCollection2190private final ProtectionDomainCache[] pdMapping;2191private java.util.Random random;21922193PolicyInfo(int numCaches) {2194policyEntries = new ArrayList<>();2195aliasMapping = Collections.synchronizedMap(new HashMap<>(11));21962197pdMapping = new ProtectionDomainCache[numCaches];2198JavaSecurityAccess jspda2199= SharedSecrets.getJavaSecurityAccess();2200for (int i = 0; i < numCaches; i++) {2201pdMapping[i] = jspda.getProtectionDomainCache();2202}2203if (numCaches > 1) {2204random = new java.util.Random();2205}2206}2207ProtectionDomainCache getPdMapping() {2208if (pdMapping.length == 1) {2209return pdMapping[0];2210} else {2211int i = java.lang.Math.abs(random.nextInt() % pdMapping.length);2212return pdMapping[i];2213}2214}2215}2216}221722182219