1/* 2 * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26package sun.security.provider; 27 28import java.io.*; 29import java.lang.reflect.*; 30import java.net.MalformedURLException; 31import java.net.URL; 32import java.net.URI; 33import java.nio.file.Paths; 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.io.FilePermission; 41import java.net.SocketPermission; 42import java.net.NetPermission; 43import java.util.concurrent.atomic.AtomicReference; 44import jdk.internal.misc.JavaSecurityProtectionDomainAccess; 45import static jdk.internal.misc.JavaSecurityProtectionDomainAccess.ProtectionDomainCache; 46import jdk.internal.misc.SharedSecrets; 47import sun.security.util.*; 48import sun.net.www.ParseUtil; 49 50/** 51 * This class represents a default Policy implementation for the 52 * "JavaPolicy" type. 53 * 54 * Note: 55 * For backward compatibility with JAAS 1.0 it loads 56 * both java.auth.policy and java.policy. However, it 57 * is recommended that java.auth.policy not be used 58 * and that java.policy contain all grant entries including 59 * those that contain principal-based entries. 60 * 61 * <p> This object stores the policy for the entire Java runtime, 62 * and is the amalgamation of multiple static policy 63 * configurations that resides in files. 64 * The algorithm for locating the policy file(s) and reading their 65 * information into this <code>Policy</code> object is: 66 * 67 * <ol> 68 * <li> 69 * Read in and load the default policy file named 70 * <JAVA_HOME>/lib/security/default.policy. <JAVA_HOME> refers 71 * to the value of the java.home system property, and specifies the directory 72 * where the JRE is installed. This policy file grants permissions to the 73 * modules loaded by the platform class loader. If the default policy file 74 * cannot be loaded, a fatal InternalError is thrown as these permissions 75 * are needed in order for the runtime to operate correctly. 76 * <li> 77 * Loop through the <code>java.security.Security</code> properties, 78 * <i>policy.url.1</i>, <i>policy.url.2</i>, ..., 79 * <i>policy.url.X</i>" and 80 * <i>auth.policy.url.1</i>, <i>auth.policy.url.2</i>, ..., 81 * <i>auth.policy.url.X</i>". These properties are set 82 * in the Java security properties file, which is located in the file named 83 * <JAVA_HOME>/conf/security/java.security. 84 * Each property value specifies a <code>URL</code> pointing to a 85 * policy file to be loaded. Read in and load each policy. 86 * 87 * <i>auth.policy.url</i> is supported only for backward compatibility. 88 * 89 * If none of these could be loaded, use a builtin static policy 90 * equivalent to the conf/security/java.policy file. 91 * 92 * <li> 93 * The <code>java.lang.System</code> property <i>java.security.policy</i> 94 * may also be set to a <code>URL</code> pointing to another policy file 95 * (which is the case when a user uses the -D switch at runtime). 96 * If this property is defined, and its use is allowed by the 97 * security property file (the Security property, 98 * <i>policy.allowSystemProperty</i> is set to <i>true</i>), 99 * also load that policy. 100 * 101 * <li> 102 * The <code>java.lang.System</code> property 103 * <i>java.security.auth.policy</i> may also be set to a 104 * <code>URL</code> pointing to another policy file 105 * (which is the case when a user uses the -D switch at runtime). 106 * If this property is defined, and its use is allowed by the 107 * security property file (the Security property, 108 * <i>policy.allowSystemProperty</i> is set to <i>true</i>), 109 * also load that policy. 110 * 111 * <i>java.security.auth.policy</i> is supported only for backward 112 * compatibility. 113 * 114 * If the <i>java.security.policy</i> or 115 * <i>java.security.auth.policy</i> property is defined using 116 * "==" (rather than "="), then load the specified policy file and ignore 117 * all other configured policies. Note, that the default.policy file is 118 * also loaded, as specified in the first step of the algorithm above. 119 * If the specified policy file cannot be loaded, use a builtin static policy 120 * equivalent to the default conf/security/java.policy file. 121 * </ol> 122 * 123 * Each policy file consists of one or more grant entries, each of 124 * which consists of a number of permission entries. 125 * 126 * <pre> 127 * grant signedBy "<b>alias</b>", codeBase "<b>URL</b>", 128 * principal <b>principalClass</b> "<b>principalName</b>", 129 * principal <b>principalClass</b> "<b>principalName</b>", 130 * ... { 131 * 132 * permission <b>Type</b> "<b>name</b> "<b>action</b>", 133 * signedBy "<b>alias</b>"; 134 * permission <b>Type</b> "<b>name</b> "<b>action</b>", 135 * signedBy "<b>alias</b>"; 136 * .... 137 * }; 138 * </pre> 139 * 140 * All non-bold items above must appear as is (although case 141 * doesn't matter and some are optional, as noted below). 142 * principal entries are optional and need not be present. 143 * Italicized items represent variable values. 144 * 145 * <p> A grant entry must begin with the word <code>grant</code>. 146 * The <code>signedBy</code>,<code>codeBase</code> and <code>principal</code> 147 * name/value pairs are optional. 148 * If they are not present, then any signer (including unsigned code) 149 * will match, and any codeBase will match. 150 * Note that the <i>principalClass</i> 151 * may be set to the wildcard value, *, which allows it to match 152 * any <code>Principal</code> class. In addition, the <i>principalName</i> 153 * may also be set to the wildcard value, *, allowing it to match 154 * any <code>Principal</code> name. When setting the <i>principalName</i> 155 * to the *, do not surround the * with quotes. 156 * 157 * <p> A permission entry must begin with the word <code>permission</code>. 158 * The word <code><i>Type</i></code> in the template above is 159 * a specific permission type, such as <code>java.io.FilePermission</code> 160 * or <code>java.lang.RuntimePermission</code>. 161 * 162 * <p> The "<i>action</i>" is required for 163 * many permission types, such as <code>java.io.FilePermission</code> 164 * (where it specifies what type of file access that is permitted). 165 * It is not required for categories such as 166 * <code>java.lang.RuntimePermission</code> 167 * where it is not necessary - you either have the 168 * permission specified by the <code>"<i>name</i>"</code> 169 * value following the type name or you don't. 170 * 171 * <p> The <code>signedBy</code> name/value pair for a permission entry 172 * is optional. If present, it indicates a signed permission. That is, 173 * the permission class itself must be signed by the given alias in 174 * order for it to be granted. For example, 175 * suppose you have the following grant entry: 176 * 177 * <pre> 178 * grant principal foo.com.Principal "Duke" { 179 * permission Foo "foobar", signedBy "FooSoft"; 180 * } 181 * </pre> 182 * 183 * <p> Then this permission of type <i>Foo</i> is granted if the 184 * <code>Foo.class</code> permission has been signed by the 185 * "FooSoft" alias, or if XXX <code>Foo.class</code> is a 186 * system class (i.e., is found on the CLASSPATH). 187 * 188 * <p> Items that appear in an entry must appear in the specified order 189 * (<code>permission</code>, <i>Type</i>, "<i>name</i>", and 190 * "<i>action</i>"). An entry is terminated with a semicolon. 191 * 192 * <p> Case is unimportant for the identifiers (<code>permission</code>, 193 * <code>signedBy</code>, <code>codeBase</code>, etc.) but is 194 * significant for the <i>Type</i> 195 * or for any string that is passed in as a value. 196 * 197 * <p> An example of two entries in a policy configuration file is 198 * <pre> 199 * // if the code is comes from "foo.com" and is running as "Duke", 200 * // grant it read/write to all files in /tmp. 201 * 202 * grant codeBase "foo.com", principal foo.com.Principal "Duke" { 203 * permission java.io.FilePermission "/tmp/*", "read,write"; 204 * }; 205 * 206 * // grant any code running as "Duke" permission to read 207 * // the "java.vendor" Property. 208 * 209 * grant principal foo.com.Principal "Duke" { 210 * permission java.util.PropertyPermission "java.vendor"; 211 * 212 * 213 * </pre> 214 * This Policy implementation supports special handling of any 215 * permission that contains the string, "<b>${{self}}</b>", as part of 216 * its target name. When such a permission is evaluated 217 * (such as during a security check), <b>${{self}}</b> is replaced 218 * with one or more Principal class/name pairs. The exact 219 * replacement performed depends upon the contents of the 220 * grant clause to which the permission belongs. 221 * <p> 222 * 223 * If the grant clause does not contain any principal information, 224 * the permission will be ignored (permissions containing 225 * <b>${{self}}</b> in their target names are only valid in the context 226 * of a principal-based grant clause). For example, BarPermission 227 * will always be ignored in the following grant clause: 228 * 229 * <pre> 230 * grant codebase "www.foo.com", signedby "duke" { 231 * permission BarPermission "... ${{self}} ..."; 232 * }; 233 * </pre> 234 * 235 * If the grant clause contains principal information, <b>${{self}}</b> 236 * will be replaced with that same principal information. 237 * For example, <b>${{self}}</b> in BarPermission will be replaced by 238 * <b>javax.security.auth.x500.X500Principal "cn=Duke"</b> 239 * in the following grant clause: 240 * 241 * <pre> 242 * grant principal javax.security.auth.x500.X500Principal "cn=Duke" { 243 * permission BarPermission "... ${{self}} ..."; 244 * }; 245 * </pre> 246 * 247 * If there is a comma-separated list of principals in the grant 248 * clause, then <b>${{self}}</b> will be replaced by the same 249 * comma-separated list or principals. 250 * In the case where both the principal class and name are 251 * wildcarded in the grant clause, <b>${{self}}</b> is replaced 252 * with all the principals associated with the <code>Subject</code> 253 * in the current <code>AccessControlContext</code>. 254 * 255 * <p> For PrivateCredentialPermissions, you can also use "<b>self</b>" 256 * instead of "<b>${{self}}</b>". However the use of "<b>self</b>" is 257 * deprecated in favour of "<b>${{self}}</b>". 258 * 259 * @see java.security.CodeSource 260 * @see java.security.Permissions 261 * @see java.security.ProtectionDomain 262 */ 263public class PolicyFile extends java.security.Policy { 264 265 private static final Debug debug = Debug.getInstance("policy"); 266 267 private static final String SELF = "${{self}}"; 268 private static final String X500PRINCIPAL = 269 "javax.security.auth.x500.X500Principal"; 270 private static final String POLICY = "java.security.policy"; 271 private static final String POLICY_URL = "policy.url."; 272 private static final String AUTH_POLICY = "java.security.auth.policy"; 273 private static final String AUTH_POLICY_URL = "auth.policy.url."; 274 275 private static final int DEFAULT_CACHE_SIZE = 1; 276 277 // contains the policy grant entries, PD cache, and alias mapping 278 private AtomicReference<PolicyInfo> policyInfo = new AtomicReference<>(); 279 280 private boolean expandProperties = true; 281 private boolean allowSystemProperties = true; 282 private boolean notUtf8 = false; 283 private URL url; 284 285 // for use with the reflection API 286 private static final Class<?>[] PARAMS0 = { }; 287 private static final Class<?>[] PARAMS1 = { String.class }; 288 private static final Class<?>[] PARAMS2 = { String.class, String.class }; 289 290 /** 291 * When a policy file has a syntax error, the exception code may generate 292 * another permission check and this can cause the policy file to be parsed 293 * repeatedly, leading to a StackOverflowError or ClassCircularityError. 294 * To avoid this, this set is populated with policy files that have been 295 * previously parsed and have syntax errors, so that they can be 296 * subsequently ignored. 297 */ 298 private static AtomicReference<Set<URL>> badPolicyURLs = 299 new AtomicReference<>(new HashSet<>()); 300 301 // The default.policy file 302 private static final URL DEFAULT_POLICY_URL = 303 AccessController.doPrivileged(new PrivilegedAction<>() { 304 @Override 305 public URL run() { 306 String sep = File.separator; 307 try { 308 return Paths.get(System.getProperty("java.home"), 309 "lib", "security", 310 "default.policy").toUri().toURL(); 311 } catch (MalformedURLException mue) { 312 // should not happen 313 throw new Error("Malformed default.policy URL: " + mue); 314 } 315 } 316 }); 317 318 /** 319 * Initializes the Policy object and reads the default policy 320 * configuration file(s) into the Policy object. 321 */ 322 public PolicyFile() { 323 init((URL)null); 324 } 325 326 /** 327 * Initializes the Policy object and reads the default policy 328 * from the specified URL only. 329 */ 330 public PolicyFile(URL url) { 331 this.url = url; 332 init(url); 333 } 334 335 /** 336 * Initializes the Policy object and reads the default policy 337 * configuration file(s) into the Policy object. 338 * 339 * See the class description for details on the algorithm used to 340 * initialize the Policy object. 341 */ 342 private void init(URL url) { 343 // Properties are set once for each init(); ignore changes between 344 // between diff invocations of initPolicyFile(policy, url, info). 345 String numCacheStr = 346 AccessController.doPrivileged(new PrivilegedAction<>() { 347 @Override 348 public String run() { 349 expandProperties = "true".equalsIgnoreCase 350 (Security.getProperty("policy.expandProperties")); 351 allowSystemProperties = "true".equalsIgnoreCase 352 (Security.getProperty("policy.allowSystemProperty")); 353 notUtf8 = "false".equalsIgnoreCase 354 (System.getProperty("sun.security.policy.utf8")); 355 return System.getProperty("sun.security.policy.numcaches"); 356 }}); 357 358 int numCaches; 359 if (numCacheStr != null) { 360 try { 361 numCaches = Integer.parseInt(numCacheStr); 362 } catch (NumberFormatException e) { 363 numCaches = DEFAULT_CACHE_SIZE; 364 } 365 } else { 366 numCaches = DEFAULT_CACHE_SIZE; 367 } 368 // System.out.println("number caches=" + numCaches); 369 PolicyInfo newInfo = new PolicyInfo(numCaches); 370 initPolicyFile(newInfo, url); 371 policyInfo.set(newInfo); 372 } 373 374 private void initPolicyFile(final PolicyInfo newInfo, final URL url) { 375 376 // always load default.policy 377 if (debug != null) { 378 debug.println("reading " + DEFAULT_POLICY_URL); 379 } 380 AccessController.doPrivileged(new PrivilegedAction<>() { 381 @Override 382 public Void run() { 383 init(DEFAULT_POLICY_URL, newInfo, true); 384 return null; 385 } 386 }); 387 388 if (url != null) { 389 390 /** 391 * If the caller specified a URL via Policy.getInstance, 392 * we only read from default.policy and that URL. 393 */ 394 395 if (debug != null) { 396 debug.println("reading " + url); 397 } 398 AccessController.doPrivileged(new PrivilegedAction<>() { 399 @Override 400 public Void run() { 401 if (init(url, newInfo, false) == false) { 402 // use static policy if all else fails 403 initStaticPolicy(newInfo); 404 } 405 return null; 406 } 407 }); 408 409 } else { 410 411 /** 412 * Caller did not specify URL via Policy.getInstance. 413 * Read from URLs listed in the java.security properties file. 414 * 415 * We call initPolicyFile with POLICY, POLICY_URL and then 416 * call it with AUTH_POLICY and AUTH_POLICY_URL. 417 * So first we will process the JAVA standard policy 418 * and then process the JAVA AUTH Policy. 419 * This is for backward compatibility as well as to handle 420 * cases where the user has a single unified policyfile 421 * with both java policy entries and auth entries 422 */ 423 424 boolean loaded_one = initPolicyFile(POLICY, POLICY_URL, newInfo); 425 // To maintain strict backward compatibility 426 // we load the static policy only if POLICY load failed 427 if (!loaded_one) { 428 // use static policy if all else fails 429 initStaticPolicy(newInfo); 430 } 431 432 initPolicyFile(AUTH_POLICY, AUTH_POLICY_URL, newInfo); 433 } 434 } 435 436 private boolean initPolicyFile(final String propname, final String urlname, 437 final PolicyInfo newInfo) { 438 boolean loadedPolicy = 439 AccessController.doPrivileged(new PrivilegedAction<>() { 440 @Override 441 public Boolean run() { 442 boolean loaded_policy = false; 443 444 if (allowSystemProperties) { 445 String extra_policy = System.getProperty(propname); 446 if (extra_policy != null) { 447 boolean overrideAll = false; 448 if (extra_policy.startsWith("=")) { 449 overrideAll = true; 450 extra_policy = extra_policy.substring(1); 451 } 452 try { 453 extra_policy = 454 PropertyExpander.expand(extra_policy); 455 URL policyURL; 456 457 File policyFile = new File(extra_policy); 458 if (policyFile.exists()) { 459 policyURL = ParseUtil.fileToEncodedURL 460 (new File(policyFile.getCanonicalPath())); 461 } else { 462 policyURL = new URL(extra_policy); 463 } 464 if (debug != null) { 465 debug.println("reading "+policyURL); 466 } 467 if (init(policyURL, newInfo, false)) { 468 loaded_policy = true; 469 } 470 } catch (Exception e) { 471 // ignore. 472 if (debug != null) { 473 debug.println("caught exception: "+e); 474 } 475 } 476 if (overrideAll) { 477 if (debug != null) { 478 debug.println("overriding other policies!"); 479 } 480 return Boolean.valueOf(loaded_policy); 481 } 482 } 483 } 484 485 int n = 1; 486 String policy_uri; 487 488 while ((policy_uri = Security.getProperty(urlname+n)) != null) { 489 try { 490 URL policy_url = null; 491 String expanded_uri = PropertyExpander.expand 492 (policy_uri).replace(File.separatorChar, '/'); 493 494 if (policy_uri.startsWith("file:${java.home}/") || 495 policy_uri.startsWith("file:${user.home}/")) { 496 497 // this special case accommodates 498 // the situation java.home/user.home 499 // expand to a single slash, resulting in 500 // a file://foo URI 501 policy_url = new File 502 (expanded_uri.substring(5)).toURI().toURL(); 503 } else { 504 policy_url = new URI(expanded_uri).toURL(); 505 } 506 507 if (debug != null) { 508 debug.println("reading " + policy_url); 509 } 510 if (init(policy_url, newInfo, false)) { 511 loaded_policy = true; 512 } 513 } catch (Exception e) { 514 if (debug != null) { 515 debug.println("error reading policy "+e); 516 e.printStackTrace(); 517 } 518 // ignore that policy 519 } 520 n++; 521 } 522 return Boolean.valueOf(loaded_policy); 523 } 524 }); 525 526 return loadedPolicy; 527 } 528 529 /** 530 * Reads a policy configuration into the Policy object using a 531 * Reader object. 532 */ 533 private boolean init(URL policy, PolicyInfo newInfo, boolean defPolicy) { 534 535 // skip parsing policy file if it has been previously parsed and 536 // has syntax errors 537 if (badPolicyURLs.get().contains(policy)) { 538 if (debug != null) { 539 debug.println("skipping bad policy file: " + policy); 540 } 541 return false; 542 } 543 544 try (InputStreamReader isr = 545 getInputStreamReader(PolicyUtil.getInputStream(policy))) { 546 547 PolicyParser pp = new PolicyParser(expandProperties); 548 pp.read(isr); 549 550 KeyStore keyStore = null; 551 try { 552 keyStore = PolicyUtil.getKeyStore 553 (policy, 554 pp.getKeyStoreUrl(), 555 pp.getKeyStoreType(), 556 pp.getKeyStoreProvider(), 557 pp.getStorePassURL(), 558 debug); 559 } catch (Exception e) { 560 // ignore, treat it like we have no keystore 561 if (debug != null) { 562 e.printStackTrace(); 563 } 564 } 565 566 Enumeration<PolicyParser.GrantEntry> enum_ = pp.grantElements(); 567 while (enum_.hasMoreElements()) { 568 PolicyParser.GrantEntry ge = enum_.nextElement(); 569 addGrantEntry(ge, keyStore, newInfo); 570 } 571 return true; 572 } catch (PolicyParser.ParsingException pe) { 573 if (defPolicy) { 574 throw new InternalError("Failed to load default.policy", pe); 575 } 576 // record bad policy file to avoid later reparsing it 577 badPolicyURLs.updateAndGet(k -> { 578 k.add(policy); 579 return k; 580 }); 581 Object[] source = {policy, pe.getLocalizedMessage()}; 582 System.err.println(LocalizedMessage.getMessage 583 (POLICY + ".error.parsing.policy.message", source)); 584 if (debug != null) { 585 pe.printStackTrace(); 586 } 587 } catch (Exception e) { 588 if (defPolicy) { 589 throw new InternalError("Failed to load default.policy", e); 590 } 591 if (debug != null) { 592 debug.println("error parsing "+policy); 593 debug.println(e.toString()); 594 e.printStackTrace(); 595 } 596 } 597 598 return false; 599 } 600 601 private InputStreamReader getInputStreamReader(InputStream is) 602 throws IOException { 603 /* 604 * Read in policy using UTF-8 by default. 605 * 606 * Check non-standard system property to see if the default encoding 607 * should be used instead. 608 */ 609 return (notUtf8) 610 ? new InputStreamReader(is) 611 : new InputStreamReader(is, "UTF-8"); 612 } 613 614 private void initStaticPolicy(final PolicyInfo newInfo) { 615 if (debug != null) { 616 debug.println("Initializing with static permissions"); 617 } 618 AccessController.doPrivileged(new PrivilegedAction<>() { 619 @Override 620 public Void run() { 621 PolicyEntry pe = new PolicyEntry(new CodeSource(null, 622 (Certificate[]) null)); 623 pe.add(SecurityConstants.LOCAL_LISTEN_PERMISSION); 624 pe.add(new PropertyPermission("java.version", 625 SecurityConstants.PROPERTY_READ_ACTION)); 626 pe.add(new PropertyPermission("java.vendor", 627 SecurityConstants.PROPERTY_READ_ACTION)); 628 pe.add(new PropertyPermission("java.vendor.url", 629 SecurityConstants.PROPERTY_READ_ACTION)); 630 pe.add(new PropertyPermission("java.class.version", 631 SecurityConstants.PROPERTY_READ_ACTION)); 632 pe.add(new PropertyPermission("os.name", 633 SecurityConstants.PROPERTY_READ_ACTION)); 634 pe.add(new PropertyPermission("os.version", 635 SecurityConstants.PROPERTY_READ_ACTION)); 636 pe.add(new PropertyPermission("os.arch", 637 SecurityConstants.PROPERTY_READ_ACTION)); 638 pe.add(new PropertyPermission("file.separator", 639 SecurityConstants.PROPERTY_READ_ACTION)); 640 pe.add(new PropertyPermission("path.separator", 641 SecurityConstants.PROPERTY_READ_ACTION)); 642 pe.add(new PropertyPermission("line.separator", 643 SecurityConstants.PROPERTY_READ_ACTION)); 644 pe.add(new PropertyPermission 645 ("java.specification.version", 646 SecurityConstants.PROPERTY_READ_ACTION)); 647 pe.add(new PropertyPermission 648 ("java.specification.vendor", 649 SecurityConstants.PROPERTY_READ_ACTION)); 650 pe.add(new PropertyPermission 651 ("java.specification.name", 652 SecurityConstants.PROPERTY_READ_ACTION)); 653 pe.add(new PropertyPermission 654 ("java.vm.specification.version", 655 SecurityConstants.PROPERTY_READ_ACTION)); 656 pe.add(new PropertyPermission 657 ("java.vm.specification.vendor", 658 SecurityConstants.PROPERTY_READ_ACTION)); 659 pe.add(new PropertyPermission 660 ("java.vm.specification.name", 661 SecurityConstants.PROPERTY_READ_ACTION)); 662 pe.add(new PropertyPermission("java.vm.version", 663 SecurityConstants.PROPERTY_READ_ACTION)); 664 pe.add(new PropertyPermission("java.vm.vendor", 665 SecurityConstants.PROPERTY_READ_ACTION)); 666 pe.add(new PropertyPermission("java.vm.name", 667 SecurityConstants.PROPERTY_READ_ACTION)); 668 669 // No need to sync because noone has access to newInfo yet 670 newInfo.policyEntries.add(pe); 671 672 return null; 673 } 674 }); 675 } 676 677 /** 678 * Given a GrantEntry, create a codeSource. 679 * 680 * @return null if signedBy alias is not recognized 681 */ 682 private CodeSource getCodeSource(PolicyParser.GrantEntry ge, KeyStore keyStore, 683 PolicyInfo newInfo) throws java.net.MalformedURLException 684 { 685 Certificate[] certs = null; 686 if (ge.signedBy != null) { 687 certs = getCertificates(keyStore, ge.signedBy, newInfo); 688 if (certs == null) { 689 // we don't have a key for this alias, 690 // just return 691 if (debug != null) { 692 debug.println(" -- No certs for alias '" + 693 ge.signedBy + "' - ignoring entry"); 694 } 695 return null; 696 } 697 } 698 699 URL location; 700 701 if (ge.codeBase != null) 702 location = new URL(ge.codeBase); 703 else 704 location = null; 705 706 return (canonicalizeCodebase(new CodeSource(location, certs),false)); 707 } 708 709 /** 710 * Add one policy entry to the list. 711 */ 712 private void addGrantEntry(PolicyParser.GrantEntry ge, 713 KeyStore keyStore, PolicyInfo newInfo) { 714 715 if (debug != null) { 716 debug.println("Adding policy entry: "); 717 debug.println(" signedBy " + ge.signedBy); 718 debug.println(" codeBase " + ge.codeBase); 719 if (ge.principals != null) { 720 for (PolicyParser.PrincipalEntry pppe : ge.principals) { 721 debug.println(" " + pppe.toString()); 722 } 723 } 724 } 725 726 try { 727 CodeSource codesource = getCodeSource(ge, keyStore, newInfo); 728 // skip if signedBy alias was unknown... 729 if (codesource == null) return; 730 731 // perform keystore alias principal replacement. 732 // for example, if alias resolves to X509 certificate, 733 // replace principal with: <X500Principal class> <SubjectDN> 734 // -- skip if alias is unknown 735 if (replacePrincipals(ge.principals, keyStore) == false) 736 return; 737 PolicyEntry entry = new PolicyEntry(codesource, ge.principals); 738 Enumeration<PolicyParser.PermissionEntry> enum_ = 739 ge.permissionElements(); 740 while (enum_.hasMoreElements()) { 741 PolicyParser.PermissionEntry pe = enum_.nextElement(); 742 743 try { 744 // perform ${{ ... }} expansions within permission name 745 expandPermissionName(pe, keyStore); 746 747 // XXX special case PrivateCredentialPermission-SELF 748 Permission perm; 749 if (pe.permission.equals 750 ("javax.security.auth.PrivateCredentialPermission") && 751 pe.name.endsWith(" self")) { 752 pe.name = pe.name.substring(0, pe.name.indexOf("self")) 753 + SELF; 754 } 755 // check for self 756 if (pe.name != null && pe.name.indexOf(SELF) != -1) { 757 // Create a "SelfPermission" , it could be an 758 // an unresolved permission which will be resolved 759 // when implies is called 760 // Add it to entry 761 Certificate[] certs; 762 if (pe.signedBy != null) { 763 certs = getCertificates(keyStore, 764 pe.signedBy, 765 newInfo); 766 } else { 767 certs = null; 768 } 769 perm = new SelfPermission(pe.permission, 770 pe.name, 771 pe.action, 772 certs); 773 } else { 774 perm = getInstance(pe.permission, 775 pe.name, 776 pe.action); 777 } 778 entry.add(perm); 779 if (debug != null) { 780 debug.println(" "+perm); 781 } 782 } catch (ClassNotFoundException cnfe) { 783 Certificate[] certs; 784 if (pe.signedBy != null) { 785 certs = getCertificates(keyStore, 786 pe.signedBy, 787 newInfo); 788 } else { 789 certs = null; 790 } 791 792 // only add if we had no signer or we had a 793 // a signer and found the keys for it. 794 if (certs != null || pe.signedBy == null) { 795 Permission perm = new UnresolvedPermission( 796 pe.permission, 797 pe.name, 798 pe.action, 799 certs); 800 entry.add(perm); 801 if (debug != null) { 802 debug.println(" "+perm); 803 } 804 } 805 } catch (java.lang.reflect.InvocationTargetException ite) { 806 Object[] source = {pe.permission, 807 ite.getTargetException().toString()}; 808 System.err.println( 809 LocalizedMessage.getMessage( 810 POLICY + ".error.adding.Permission.perm.message", 811 source)); 812 } catch (Exception e) { 813 Object[] source = {pe.permission, 814 e.toString()}; 815 System.err.println( 816 LocalizedMessage.getMessage( 817 POLICY + ".error.adding.Permission.perm.message", 818 source)); 819 } 820 } 821 822 // No need to sync because noone has access to newInfo yet 823 newInfo.policyEntries.add(entry); 824 } catch (Exception e) { 825 Object[] source = {e.toString()}; 826 System.err.println( 827 LocalizedMessage.getMessage( 828 POLICY + ".error.adding.Entry.message", 829 source)); 830 } 831 if (debug != null) 832 debug.println(); 833 } 834 835 /** 836 * Returns a new Permission object of the given Type. The Permission is 837 * created by getting the 838 * Class object using the <code>Class.forName</code> method, and using 839 * the reflection API to invoke the (String name, String actions) 840 * constructor on the 841 * object. 842 * 843 * @param type the type of Permission being created. 844 * @param name the name of the Permission being created. 845 * @param actions the actions of the Permission being created. 846 * 847 * @exception ClassNotFoundException if the particular Permission 848 * class could not be found. 849 * 850 * @exception IllegalAccessException if the class or initializer is 851 * not accessible. 852 * 853 * @exception InstantiationException if getInstance tries to 854 * instantiate an abstract class or an interface, or if the 855 * instantiation fails for some other reason. 856 * 857 * @exception NoSuchMethodException if the (String, String) constructor 858 * is not found. 859 * 860 * @exception InvocationTargetException if the underlying Permission 861 * constructor throws an exception. 862 * 863 */ 864 865 private static final Permission getInstance(String type, 866 String name, 867 String actions) 868 throws ClassNotFoundException, 869 InstantiationException, 870 IllegalAccessException, 871 NoSuchMethodException, 872 InvocationTargetException 873 { 874 Class<?> pc = Class.forName(type, false, null); 875 Permission answer = getKnownPermission(pc, name, actions); 876 if (answer != null) { 877 return answer; 878 } 879 if (!Permission.class.isAssignableFrom(pc)) { 880 // not the right subtype 881 throw new ClassCastException(type + " is not a Permission"); 882 } 883 884 if (name == null && actions == null) { 885 try { 886 Constructor<?> c = pc.getConstructor(PARAMS0); 887 return (Permission) c.newInstance(new Object[] {}); 888 } catch (NoSuchMethodException ne) { 889 try { 890 Constructor<?> c = pc.getConstructor(PARAMS1); 891 return (Permission) c.newInstance( 892 new Object[] { name}); 893 } catch (NoSuchMethodException ne1 ) { 894 Constructor<?> c = pc.getConstructor(PARAMS2); 895 return (Permission) c.newInstance( 896 new Object[] { name, actions }); 897 } 898 } 899 } else { 900 if (name != null && actions == null) { 901 try { 902 Constructor<?> c = pc.getConstructor(PARAMS1); 903 return (Permission) c.newInstance(new Object[] { name}); 904 } catch (NoSuchMethodException ne) { 905 Constructor<?> c = pc.getConstructor(PARAMS2); 906 return (Permission) c.newInstance( 907 new Object[] { name, actions }); 908 } 909 } else { 910 Constructor<?> c = pc.getConstructor(PARAMS2); 911 return (Permission) c.newInstance( 912 new Object[] { name, actions }); 913 } 914 } 915 } 916 917 /** 918 * Creates one of the well-known permissions in the java.base module 919 * directly instead of via reflection. Keep list short to not penalize 920 * permissions from other modules. 921 */ 922 private static Permission getKnownPermission(Class<?> claz, String name, 923 String actions) { 924 if (claz.equals(FilePermission.class)) { 925 return new FilePermission(name, actions); 926 } else if (claz.equals(SocketPermission.class)) { 927 return new SocketPermission(name, actions); 928 } else if (claz.equals(RuntimePermission.class)) { 929 return new RuntimePermission(name, actions); 930 } else if (claz.equals(PropertyPermission.class)) { 931 return new PropertyPermission(name, actions); 932 } else if (claz.equals(NetPermission.class)) { 933 return new NetPermission(name, actions); 934 } else if (claz.equals(AllPermission.class)) { 935 return SecurityConstants.ALL_PERMISSION; 936 } else if (claz.equals(SecurityPermission.class)) { 937 return new SecurityPermission(name, actions); 938 } else { 939 return null; 940 } 941 } 942 943 /** 944 * Creates one of the well-known principals in the java.base module 945 * directly instead of via reflection. Keep list short to not penalize 946 * principals from other modules. 947 */ 948 private static Principal getKnownPrincipal(Class<?> claz, String name) { 949 if (claz.equals(X500Principal.class)) { 950 return new X500Principal(name); 951 } else { 952 return null; 953 } 954 } 955 956 /** 957 * Fetch all certs associated with this alias. 958 */ 959 private Certificate[] getCertificates 960 (KeyStore keyStore, String aliases, PolicyInfo newInfo) { 961 962 List<Certificate> vcerts = null; 963 964 StringTokenizer st = new StringTokenizer(aliases, ","); 965 int n = 0; 966 967 while (st.hasMoreTokens()) { 968 String alias = st.nextToken().trim(); 969 n++; 970 Certificate cert = null; 971 // See if this alias's cert has already been cached 972 synchronized (newInfo.aliasMapping) { 973 cert = (Certificate)newInfo.aliasMapping.get(alias); 974 975 if (cert == null && keyStore != null) { 976 977 try { 978 cert = keyStore.getCertificate(alias); 979 } catch (KeyStoreException kse) { 980 // never happens, because keystore has already been loaded 981 // when we call this 982 } 983 if (cert != null) { 984 newInfo.aliasMapping.put(alias, cert); 985 newInfo.aliasMapping.put(cert, alias); 986 } 987 } 988 } 989 990 if (cert != null) { 991 if (vcerts == null) 992 vcerts = new ArrayList<>(); 993 vcerts.add(cert); 994 } 995 } 996 997 // make sure n == vcerts.size, since we are doing a logical *and* 998 if (vcerts != null && n == vcerts.size()) { 999 Certificate[] certs = new Certificate[vcerts.size()]; 1000 vcerts.toArray(certs); 1001 return certs; 1002 } else { 1003 return null; 1004 } 1005 } 1006 1007 /** 1008 * Refreshes the policy object by re-reading all the policy files. 1009 */ 1010 @Override public void refresh() { 1011 init(url); 1012 } 1013 1014 /** 1015 * Evaluates the global policy for the permissions granted to 1016 * the ProtectionDomain and tests whether the permission is 1017 * granted. 1018 * 1019 * @param pd the ProtectionDomain to test 1020 * @param p the Permission object to be tested for implication. 1021 * 1022 * @return true if "permission" is a proper subset of a permission 1023 * granted to this ProtectionDomain. 1024 * 1025 * @see java.security.ProtectionDomain 1026 */ 1027 @Override 1028 public boolean implies(ProtectionDomain pd, Permission p) { 1029 PolicyInfo pi = policyInfo.get(); 1030 ProtectionDomainCache pdMap = pi.getPdMapping(); 1031 1032 PermissionCollection pc = pdMap.get(pd); 1033 1034 if (pc != null) { 1035 return pc.implies(p); 1036 } 1037 1038 pc = getPermissions(pd); 1039 if (pc == null) { 1040 return false; 1041 } 1042 1043 // cache mapping of protection domain to its PermissionCollection 1044 pdMap.put(pd, pc); 1045 return pc.implies(p); 1046 } 1047 1048 /** 1049 * Examines this <code>Policy</code> and returns the permissions granted 1050 * to the specified <code>ProtectionDomain</code>. This includes 1051 * the permissions currently associated with the domain as well 1052 * as the policy permissions granted to the domain's 1053 * CodeSource, ClassLoader, and Principals. 1054 * 1055 * <p> Note that this <code>Policy</code> implementation has 1056 * special handling for PrivateCredentialPermissions. 1057 * When this method encounters a <code>PrivateCredentialPermission</code> 1058 * which specifies "self" as the <code>Principal</code> class and name, 1059 * it does not add that <code>Permission</code> to the returned 1060 * <code>PermissionCollection</code>. Instead, it builds 1061 * a new <code>PrivateCredentialPermission</code> 1062 * for each <code>Principal</code> associated with the provided 1063 * <code>Subject</code>. Each new <code>PrivateCredentialPermission</code> 1064 * contains the same Credential class as specified in the 1065 * originally granted permission, as well as the Class and name 1066 * for the respective <code>Principal</code>. 1067 * 1068 * @param domain the Permissions granted to this 1069 * <code>ProtectionDomain</code> are returned. 1070 * 1071 * @return the Permissions granted to the provided 1072 * <code>ProtectionDomain</code>. 1073 */ 1074 @Override 1075 public PermissionCollection getPermissions(ProtectionDomain domain) { 1076 Permissions perms = new Permissions(); 1077 1078 if (domain == null) 1079 return perms; 1080 1081 // first get policy perms 1082 getPermissions(perms, domain); 1083 1084 // add static perms 1085 // - adding static perms after policy perms is necessary 1086 // to avoid a regression for 4301064 1087 PermissionCollection pc = domain.getPermissions(); 1088 if (pc != null) { 1089 synchronized (pc) { 1090 Enumeration<Permission> e = pc.elements(); 1091 while (e.hasMoreElements()) { 1092 perms.add(FilePermCompat.newPermPlusAltPath(e.nextElement())); 1093 } 1094 } 1095 } 1096 1097 return perms; 1098 } 1099 1100 /** 1101 * Examines this Policy and creates a PermissionCollection object with 1102 * the set of permissions for the specified CodeSource. 1103 * 1104 * @param codesource the CodeSource associated with the caller. 1105 * This encapsulates the original location of the code (where the code 1106 * came from) and the public key(s) of its signer. 1107 * 1108 * @return the set of permissions according to the policy. 1109 */ 1110 @Override 1111 public PermissionCollection getPermissions(CodeSource codesource) { 1112 return getPermissions(new Permissions(), codesource); 1113 } 1114 1115 /** 1116 * Examines the global policy and returns the provided Permissions 1117 * object with additional permissions granted to the specified 1118 * ProtectionDomain. 1119 * 1120 * @param perms the Permissions to populate 1121 * @param pd the ProtectionDomain associated with the caller. 1122 * 1123 * @return the set of Permissions according to the policy. 1124 */ 1125 private PermissionCollection getPermissions(Permissions perms, 1126 ProtectionDomain pd ) { 1127 if (debug != null) { 1128 debug.println("getPermissions:\n\t" + printPD(pd)); 1129 } 1130 1131 final CodeSource cs = pd.getCodeSource(); 1132 if (cs == null) 1133 return perms; 1134 1135 CodeSource canonCodeSource = AccessController.doPrivileged( 1136 new java.security.PrivilegedAction<>(){ 1137 @Override 1138 public CodeSource run() { 1139 return canonicalizeCodebase(cs, true); 1140 } 1141 }); 1142 return getPermissions(perms, canonCodeSource, pd.getPrincipals()); 1143 } 1144 1145 /** 1146 * Examines the global policy and returns the provided Permissions 1147 * object with additional permissions granted to the specified 1148 * CodeSource. 1149 * 1150 * @param perms the permissions to populate 1151 * @param cs the codesource associated with the caller. 1152 * This encapsulates the original location of the code (where the code 1153 * came from) and the public key(s) of its signer. 1154 * 1155 * @return the set of permissions according to the policy. 1156 */ 1157 private PermissionCollection getPermissions(Permissions perms, 1158 final CodeSource cs) { 1159 1160 if (cs == null) 1161 return perms; 1162 1163 CodeSource canonCodeSource = AccessController.doPrivileged( 1164 new PrivilegedAction<>(){ 1165 @Override 1166 public CodeSource run() { 1167 return canonicalizeCodebase(cs, true); 1168 } 1169 }); 1170 1171 return getPermissions(perms, canonCodeSource, null); 1172 } 1173 1174 private Permissions getPermissions(Permissions perms, 1175 final CodeSource cs, 1176 Principal[] principals) { 1177 PolicyInfo pi = policyInfo.get(); 1178 1179 for (PolicyEntry entry : pi.policyEntries) { 1180 addPermissions(perms, cs, principals, entry); 1181 } 1182 1183 return perms; 1184 } 1185 1186 private void addPermissions(Permissions perms, 1187 final CodeSource cs, 1188 Principal[] principals, 1189 final PolicyEntry entry) { 1190 1191 if (debug != null) { 1192 debug.println("evaluate codesources:\n" + 1193 "\tPolicy CodeSource: " + entry.getCodeSource() + "\n" + 1194 "\tActive CodeSource: " + cs); 1195 } 1196 1197 // check to see if the CodeSource implies 1198 Boolean imp = AccessController.doPrivileged 1199 (new PrivilegedAction<>() { 1200 @Override 1201 public Boolean run() { 1202 return entry.getCodeSource().implies(cs); 1203 } 1204 }); 1205 if (!imp.booleanValue()) { 1206 if (debug != null) { 1207 debug.println("evaluation (codesource) failed"); 1208 } 1209 1210 // CodeSource does not imply - return and try next policy entry 1211 return; 1212 } 1213 1214 // check to see if the Principals imply 1215 1216 List<PolicyParser.PrincipalEntry> entryPs = entry.getPrincipals(); 1217 if (debug != null) { 1218 List<PolicyParser.PrincipalEntry> accPs = new ArrayList<>(); 1219 if (principals != null) { 1220 for (int i = 0; i < principals.length; i++) { 1221 accPs.add(new PolicyParser.PrincipalEntry 1222 (principals[i].getClass().getName(), 1223 principals[i].getName())); 1224 } 1225 } 1226 debug.println("evaluate principals:\n" + 1227 "\tPolicy Principals: " + entryPs + "\n" + 1228 "\tActive Principals: " + accPs); 1229 } 1230 1231 if (entryPs == null || entryPs.isEmpty()) { 1232 1233 // policy entry has no principals - 1234 // add perms regardless of principals in current ACC 1235 1236 addPerms(perms, principals, entry); 1237 if (debug != null) { 1238 debug.println("evaluation (codesource/principals) passed"); 1239 } 1240 return; 1241 1242 } else if (principals == null || principals.length == 0) { 1243 1244 // current thread has no principals but this policy entry 1245 // has principals - perms are not added 1246 1247 if (debug != null) { 1248 debug.println("evaluation (principals) failed"); 1249 } 1250 return; 1251 } 1252 1253 // current thread has principals and this policy entry 1254 // has principals. see if policy entry principals match 1255 // principals in current ACC 1256 1257 for (PolicyParser.PrincipalEntry pppe : entryPs) { 1258 1259 // Check for wildcards 1260 if (pppe.isWildcardClass()) { 1261 // a wildcard class matches all principals in current ACC 1262 continue; 1263 } 1264 1265 if (pppe.isWildcardName()) { 1266 // a wildcard name matches any principal with the same class 1267 if (wildcardPrincipalNameImplies(pppe.principalClass, 1268 principals)) { 1269 continue; 1270 } 1271 if (debug != null) { 1272 debug.println("evaluation (principal name wildcard) failed"); 1273 } 1274 // policy entry principal not in current ACC - 1275 // immediately return and go to next policy entry 1276 return; 1277 } 1278 1279 Set<Principal> pSet = new HashSet<>(Arrays.asList(principals)); 1280 Subject subject = new Subject(true, pSet, 1281 Collections.EMPTY_SET, 1282 Collections.EMPTY_SET); 1283 try { 1284 ClassLoader cl = Thread.currentThread().getContextClassLoader(); 1285 Class<?> pClass = Class.forName(pppe.principalClass, false, cl); 1286 Principal p = getKnownPrincipal(pClass, pppe.principalName); 1287 if (p == null) { 1288 if (!Principal.class.isAssignableFrom(pClass)) { 1289 // not the right subtype 1290 throw new ClassCastException(pppe.principalClass + 1291 " is not a Principal"); 1292 } 1293 1294 Constructor<?> c = pClass.getConstructor(PARAMS1); 1295 p = (Principal)c.newInstance(new Object[] { 1296 pppe.principalName }); 1297 1298 } 1299 1300 if (debug != null) { 1301 debug.println("found Principal " + p.getClass().getName()); 1302 } 1303 1304 // check if the Principal implies the current 1305 // thread's principals 1306 if (!p.implies(subject)) { 1307 if (debug != null) { 1308 debug.println("evaluation (principal implies) failed"); 1309 } 1310 1311 // policy principal does not imply the current Subject - 1312 // immediately return and go to next policy entry 1313 return; 1314 } 1315 } catch (Exception e) { 1316 // fall back to default principal comparison. 1317 // see if policy entry principal is in current ACC 1318 1319 if (debug != null) { 1320 e.printStackTrace(); 1321 } 1322 1323 if (!pppe.implies(subject)) { 1324 if (debug != null) { 1325 debug.println("evaluation (default principal implies) failed"); 1326 } 1327 1328 // policy entry principal not in current ACC - 1329 // immediately return and go to next policy entry 1330 return; 1331 } 1332 } 1333 1334 // either the principal information matched, 1335 // or the Principal.implies succeeded. 1336 // continue loop and test the next policy principal 1337 } 1338 1339 // all policy entry principals were found in the current ACC - 1340 // grant the policy permissions 1341 1342 if (debug != null) { 1343 debug.println("evaluation (codesource/principals) passed"); 1344 } 1345 addPerms(perms, principals, entry); 1346 } 1347 1348 /** 1349 * Returns true if the array of principals contains at least one 1350 * principal of the specified class. 1351 */ 1352 private static boolean wildcardPrincipalNameImplies(String principalClass, 1353 Principal[] principals) 1354 { 1355 for (Principal p : principals) { 1356 if (principalClass.equals(p.getClass().getName())) { 1357 return true; 1358 } 1359 } 1360 return false; 1361 } 1362 1363 private void addPerms(Permissions perms, 1364 Principal[] accPs, 1365 PolicyEntry entry) { 1366 for (int i = 0; i < entry.permissions.size(); i++) { 1367 Permission p = entry.permissions.get(i); 1368 if (debug != null) { 1369 debug.println(" granting " + p); 1370 } 1371 1372 if (p instanceof SelfPermission) { 1373 // handle "SELF" permissions 1374 expandSelf((SelfPermission)p, 1375 entry.getPrincipals(), 1376 accPs, 1377 perms); 1378 } else { 1379 perms.add(FilePermCompat.newPermPlusAltPath(p)); 1380 } 1381 } 1382 } 1383 1384 /** 1385 * @param sp the SelfPermission that needs to be expanded. 1386 * 1387 * @param entryPs list of principals for the Policy entry. 1388 * 1389 * @param pdp Principal array from the current ProtectionDomain. 1390 * 1391 * @param perms the PermissionCollection where the individual 1392 * Permissions will be added after expansion. 1393 */ 1394 1395 private void expandSelf(SelfPermission sp, 1396 List<PolicyParser.PrincipalEntry> entryPs, 1397 Principal[] pdp, 1398 Permissions perms) { 1399 1400 if (entryPs == null || entryPs.isEmpty()) { 1401 // No principals in the grant to substitute 1402 if (debug != null) { 1403 debug.println("Ignoring permission " 1404 + sp.getSelfType() 1405 + " with target name (" 1406 + sp.getSelfName() + "). " 1407 + "No Principal(s) specified " 1408 + "in the grant clause. " 1409 + "SELF-based target names are " 1410 + "only valid in the context " 1411 + "of a Principal-based grant entry." 1412 ); 1413 } 1414 return; 1415 } 1416 int startIndex = 0; 1417 int v; 1418 StringBuilder sb = new StringBuilder(); 1419 while ((v = sp.getSelfName().indexOf(SELF, startIndex)) != -1) { 1420 1421 // add non-SELF string 1422 sb.append(sp.getSelfName().substring(startIndex, v)); 1423 1424 // expand SELF 1425 Iterator<PolicyParser.PrincipalEntry> pli = entryPs.iterator(); 1426 while (pli.hasNext()) { 1427 PolicyParser.PrincipalEntry pppe = pli.next(); 1428 String[][] principalInfo = getPrincipalInfo(pppe,pdp); 1429 for (int i = 0; i < principalInfo.length; i++) { 1430 if (i != 0) { 1431 sb.append(", "); 1432 } 1433 sb.append(principalInfo[i][0] + " " + 1434 "\"" + principalInfo[i][1] + "\""); 1435 } 1436 if (pli.hasNext()) { 1437 sb.append(", "); 1438 } 1439 } 1440 startIndex = v + SELF.length(); 1441 } 1442 // add remaining string (might be the entire string) 1443 sb.append(sp.getSelfName().substring(startIndex)); 1444 1445 if (debug != null) { 1446 debug.println(" expanded:\n\t" + sp.getSelfName() 1447 + "\n into:\n\t" + sb.toString()); 1448 } 1449 try { 1450 // first try to instantiate the permission 1451 perms.add(FilePermCompat.newPermPlusAltPath(getInstance(sp.getSelfType(), 1452 sb.toString(), 1453 sp.getSelfActions()))); 1454 } catch (ClassNotFoundException cnfe) { 1455 // ok, the permission is not in the bootclasspath. 1456 // before we add an UnresolvedPermission, check to see 1457 // whether this perm already belongs to the collection. 1458 // if so, use that perm's ClassLoader to create a new 1459 // one. 1460 Class<?> pc = null; 1461 synchronized (perms) { 1462 Enumeration<Permission> e = perms.elements(); 1463 while (e.hasMoreElements()) { 1464 Permission pElement = e.nextElement(); 1465 if (pElement.getClass().getName().equals(sp.getSelfType())) { 1466 pc = pElement.getClass(); 1467 break; 1468 } 1469 } 1470 } 1471 if (pc == null) { 1472 // create an UnresolvedPermission 1473 perms.add(new UnresolvedPermission(sp.getSelfType(), 1474 sb.toString(), 1475 sp.getSelfActions(), 1476 sp.getCerts())); 1477 } else { 1478 try { 1479 // we found an instantiated permission. 1480 // use its class loader to instantiate a new permission. 1481 Constructor<?> c; 1482 // name parameter can not be null 1483 if (sp.getSelfActions() == null) { 1484 try { 1485 c = pc.getConstructor(PARAMS1); 1486 perms.add((Permission)c.newInstance 1487 (new Object[] {sb.toString()})); 1488 } catch (NoSuchMethodException ne) { 1489 c = pc.getConstructor(PARAMS2); 1490 perms.add((Permission)c.newInstance 1491 (new Object[] {sb.toString(), 1492 sp.getSelfActions() })); 1493 } 1494 } else { 1495 c = pc.getConstructor(PARAMS2); 1496 perms.add((Permission)c.newInstance 1497 (new Object[] {sb.toString(), 1498 sp.getSelfActions()})); 1499 } 1500 } catch (Exception nme) { 1501 if (debug != null) { 1502 debug.println("self entry expansion " + 1503 " instantiation failed: " 1504 + nme.toString()); 1505 } 1506 } 1507 } 1508 } catch (Exception e) { 1509 if (debug != null) { 1510 debug.println(e.toString()); 1511 } 1512 } 1513 } 1514 1515 /** 1516 * return the principal class/name pair in the 2D array. 1517 * array[x][y]: x corresponds to the array length. 1518 * if (y == 0), it's the principal class. 1519 * if (y == 1), it's the principal name. 1520 */ 1521 private String[][] getPrincipalInfo 1522 (PolicyParser.PrincipalEntry pe, Principal[] pdp) { 1523 1524 // there are 3 possibilities: 1525 // 1) the entry's Principal class and name are not wildcarded 1526 // 2) the entry's Principal name is wildcarded only 1527 // 3) the entry's Principal class and name are wildcarded 1528 1529 if (!pe.isWildcardClass() && !pe.isWildcardName()) { 1530 1531 // build an info array for the principal 1532 // from the Policy entry 1533 String[][] info = new String[1][2]; 1534 info[0][0] = pe.principalClass; 1535 info[0][1] = pe.principalName; 1536 return info; 1537 1538 } else if (!pe.isWildcardClass() && pe.isWildcardName()) { 1539 1540 // build an info array for every principal 1541 // in the current domain which has a principal class 1542 // that is equal to policy entry principal class name 1543 List<Principal> plist = new ArrayList<>(); 1544 for (int i = 0; i < pdp.length; i++) { 1545 if (pe.principalClass.equals(pdp[i].getClass().getName())) 1546 plist.add(pdp[i]); 1547 } 1548 String[][] info = new String[plist.size()][2]; 1549 int i = 0; 1550 for (Principal p : plist) { 1551 info[i][0] = p.getClass().getName(); 1552 info[i][1] = p.getName(); 1553 i++; 1554 } 1555 return info; 1556 1557 } else { 1558 1559 // build an info array for every 1560 // one of the current Domain's principals 1561 1562 String[][] info = new String[pdp.length][2]; 1563 1564 for (int i = 0; i < pdp.length; i++) { 1565 info[i][0] = pdp[i].getClass().getName(); 1566 info[i][1] = pdp[i].getName(); 1567 } 1568 return info; 1569 } 1570 } 1571 1572 /* 1573 * Returns the signer certificates from the list of certificates 1574 * associated with the given code source. 1575 * 1576 * The signer certificates are those certificates that were used 1577 * to verify signed code originating from the codesource location. 1578 * 1579 * This method assumes that in the given code source, each signer 1580 * certificate is followed by its supporting certificate chain 1581 * (which may be empty), and that the signer certificate and its 1582 * supporting certificate chain are ordered bottom-to-top 1583 * (i.e., with the signer certificate first and the (root) certificate 1584 * authority last). 1585 */ 1586 protected Certificate[] getSignerCertificates(CodeSource cs) { 1587 Certificate[] certs = null; 1588 if ((certs = cs.getCertificates()) == null) 1589 return null; 1590 for (int i=0; i<certs.length; i++) { 1591 if (!(certs[i] instanceof X509Certificate)) 1592 return cs.getCertificates(); 1593 } 1594 1595 // Do we have to do anything? 1596 int i = 0; 1597 int count = 0; 1598 while (i < certs.length) { 1599 count++; 1600 while (((i+1) < certs.length) 1601 && ((X509Certificate)certs[i]).getIssuerDN().equals( 1602 ((X509Certificate)certs[i+1]).getSubjectDN())) { 1603 i++; 1604 } 1605 i++; 1606 } 1607 if (count == certs.length) 1608 // Done 1609 return certs; 1610 1611 List<Certificate> userCertList = new ArrayList<>(); 1612 i = 0; 1613 while (i < certs.length) { 1614 userCertList.add(certs[i]); 1615 while (((i+1) < certs.length) 1616 && ((X509Certificate)certs[i]).getIssuerDN().equals( 1617 ((X509Certificate)certs[i+1]).getSubjectDN())) { 1618 i++; 1619 } 1620 i++; 1621 } 1622 Certificate[] userCerts = new Certificate[userCertList.size()]; 1623 userCertList.toArray(userCerts); 1624 return userCerts; 1625 } 1626 1627 private CodeSource canonicalizeCodebase(CodeSource cs, 1628 boolean extractSignerCerts) { 1629 1630 String path = null; 1631 1632 CodeSource canonCs = cs; 1633 URL u = cs.getLocation(); 1634 if (u != null) { 1635 if (u.getProtocol().equals("jar")) { 1636 // unwrap url embedded inside jar url 1637 String spec = u.getFile(); 1638 int separator = spec.indexOf("!/"); 1639 if (separator != -1) { 1640 try { 1641 u = new URL(spec.substring(0, separator)); 1642 } catch (MalformedURLException e) { 1643 // Fail silently. In this case, url stays what 1644 // it was above 1645 } 1646 } 1647 } 1648 if (u.getProtocol().equals("file")) { 1649 boolean isLocalFile = false; 1650 String host = u.getHost(); 1651 isLocalFile = (host == null || host.equals("") || 1652 host.equals("~") || host.equalsIgnoreCase("localhost")); 1653 1654 if (isLocalFile) { 1655 path = u.getFile().replace('/', File.separatorChar); 1656 path = ParseUtil.decode(path); 1657 } 1658 } 1659 } 1660 1661 if (path != null) { 1662 try { 1663 URL csUrl = null; 1664 path = canonPath(path); 1665 csUrl = ParseUtil.fileToEncodedURL(new File(path)); 1666 1667 if (extractSignerCerts) { 1668 canonCs = new CodeSource(csUrl, 1669 getSignerCertificates(cs)); 1670 } else { 1671 canonCs = new CodeSource(csUrl, 1672 cs.getCertificates()); 1673 } 1674 } catch (IOException ioe) { 1675 // leave codesource as it is, unless we have to extract its 1676 // signer certificates 1677 if (extractSignerCerts) { 1678 canonCs = new CodeSource(cs.getLocation(), 1679 getSignerCertificates(cs)); 1680 } 1681 } 1682 } else { 1683 if (extractSignerCerts) { 1684 canonCs = new CodeSource(cs.getLocation(), 1685 getSignerCertificates(cs)); 1686 } 1687 } 1688 return canonCs; 1689 } 1690 1691 // Wrapper to return a canonical path that avoids calling getCanonicalPath() 1692 // with paths that are intended to match all entries in the directory 1693 private static String canonPath(String path) throws IOException { 1694 if (path.endsWith("*")) { 1695 path = path.substring(0, path.length()-1) + "-"; 1696 path = new File(path).getCanonicalPath(); 1697 return path.substring(0, path.length()-1) + "*"; 1698 } else { 1699 return new File(path).getCanonicalPath(); 1700 } 1701 } 1702 1703 private String printPD(ProtectionDomain pd) { 1704 Principal[] principals = pd.getPrincipals(); 1705 String pals = "<no principals>"; 1706 if (principals != null && principals.length > 0) { 1707 StringBuilder palBuf = new StringBuilder("(principals "); 1708 for (int i = 0; i < principals.length; i++) { 1709 palBuf.append(principals[i].getClass().getName() + 1710 " \"" + principals[i].getName() + 1711 "\""); 1712 if (i < principals.length-1) 1713 palBuf.append(", "); 1714 else 1715 palBuf.append(")"); 1716 } 1717 pals = palBuf.toString(); 1718 } 1719 return "PD CodeSource: " 1720 + pd.getCodeSource() 1721 +"\n\t" + "PD ClassLoader: " 1722 + pd.getClassLoader() 1723 +"\n\t" + "PD Principals: " 1724 + pals; 1725 } 1726 1727 /** 1728 * return true if no replacement was performed, 1729 * or if replacement succeeded. 1730 */ 1731 private boolean replacePrincipals( 1732 List<PolicyParser.PrincipalEntry> principals, KeyStore keystore) { 1733 1734 if (principals == null || principals.isEmpty() || keystore == null) 1735 return true; 1736 1737 for (PolicyParser.PrincipalEntry pppe : principals) { 1738 if (pppe.isReplaceName()) { 1739 1740 // perform replacement 1741 // (only X509 replacement is possible now) 1742 String name; 1743 if ((name = getDN(pppe.principalName, keystore)) == null) { 1744 return false; 1745 } 1746 1747 if (debug != null) { 1748 debug.println(" Replacing \"" + 1749 pppe.principalName + 1750 "\" with " + 1751 X500PRINCIPAL + "/\"" + 1752 name + 1753 "\""); 1754 } 1755 1756 pppe.principalClass = X500PRINCIPAL; 1757 pppe.principalName = name; 1758 } 1759 } 1760 // return true if no replacement was performed, 1761 // or if replacement succeeded 1762 return true; 1763 } 1764 1765 private void expandPermissionName(PolicyParser.PermissionEntry pe, 1766 KeyStore keystore) throws Exception { 1767 // short cut the common case 1768 if (pe.name == null || pe.name.indexOf("${{", 0) == -1) { 1769 return; 1770 } 1771 1772 int startIndex = 0; 1773 int b, e; 1774 StringBuilder sb = new StringBuilder(); 1775 while ((b = pe.name.indexOf("${{", startIndex)) != -1) { 1776 e = pe.name.indexOf("}}", b); 1777 if (e < 1) { 1778 break; 1779 } 1780 sb.append(pe.name.substring(startIndex, b)); 1781 1782 // get the value in ${{...}} 1783 String value = pe.name.substring(b+3, e); 1784 1785 // parse up to the first ':' 1786 int colonIndex; 1787 String prefix = value; 1788 String suffix; 1789 if ((colonIndex = value.indexOf(':')) != -1) { 1790 prefix = value.substring(0, colonIndex); 1791 } 1792 1793 // handle different prefix possibilities 1794 if (prefix.equalsIgnoreCase("self")) { 1795 // do nothing - handled later 1796 sb.append(pe.name.substring(b, e+2)); 1797 startIndex = e+2; 1798 continue; 1799 } else if (prefix.equalsIgnoreCase("alias")) { 1800 // get the suffix and perform keystore alias replacement 1801 if (colonIndex == -1) { 1802 Object[] source = {pe.name}; 1803 throw new Exception( 1804 LocalizedMessage.getMessage( 1805 "alias.name.not.provided.pe.name.", 1806 source)); 1807 } 1808 suffix = value.substring(colonIndex+1); 1809 if ((suffix = getDN(suffix, keystore)) == null) { 1810 Object[] source = {value.substring(colonIndex+1)}; 1811 throw new Exception( 1812 LocalizedMessage.getMessage( 1813 "unable.to.perform.substitution.on.alias.suffix", 1814 source)); 1815 } 1816 1817 sb.append(X500PRINCIPAL + " \"" + suffix + "\""); 1818 startIndex = e+2; 1819 } else { 1820 Object[] source = {prefix}; 1821 throw new Exception( 1822 LocalizedMessage.getMessage( 1823 "substitution.value.prefix.unsupported", 1824 source)); 1825 } 1826 } 1827 1828 // copy the rest of the value 1829 sb.append(pe.name.substring(startIndex)); 1830 1831 // replace the name with expanded value 1832 if (debug != null) { 1833 debug.println(" Permission name expanded from:\n\t" + 1834 pe.name + "\nto\n\t" + sb.toString()); 1835 } 1836 pe.name = sb.toString(); 1837 } 1838 1839 private String getDN(String alias, KeyStore keystore) { 1840 Certificate cert = null; 1841 try { 1842 cert = keystore.getCertificate(alias); 1843 } catch (Exception e) { 1844 if (debug != null) { 1845 debug.println(" Error retrieving certificate for '" + 1846 alias + 1847 "': " + 1848 e.toString()); 1849 } 1850 return null; 1851 } 1852 1853 if (cert == null || !(cert instanceof X509Certificate)) { 1854 if (debug != null) { 1855 debug.println(" -- No certificate for '" + 1856 alias + 1857 "' - ignoring entry"); 1858 } 1859 return null; 1860 } else { 1861 X509Certificate x509Cert = (X509Certificate)cert; 1862 1863 // 4702543: X500 names with an EmailAddress 1864 // were encoded incorrectly. create new 1865 // X500Principal name with correct encoding 1866 1867 X500Principal p = new X500Principal 1868 (x509Cert.getSubjectX500Principal().toString()); 1869 return p.getName(); 1870 } 1871 } 1872 1873 /** 1874 * Each entry in the policy configuration file is represented by a 1875 * PolicyEntry object. <p> 1876 * 1877 * A PolicyEntry is a (CodeSource,Permission) pair. The 1878 * CodeSource contains the (URL, PublicKey) that together identify 1879 * where the Java bytecodes come from and who (if anyone) signed 1880 * them. The URL could refer to localhost. The URL could also be 1881 * null, meaning that this policy entry is given to all comers, as 1882 * long as they match the signer field. The signer could be null, 1883 * meaning the code is not signed. <p> 1884 * 1885 * The Permission contains the (Type, Name, Action) triplet. <p> 1886 * 1887 * For now, the Policy object retrieves the public key from the 1888 * X.509 certificate on disk that corresponds to the signedBy 1889 * alias specified in the Policy config file. For reasons of 1890 * efficiency, the Policy object keeps a hashtable of certs already 1891 * read in. This could be replaced by a secure internal key 1892 * store. 1893 * 1894 * <p> 1895 * For example, the entry 1896 * <pre> 1897 * permission java.io.File "/tmp", "read,write", 1898 * signedBy "Duke"; 1899 * </pre> 1900 * is represented internally 1901 * <pre> 1902 * 1903 * FilePermission f = new FilePermission("/tmp", "read,write"); 1904 * PublicKey p = publickeys.get("Duke"); 1905 * URL u = InetAddress.getLocalHost(); 1906 * CodeBase c = new CodeBase( p, u ); 1907 * pe = new PolicyEntry(f, c); 1908 * </pre> 1909 * 1910 * @author Marianne Mueller 1911 * @author Roland Schemers 1912 * @see java.security.CodeSource 1913 * @see java.security.Policy 1914 * @see java.security.Permissions 1915 * @see java.security.ProtectionDomain 1916 */ 1917 private static class PolicyEntry { 1918 1919 private final CodeSource codesource; 1920 final List<Permission> permissions; 1921 private final List<PolicyParser.PrincipalEntry> principals; 1922 1923 /** 1924 * Given a Permission and a CodeSource, create a policy entry. 1925 * 1926 * XXX Decide if/how to add validity fields and "purpose" fields to 1927 * XXX policy entries 1928 * 1929 * @param cs the CodeSource, which encapsulates the URL and the 1930 * public key 1931 * attributes from the policy config file. Validity checks 1932 * are performed on the public key before PolicyEntry is 1933 * called. 1934 * 1935 */ 1936 PolicyEntry(CodeSource cs, List<PolicyParser.PrincipalEntry> principals) 1937 { 1938 this.codesource = cs; 1939 this.permissions = new ArrayList<Permission>(); 1940 this.principals = principals; // can be null 1941 } 1942 1943 PolicyEntry(CodeSource cs) 1944 { 1945 this(cs, null); 1946 } 1947 1948 List<PolicyParser.PrincipalEntry> getPrincipals() { 1949 return principals; // can be null 1950 } 1951 1952 /** 1953 * add a Permission object to this entry. 1954 * No need to sync add op because perms are added to entry only 1955 * while entry is being initialized 1956 */ 1957 void add(Permission p) { 1958 permissions.add(p); 1959 } 1960 1961 /** 1962 * Return the CodeSource for this policy entry 1963 */ 1964 CodeSource getCodeSource() { 1965 return codesource; 1966 } 1967 1968 @Override public String toString(){ 1969 StringBuilder sb = new StringBuilder(); 1970 sb.append(ResourcesMgr.getString("LPARAM")); 1971 sb.append(getCodeSource()); 1972 sb.append("\n"); 1973 for (int j = 0; j < permissions.size(); j++) { 1974 Permission p = permissions.get(j); 1975 sb.append(ResourcesMgr.getString("SPACE")); 1976 sb.append(ResourcesMgr.getString("SPACE")); 1977 sb.append(p); 1978 sb.append(ResourcesMgr.getString("NEWLINE")); 1979 } 1980 sb.append(ResourcesMgr.getString("RPARAM")); 1981 sb.append(ResourcesMgr.getString("NEWLINE")); 1982 return sb.toString(); 1983 } 1984 } 1985 1986 private static class SelfPermission extends Permission { 1987 1988 private static final long serialVersionUID = -8315562579967246806L; 1989 1990 /** 1991 * The class name of the Permission class that will be 1992 * created when this self permission is expanded . 1993 * 1994 * @serial 1995 */ 1996 private String type; 1997 1998 /** 1999 * The permission name. 2000 * 2001 * @serial 2002 */ 2003 private String name; 2004 2005 /** 2006 * The actions of the permission. 2007 * 2008 * @serial 2009 */ 2010 private String actions; 2011 2012 /** 2013 * The certs of the permission. 2014 * 2015 * @serial 2016 */ 2017 private Certificate[] certs; 2018 2019 /** 2020 * Creates a new SelfPermission containing the permission 2021 * information needed later to expand the self 2022 * @param type the class name of the Permission class that will be 2023 * created when this permission is expanded and if necessary resolved. 2024 * @param name the name of the permission. 2025 * @param actions the actions of the permission. 2026 * @param certs the certificates the permission's class was signed with. 2027 * This is a list of certificate chains, where each chain is composed of 2028 * a signer certificate and optionally its supporting certificate chain. 2029 * Each chain is ordered bottom-to-top (i.e., with the signer 2030 * certificate first and the (root) certificate authority last). 2031 */ 2032 public SelfPermission(String type, String name, String actions, 2033 Certificate[] certs) 2034 { 2035 super(type); 2036 if (type == null) { 2037 throw new NullPointerException 2038 (LocalizedMessage.getMessage("type.can.t.be.null")); 2039 } 2040 this.type = type; 2041 this.name = name; 2042 this.actions = actions; 2043 if (certs != null) { 2044 // Extract the signer certs from the list of certificates. 2045 for (int i=0; i<certs.length; i++) { 2046 if (!(certs[i] instanceof X509Certificate)) { 2047 // there is no concept of signer certs, so we store the 2048 // entire cert array 2049 this.certs = certs.clone(); 2050 break; 2051 } 2052 } 2053 2054 if (this.certs == null) { 2055 // Go through the list of certs and see if all the certs are 2056 // signer certs. 2057 int i = 0; 2058 int count = 0; 2059 while (i < certs.length) { 2060 count++; 2061 while (((i+1) < certs.length) && 2062 ((X509Certificate)certs[i]).getIssuerDN().equals( 2063 ((X509Certificate)certs[i+1]).getSubjectDN())) { 2064 i++; 2065 } 2066 i++; 2067 } 2068 if (count == certs.length) { 2069 // All the certs are signer certs, so we store the 2070 // entire array 2071 this.certs = certs.clone(); 2072 } 2073 2074 if (this.certs == null) { 2075 // extract the signer certs 2076 List<Certificate> signerCerts = new ArrayList<>(); 2077 i = 0; 2078 while (i < certs.length) { 2079 signerCerts.add(certs[i]); 2080 while (((i+1) < certs.length) && 2081 ((X509Certificate)certs[i]).getIssuerDN().equals( 2082 ((X509Certificate)certs[i+1]).getSubjectDN())) { 2083 i++; 2084 } 2085 i++; 2086 } 2087 this.certs = new Certificate[signerCerts.size()]; 2088 signerCerts.toArray(this.certs); 2089 } 2090 } 2091 } 2092 } 2093 2094 /** 2095 * This method always returns false for SelfPermission permissions. 2096 * That is, an SelfPermission never considered to 2097 * imply another permission. 2098 * 2099 * @param p the permission to check against. 2100 * 2101 * @return false. 2102 */ 2103 @Override public boolean implies(Permission p) { 2104 return false; 2105 } 2106 2107 /** 2108 * Checks two SelfPermission objects for equality. 2109 * 2110 * Checks that <i>obj</i> is an SelfPermission, and has 2111 * the same type (class) name, permission name, actions, and 2112 * certificates as this object. 2113 * 2114 * @param obj the object we are testing for equality with this object. 2115 * 2116 * @return true if obj is an SelfPermission, and has the same 2117 * type (class) name, permission name, actions, and 2118 * certificates as this object. 2119 */ 2120 @Override public boolean equals(Object obj) { 2121 if (obj == this) 2122 return true; 2123 2124 if (! (obj instanceof SelfPermission)) 2125 return false; 2126 SelfPermission that = (SelfPermission) obj; 2127 2128 if (!(this.type.equals(that.type) && 2129 this.name.equals(that.name) && 2130 this.actions.equals(that.actions))) 2131 return false; 2132 2133 if (this.certs.length != that.certs.length) 2134 return false; 2135 2136 int i,j; 2137 boolean match; 2138 2139 for (i = 0; i < this.certs.length; i++) { 2140 match = false; 2141 for (j = 0; j < that.certs.length; j++) { 2142 if (this.certs[i].equals(that.certs[j])) { 2143 match = true; 2144 break; 2145 } 2146 } 2147 if (!match) return false; 2148 } 2149 2150 for (i = 0; i < that.certs.length; i++) { 2151 match = false; 2152 for (j = 0; j < this.certs.length; j++) { 2153 if (that.certs[i].equals(this.certs[j])) { 2154 match = true; 2155 break; 2156 } 2157 } 2158 if (!match) return false; 2159 } 2160 return true; 2161 } 2162 2163 /** 2164 * Returns the hash code value for this object. 2165 * 2166 * @return a hash code value for this object. 2167 */ 2168 @Override public int hashCode() { 2169 int hash = type.hashCode(); 2170 if (name != null) 2171 hash ^= name.hashCode(); 2172 if (actions != null) 2173 hash ^= actions.hashCode(); 2174 return hash; 2175 } 2176 2177 /** 2178 * Returns the canonical string representation of the actions, 2179 * which currently is the empty string "", since there are no actions 2180 * for an SelfPermission. That is, the actions for the 2181 * permission that will be created when this SelfPermission 2182 * is resolved may be non-null, but an SelfPermission 2183 * itself is never considered to have any actions. 2184 * 2185 * @return the empty string "". 2186 */ 2187 @Override public String getActions() { 2188 return ""; 2189 } 2190 2191 public String getSelfType() { 2192 return type; 2193 } 2194 2195 public String getSelfName() { 2196 return name; 2197 } 2198 2199 public String getSelfActions() { 2200 return actions; 2201 } 2202 2203 public Certificate[] getCerts() { 2204 return certs; 2205 } 2206 2207 /** 2208 * Returns a string describing this SelfPermission. The convention 2209 * is to specify the class name, the permission name, and the actions, 2210 * in the following format: '(unresolved "ClassName" "name" "actions")'. 2211 * 2212 * @return information about this SelfPermission. 2213 */ 2214 @Override public String toString() { 2215 return "(SelfPermission " + type + " " + name + " " + actions + ")"; 2216 } 2217 } 2218 2219 /** 2220 * holds policy information that we need to synch on 2221 */ 2222 private static class PolicyInfo { 2223 private static final boolean verbose = false; 2224 2225 // Stores grant entries in the policy 2226 final List<PolicyEntry> policyEntries; 2227 2228 // Maps aliases to certs 2229 final Map<Object, Object> aliasMapping; 2230 2231 // Maps ProtectionDomain to PermissionCollection 2232 private final ProtectionDomainCache[] pdMapping; 2233 private java.util.Random random; 2234 2235 PolicyInfo(int numCaches) { 2236 policyEntries = new ArrayList<>(); 2237 aliasMapping = Collections.synchronizedMap(new HashMap<>(11)); 2238 2239 pdMapping = new ProtectionDomainCache[numCaches]; 2240 JavaSecurityProtectionDomainAccess jspda 2241 = SharedSecrets.getJavaSecurityProtectionDomainAccess(); 2242 for (int i = 0; i < numCaches; i++) { 2243 pdMapping[i] = jspda.getProtectionDomainCache(); 2244 } 2245 if (numCaches > 1) { 2246 random = new java.util.Random(); 2247 } 2248 } 2249 ProtectionDomainCache getPdMapping() { 2250 if (pdMapping.length == 1) { 2251 return pdMapping[0]; 2252 } else { 2253 int i = java.lang.Math.abs(random.nextInt() % pdMapping.length); 2254 return pdMapping[i]; 2255 } 2256 } 2257 } 2258} 2259