1 /* 2 * Copyright (c) 1997, 2018, 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 26 package java.io; 27 28 import java.nio.file.*; 29 import java.security.*; 30 import java.util.Enumeration; 31 import java.util.Objects; 32 import java.util.StringJoiner; 33 import java.util.Vector; 34 import java.util.concurrent.ConcurrentHashMap; 35 36 import jdk.internal.access.JavaIOFilePermissionAccess; 37 import jdk.internal.access.SharedSecrets; 38 import sun.nio.fs.DefaultFileSystemProvider; 39 import sun.security.action.GetPropertyAction; 40 import sun.security.util.FilePermCompat; 41 import sun.security.util.SecurityConstants; 42 43 /** 44 * This class represents access to a file or directory. A FilePermission consists 45 * of a pathname and a set of actions valid for that pathname. 46 * <P> 47 * Pathname is the pathname of the file or directory granted the specified 48 * actions. A pathname that ends in "/*" (where "/" is 49 * the file separator character, <code>File.separatorChar</code>) indicates 50 * all the files and directories contained in that directory. A pathname 51 * that ends with "/-" indicates (recursively) all files 52 * and subdirectories contained in that directory. Such a pathname is called 53 * a wildcard pathname. Otherwise, it's a simple pathname. 54 * <P> 55 * A pathname consisting of the special token {@literal "<<ALL FILES>>"} 56 * matches <b>any</b> file. 57 * <P> 58 * Note: A pathname consisting of a single "*" indicates all the files 59 * in the current directory, while a pathname consisting of a single "-" 60 * indicates all the files in the current directory and 61 * (recursively) all files and subdirectories contained in the current 62 * directory. 63 * <P> 64 * The actions to be granted are passed to the constructor in a string containing 65 * a list of one or more comma-separated keywords. The possible keywords are 66 * "read", "write", "execute", "delete", and "readlink". Their meaning is 67 * defined as follows: 68 * 69 * <DL> 70 * <DT> read <DD> read permission 71 * <DT> write <DD> write permission 72 * <DT> execute 73 * <DD> execute permission. Allows <code>Runtime.exec</code> to 74 * be called. Corresponds to <code>SecurityManager.checkExec</code>. 75 * <DT> delete 76 * <DD> delete permission. Allows <code>File.delete</code> to 77 * be called. Corresponds to <code>SecurityManager.checkDelete</code>. 78 * <DT> readlink 79 * <DD> read link permission. Allows the target of a 80 * <a href="../nio/file/package-summary.html#links">symbolic link</a> 81 * to be read by invoking the {@link java.nio.file.Files#readSymbolicLink 82 * readSymbolicLink } method. 83 * </DL> 84 * <P> 85 * The actions string is converted to lowercase before processing. 86 * <P> 87 * Be careful when granting FilePermissions. Think about the implications 88 * of granting read and especially write access to various files and 89 * directories. The {@literal "<<ALL FILES>>"} permission with write action is 90 * especially dangerous. This grants permission to write to the entire 91 * file system. One thing this effectively allows is replacement of the 92 * system binary, including the JVM runtime environment. 93 * <P> 94 * Please note: Code can always read a file from the same 95 * directory it's in (or a subdirectory of that directory); it does not 96 * need explicit permission to do so. 97 * 98 * @see java.security.Permission 99 * @see java.security.Permissions 100 * @see java.security.PermissionCollection 101 * 102 * 103 * @author Marianne Mueller 104 * @author Roland Schemers 105 * @since 1.2 106 * 107 * @serial exclude 108 */ 109 110 public final class FilePermission extends Permission implements Serializable { 111 112 /** 113 * Execute action. 114 */ 115 private static final int EXECUTE = 0x1; 116 /** 117 * Write action. 118 */ 119 private static final int WRITE = 0x2; 120 /** 121 * Read action. 122 */ 123 private static final int READ = 0x4; 124 /** 125 * Delete action. 126 */ 127 private static final int DELETE = 0x8; 128 /** 129 * Read link action. 130 */ 131 private static final int READLINK = 0x10; 132 133 /** 134 * All actions (read,write,execute,delete,readlink) 135 */ 136 private static final int ALL = READ|WRITE|EXECUTE|DELETE|READLINK; 137 /** 138 * No actions. 139 */ 140 private static final int NONE = 0x0; 141 142 // the actions mask 143 private transient int mask; 144 145 // does path indicate a directory? (wildcard or recursive) 146 private transient boolean directory; 147 148 // is it a recursive directory specification? 149 private transient boolean recursive; 150 151 /** 152 * the actions string. 153 * 154 * @serial 155 */ 156 private String actions; // Left null as long as possible, then 157 // created and re-used in the getAction function. 158 159 // canonicalized dir path. used by the "old" behavior (nb == false). 160 // In the case of directories, it is the name "/blah/*" or "/blah/-" 161 // without the last character (the "*" or "-"). 162 163 private transient String cpath; 164 165 // Following fields used by the "new" behavior (nb == true), in which 166 // input path is not canonicalized. For compatibility (so that granting 167 // FilePermission on "x" allows reading "`pwd`/x", an alternative path 168 // can be added so that both can be used in an implies() check. Please note 169 // the alternative path only deals with absolute/relative path, and does 170 // not deal with symlink/target. 171 172 private transient Path npath; // normalized dir path. 173 private transient Path npath2; // alternative normalized dir path. 174 private transient boolean allFiles; // whether this is <<ALL FILES>> 175 private transient boolean invalid; // whether input path is invalid 176 177 // static Strings used by init(int mask) 178 private static final char RECURSIVE_CHAR = '-'; 179 private static final char WILD_CHAR = '*'; 180 181 // public String toString() { 182 // StringBuffer sb = new StringBuffer(); 183 // sb.append("*** FilePermission on " + getName() + " ***"); 184 // for (Field f : FilePermission.class.getDeclaredFields()) { 185 // if (!Modifier.isStatic(f.getModifiers())) { 186 // try { 187 // sb.append(f.getName() + " = " + f.get(this)); 188 // } catch (Exception e) { 189 // sb.append(f.getName() + " = " + e.toString()); 190 // } 191 // sb.append('\n'); 192 // } 193 // } 194 // sb.append("***\n"); 195 // return sb.toString(); 196 // } 197 198 private static final long serialVersionUID = 7930732926638008763L; 199 200 /** 201 * Always use the builtin system-default file system, in case the 202 * java.nio.file.spi.DefaultFileSystemProvider system property is set. 203 */ 204 private static final java.nio.file.FileSystem builtInFS = 205 DefaultFileSystemProvider.theFileSystem(); 206 207 private static final Path here = builtInFS.getPath( 208 GetPropertyAction.privilegedGetProperty("user.dir")); 209 210 private static final Path EMPTY_PATH = builtInFS.getPath(""); 211 private static final Path DASH_PATH = builtInFS.getPath("-"); 212 private static final Path DOTDOT_PATH = builtInFS.getPath(".."); 213 214 /** 215 * A private constructor that clones some and updates some, 216 * always with a different name. 217 * @param input 218 */ 219 private FilePermission(String name, 220 FilePermission input, 221 Path npath, 222 Path npath2, 223 int mask, 224 String actions) { 225 super(name); 226 // Customizables 227 this.npath = npath; 228 this.npath2 = npath2; 229 this.actions = actions; 230 this.mask = mask; 231 // Cloneds 232 this.allFiles = input.allFiles; 233 this.invalid = input.invalid; 234 this.recursive = input.recursive; 235 this.directory = input.directory; 236 this.cpath = input.cpath; 237 } 238 239 /** 240 * Returns the alternative path as a Path object, i.e. absolute path 241 * for a relative one, or vice versa. 242 * 243 * @param in a real path w/o "-" or "*" at the end, and not <<ALL FILES>>. 244 * @return the alternative path, or null if cannot find one. 245 */ 246 private static Path altPath(Path in) { 247 try { 248 if (!in.isAbsolute()) { 249 return here.resolve(in).normalize(); 250 } else { 251 return here.relativize(in).normalize(); 252 } 253 } catch (IllegalArgumentException e) { 254 return null; 255 } 256 } 257 258 static { 259 SharedSecrets.setJavaIOFilePermissionAccess( 260 /** 261 * Creates FilePermission objects with special internals. 262 * See {@link FilePermCompat#newPermPlusAltPath(Permission)} and 263 * {@link FilePermCompat#newPermUsingAltPath(Permission)}. 264 */ 265 new JavaIOFilePermissionAccess() { 266 public FilePermission newPermPlusAltPath(FilePermission input) { 267 if (!input.invalid && input.npath2 == null && !input.allFiles) { 268 Path npath2 = altPath(input.npath); 269 if (npath2 != null) { 270 // Please note the name of the new permission is 271 // different than the original so that when one is 272 // added to a FilePermissionCollection it will not 273 // be merged with the original one. 274 return new FilePermission(input.getName() + "#plus", 275 input, 276 input.npath, 277 npath2, 278 input.mask, 279 input.actions); 280 } 281 } 282 return input; 283 } 284 public FilePermission newPermUsingAltPath(FilePermission input) { 285 if (!input.invalid && !input.allFiles) { 286 Path npath2 = altPath(input.npath); 287 if (npath2 != null) { 288 // New name, see above. 289 return new FilePermission(input.getName() + "#using", 290 input, 291 npath2, 292 null, 293 input.mask, 294 input.actions); 295 } 296 } 297 return null; 298 } 299 } 300 ); 301 } 302 303 /** 304 * initialize a FilePermission object. Common to all constructors. 305 * Also called during de-serialization. 306 * 307 * @param mask the actions mask to use. 308 * 309 */ 310 private void init(int mask) { 311 if ((mask & ALL) != mask) 312 throw new IllegalArgumentException("invalid actions mask"); 313 314 if (mask == NONE) 315 throw new IllegalArgumentException("invalid actions mask"); 316 317 if (FilePermCompat.nb) { 318 String name = getName(); 319 320 if (name == null) 321 throw new NullPointerException("name can't be null"); 322 323 this.mask = mask; 324 325 if (name.equals("<<ALL FILES>>")) { 326 allFiles = true; 327 npath = EMPTY_PATH; 328 // other fields remain default 329 return; 330 } 331 332 boolean rememberStar = false; 333 if (name.endsWith("*")) { 334 rememberStar = true; 335 recursive = false; 336 name = name.substring(0, name.length()-1) + "-"; 337 } 338 339 try { 340 // new File() can "normalize" some name, for example, "/C:/X" on 341 // Windows. Some JDK codes generate such illegal names. 342 npath = builtInFS.getPath(new File(name).getPath()) 343 .normalize(); 344 // lastName should always be non-null now 345 Path lastName = npath.getFileName(); 346 if (lastName != null && lastName.equals(DASH_PATH)) { 347 directory = true; 348 recursive = !rememberStar; 349 npath = npath.getParent(); 350 } 351 if (npath == null) { 352 npath = EMPTY_PATH; 353 } 354 invalid = false; 355 } catch (InvalidPathException ipe) { 356 // Still invalid. For compatibility reason, accept it 357 // but make this permission useless. 358 npath = builtInFS.getPath("-u-s-e-l-e-s-s-"); 359 invalid = true; 360 } 361 362 } else { 363 if ((cpath = getName()) == null) 364 throw new NullPointerException("name can't be null"); 365 366 this.mask = mask; 367 368 if (cpath.equals("<<ALL FILES>>")) { 369 directory = true; 370 recursive = true; 371 cpath = ""; 372 return; 373 } 374 375 // store only the canonical cpath if possible 376 cpath = AccessController.doPrivileged(new PrivilegedAction<>() { 377 public String run() { 378 try { 379 String path = cpath; 380 if (cpath.endsWith("*")) { 381 // call getCanonicalPath with a path with wildcard character 382 // replaced to avoid calling it with paths that are 383 // intended to match all entries in a directory 384 path = path.substring(0, path.length() - 1) + "-"; 385 path = new File(path).getCanonicalPath(); 386 return path.substring(0, path.length() - 1) + "*"; 387 } else { 388 return new File(path).getCanonicalPath(); 389 } 390 } catch (IOException ioe) { 391 return cpath; 392 } 393 } 394 }); 395 396 int len = cpath.length(); 397 char last = ((len > 0) ? cpath.charAt(len - 1) : 0); 398 399 if (last == RECURSIVE_CHAR && 400 cpath.charAt(len - 2) == File.separatorChar) { 401 directory = true; 402 recursive = true; 403 cpath = cpath.substring(0, --len); 404 } else if (last == WILD_CHAR && 405 cpath.charAt(len - 2) == File.separatorChar) { 406 directory = true; 407 //recursive = false; 408 cpath = cpath.substring(0, --len); 409 } else { 410 // overkill since they are initialized to false, but 411 // commented out here to remind us... 412 //directory = false; 413 //recursive = false; 414 } 415 416 // XXX: at this point the path should be absolute. die if it isn't? 417 } 418 } 419 420 /** 421 * Creates a new FilePermission object with the specified actions. 422 * <i>path</i> is the pathname of a file or directory, and <i>actions</i> 423 * contains a comma-separated list of the desired actions granted on the 424 * file or directory. Possible actions are 425 * "read", "write", "execute", "delete", and "readlink". 426 * 427 * <p>A pathname that ends in "/*" (where "/" is 428 * the file separator character, <code>File.separatorChar</code>) 429 * indicates all the files and directories contained in that directory. 430 * A pathname that ends with "/-" indicates (recursively) all files and 431 * subdirectories contained in that directory. The special pathname 432 * {@literal "<<ALL FILES>>"} matches any file. 433 * 434 * <p>A pathname consisting of a single "*" indicates all the files 435 * in the current directory, while a pathname consisting of a single "-" 436 * indicates all the files in the current directory and 437 * (recursively) all files and subdirectories contained in the current 438 * directory. 439 * 440 * <p>A pathname containing an empty string represents an empty path. 441 * 442 * @implNote In this implementation, the 443 * {@code jdk.io.permissionsUseCanonicalPath} system property dictates how 444 * the {@code path} argument is processed and stored. 445 * <P> 446 * If the value of the system property is set to {@code true}, {@code path} 447 * is canonicalized and stored as a String object named {@code cpath}. 448 * This means a relative path is converted to an absolute path, a Windows 449 * DOS-style 8.3 path is expanded to a long path, and a symbolic link is 450 * resolved to its target, etc. 451 * <P> 452 * If the value of the system property is set to {@code false}, {@code path} 453 * is converted to a {@link java.nio.file.Path} object named {@code npath} 454 * after {@link Path#normalize() normalization}. No canonicalization is 455 * performed which means the underlying file system is not accessed. 456 * If an {@link InvalidPathException} is thrown during the conversion, 457 * this {@code FilePermission} will be labeled as invalid. 458 * <P> 459 * In either case, the "*" or "-" character at the end of a wildcard 460 * {@code path} is removed before canonicalization or normalization. 461 * It is stored in a separate wildcard flag field. 462 * <P> 463 * The default value of the {@code jdk.io.permissionsUseCanonicalPath} 464 * system property is {@code false} in this implementation. 465 * 466 * @param path the pathname of the file/directory. 467 * @param actions the action string. 468 * 469 * @throws IllegalArgumentException 470 * If actions is <code>null</code>, empty or contains an action 471 * other than the specified possible actions. 472 */ 473 public FilePermission(String path, String actions) { 474 super(path); 475 init(getMask(actions)); 476 } 477 478 /** 479 * Creates a new FilePermission object using an action mask. 480 * More efficient than the FilePermission(String, String) constructor. 481 * Can be used from within 482 * code that needs to create a FilePermission object to pass into the 483 * <code>implies</code> method. 484 * 485 * @param path the pathname of the file/directory. 486 * @param mask the action mask to use. 487 */ 488 // package private for use by the FilePermissionCollection add method 489 FilePermission(String path, int mask) { 490 super(path); 491 init(mask); 492 } 493 494 /** 495 * Checks if this FilePermission object "implies" the specified permission. 496 * <P> 497 * More specifically, this method returns true if: 498 * <ul> 499 * <li> <i>p</i> is an instanceof FilePermission, 500 * <li> <i>p</i>'s actions are a proper subset of this 501 * object's actions, and 502 * <li> <i>p</i>'s pathname is implied by this object's 503 * pathname. For example, "/tmp/*" implies "/tmp/foo", since 504 * "/tmp/*" encompasses all files in the "/tmp" directory, 505 * including the one named "foo". 506 * </ul> 507 * <P> 508 * Precisely, a simple pathname implies another simple pathname 509 * if and only if they are equal. A simple pathname never implies 510 * a wildcard pathname. A wildcard pathname implies another wildcard 511 * pathname if and only if all simple pathnames implied by the latter 512 * are implied by the former. A wildcard pathname implies a simple 513 * pathname if and only if 514 * <ul> 515 * <li>if the wildcard flag is "*", the simple pathname's path 516 * must be right inside the wildcard pathname's path. 517 * <li>if the wildcard flag is "-", the simple pathname's path 518 * must be recursively inside the wildcard pathname's path. 519 * </ul> 520 * <P> 521 * {@literal "<<ALL FILES>>"} implies every other pathname. No pathname, 522 * except for {@literal "<<ALL FILES>>"} itself, implies 523 * {@literal "<<ALL FILES>>"}. 524 * 525 * @implNote 526 * If {@code jdk.io.permissionsUseCanonicalPath} is {@code true}, a 527 * simple {@code cpath} is inside a wildcard {@code cpath} if and only if 528 * after removing the base name (the last name in the pathname's name 529 * sequence) from the former the remaining part equals to the latter, 530 * a simple {@code cpath} is recursively inside a wildcard {@code cpath} 531 * if and only if the former starts with the latter. 532 * <p> 533 * If {@code jdk.io.permissionsUseCanonicalPath} is {@code false}, a 534 * simple {@code npath} is inside a wildcard {@code npath} if and only if 535 * {@code simple_npath.relativize(wildcard_npath)} is exactly "..", 536 * a simple {@code npath} is recursively inside a wildcard {@code npath} 537 * if and only if {@code simple_npath.relativize(wildcard_npath)} is a 538 * series of one or more "..". This means "/-" implies "/foo" but not "foo". 539 * <p> 540 * An invalid {@code FilePermission} does not imply any object except for 541 * itself. An invalid {@code FilePermission} is not implied by any object 542 * except for itself or a {@code FilePermission} on 543 * {@literal "<<ALL FILES>>"} whose actions is a superset of this 544 * invalid {@code FilePermission}. Even if two {@code FilePermission} 545 * are created with the same invalid path, one does not imply the other. 546 * 547 * @param p the permission to check against. 548 * 549 * @return <code>true</code> if the specified permission is not 550 * <code>null</code> and is implied by this object, 551 * <code>false</code> otherwise. 552 */ 553 @Override 554 public boolean implies(Permission p) { 555 if (!(p instanceof FilePermission)) 556 return false; 557 558 FilePermission that = (FilePermission) p; 559 560 // we get the effective mask. i.e., the "and" of this and that. 561 // They must be equal to that.mask for implies to return true. 562 563 return ((this.mask & that.mask) == that.mask) && impliesIgnoreMask(that); 564 } 565 566 /** 567 * Checks if the Permission's actions are a proper subset of the 568 * this object's actions. Returns the effective mask iff the 569 * this FilePermission's path also implies that FilePermission's path. 570 * 571 * @param that the FilePermission to check against. 572 * @return the effective mask 573 */ 574 boolean impliesIgnoreMask(FilePermission that) { 575 if (FilePermCompat.nb) { 576 if (this == that) { 577 return true; 578 } 579 if (allFiles) { 580 return true; 581 } 582 if (this.invalid || that.invalid) { 583 return false; 584 } 585 if (that.allFiles) { 586 return false; 587 } 588 // Left at least same level of wildness as right 589 if ((this.recursive && that.recursive) != that.recursive 590 || (this.directory && that.directory) != that.directory) { 591 return false; 592 } 593 // Same npath is good as long as both or neither are directories 594 if (this.npath.equals(that.npath) 595 && this.directory == that.directory) { 596 return true; 597 } 598 int diff = containsPath(this.npath, that.npath); 599 // Right inside left is good if recursive 600 if (diff >= 1 && recursive) { 601 return true; 602 } 603 // Right right inside left if it is element in set 604 if (diff == 1 && directory && !that.directory) { 605 return true; 606 } 607 608 // Hack: if a npath2 field exists, apply the same checks 609 // on it as a fallback. 610 if (this.npath2 != null) { 611 if (this.npath2.equals(that.npath) 612 && this.directory == that.directory) { 613 return true; 614 } 615 diff = containsPath(this.npath2, that.npath); 616 if (diff >= 1 && recursive) { 617 return true; 618 } 619 if (diff == 1 && directory && !that.directory) { 620 return true; 621 } 622 } 623 624 return false; 625 } else { 626 if (this.directory) { 627 if (this.recursive) { 628 // make sure that.path is longer then path so 629 // something like /foo/- does not imply /foo 630 if (that.directory) { 631 return (that.cpath.length() >= this.cpath.length()) && 632 that.cpath.startsWith(this.cpath); 633 } else { 634 return ((that.cpath.length() > this.cpath.length()) && 635 that.cpath.startsWith(this.cpath)); 636 } 637 } else { 638 if (that.directory) { 639 // if the permission passed in is a directory 640 // specification, make sure that a non-recursive 641 // permission (i.e., this object) can't imply a recursive 642 // permission. 643 if (that.recursive) 644 return false; 645 else 646 return (this.cpath.equals(that.cpath)); 647 } else { 648 int last = that.cpath.lastIndexOf(File.separatorChar); 649 if (last == -1) 650 return false; 651 else { 652 // this.cpath.equals(that.cpath.substring(0, last+1)); 653 // Use regionMatches to avoid creating new string 654 return (this.cpath.length() == (last + 1)) && 655 this.cpath.regionMatches(0, that.cpath, 0, last + 1); 656 } 657 } 658 } 659 } else if (that.directory) { 660 // if this is NOT recursive/wildcarded, 661 // do not let it imply a recursive/wildcarded permission 662 return false; 663 } else { 664 return (this.cpath.equals(that.cpath)); 665 } 666 } 667 } 668 669 /** 670 * Returns the depth between an outer path p1 and an inner path p2. -1 671 * is returned if 672 * 673 * - p1 does not contains p2. 674 * - this is not decidable. For example, p1="../x", p2="y". 675 * - the depth is not decidable. For example, p1="/", p2="x". 676 * 677 * This method can return 2 if the depth is greater than 2. 678 * 679 * @param p1 the expected outer path, normalized 680 * @param p2 the expected inner path, normalized 681 * @return the depth in between 682 */ 683 private static int containsPath(Path p1, Path p2) { 684 685 // Two paths must have the same root. For example, 686 // there is no contains relation between any two of 687 // "/x", "x", "C:/x", "C:x", and "//host/share/x". 688 if (!Objects.equals(p1.getRoot(), p2.getRoot())) { 689 return -1; 690 } 691 692 // Empty path (i.e. "." or "") is a strange beast, 693 // because its getNameCount()==1 but getName(0) is null. 694 // It's better to deal with it separately. 695 if (p1.equals(EMPTY_PATH)) { 696 if (p2.equals(EMPTY_PATH)) { 697 return 0; 698 } else if (p2.getName(0).equals(DOTDOT_PATH)) { 699 // "." contains p2 iff p2 has no "..". Since 700 // a normalized path can only have 0 or more 701 // ".." at the beginning. We only need to look 702 // at the head. 703 return -1; 704 } else { 705 // and the distance is p2's name count. i.e. 706 // 3 between "." and "a/b/c". 707 return p2.getNameCount(); 708 } 709 } else if (p2.equals(EMPTY_PATH)) { 710 int c1 = p1.getNameCount(); 711 if (!p1.getName(c1 - 1).equals(DOTDOT_PATH)) { 712 // "." is inside p1 iff p1 is 1 or more "..". 713 // For the same reason above, we only need to 714 // look at the tail. 715 return -1; 716 } 717 // and the distance is the count of ".." 718 return c1; 719 } 720 721 // Good. No more empty paths. 722 723 // Common heads are removed 724 725 int c1 = p1.getNameCount(); 726 int c2 = p2.getNameCount(); 727 728 int n = Math.min(c1, c2); 729 int i = 0; 730 while (i < n) { 731 if (!p1.getName(i).equals(p2.getName(i))) 732 break; 733 i++; 734 } 735 736 // for p1 containing p2, p1 must be 0-or-more "..", 737 // and p2 cannot have "..". For the same reason, we only 738 // check tail of p1 and head of p2. 739 if (i < c1 && !p1.getName(c1 - 1).equals(DOTDOT_PATH)) { 740 return -1; 741 } 742 743 if (i < c2 && p2.getName(i).equals(DOTDOT_PATH)) { 744 return -1; 745 } 746 747 // and the distance is the name counts added (after removing 748 // the common heads). 749 750 // For example: p1 = "../../..", p2 = "../a". 751 // After removing the common heads, they become "../.." and "a", 752 // and the distance is (3-1)+(2-1) = 3. 753 return c1 - i + c2 - i; 754 } 755 756 /** 757 * Checks two FilePermission objects for equality. Checks that <i>obj</i> is 758 * a FilePermission, and has the same pathname and actions as this object. 759 * 760 * @implNote More specifically, two pathnames are the same if and only if 761 * they have the same wildcard flag and their {@code cpath} 762 * (if {@code jdk.io.permissionsUseCanonicalPath} is {@code true}) or 763 * {@code npath} (if {@code jdk.io.permissionsUseCanonicalPath} 764 * is {@code false}) are equal. Or they are both {@literal "<<ALL FILES>>"}. 765 * <p> 766 * When {@code jdk.io.permissionsUseCanonicalPath} is {@code false}, an 767 * invalid {@code FilePermission} does not equal to any object except 768 * for itself, even if they are created using the same invalid path. 769 * 770 * @param obj the object we are testing for equality with this object. 771 * @return <code>true</code> if obj is a FilePermission, and has the same 772 * pathname and actions as this FilePermission object, 773 * <code>false</code> otherwise. 774 */ 775 @Override 776 public boolean equals(Object obj) { 777 if (obj == this) 778 return true; 779 780 if (! (obj instanceof FilePermission)) 781 return false; 782 783 FilePermission that = (FilePermission) obj; 784 785 if (FilePermCompat.nb) { 786 if (this.invalid || that.invalid) { 787 return false; 788 } 789 return (this.mask == that.mask) && 790 (this.allFiles == that.allFiles) && 791 this.npath.equals(that.npath) && 792 Objects.equals(npath2, that.npath2) && 793 (this.directory == that.directory) && 794 (this.recursive == that.recursive); 795 } else { 796 return (this.mask == that.mask) && 797 this.cpath.equals(that.cpath) && 798 (this.directory == that.directory) && 799 (this.recursive == that.recursive); 800 } 801 } 802 803 /** 804 * Returns the hash code value for this object. 805 * 806 * @return a hash code value for this object. 807 */ 808 @Override 809 public int hashCode() { 810 if (FilePermCompat.nb) { 811 return Objects.hash( 812 mask, allFiles, directory, recursive, npath, npath2, invalid); 813 } else { 814 return 0; 815 } 816 } 817 818 /** 819 * Converts an actions String to an actions mask. 820 * 821 * @param actions the action string. 822 * @return the actions mask. 823 */ 824 private static int getMask(String actions) { 825 int mask = NONE; 826 827 // Null action valid? 828 if (actions == null) { 829 return mask; 830 } 831 832 // Use object identity comparison against known-interned strings for 833 // performance benefit (these values are used heavily within the JDK). 834 if (actions == SecurityConstants.FILE_READ_ACTION) { 835 return READ; 836 } else if (actions == SecurityConstants.FILE_WRITE_ACTION) { 837 return WRITE; 838 } else if (actions == SecurityConstants.FILE_EXECUTE_ACTION) { 839 return EXECUTE; 840 } else if (actions == SecurityConstants.FILE_DELETE_ACTION) { 841 return DELETE; 842 } else if (actions == SecurityConstants.FILE_READLINK_ACTION) { 843 return READLINK; 844 } 845 846 char[] a = actions.toCharArray(); 847 848 int i = a.length - 1; 849 if (i < 0) 850 return mask; 851 852 while (i != -1) { 853 char c; 854 855 // skip whitespace 856 while ((i!=-1) && ((c = a[i]) == ' ' || 857 c == '\r' || 858 c == '\n' || 859 c == '\f' || 860 c == '\t')) 861 i--; 862 863 // check for the known strings 864 int matchlen; 865 866 if (i >= 3 && (a[i-3] == 'r' || a[i-3] == 'R') && 867 (a[i-2] == 'e' || a[i-2] == 'E') && 868 (a[i-1] == 'a' || a[i-1] == 'A') && 869 (a[i] == 'd' || a[i] == 'D')) 870 { 871 matchlen = 4; 872 mask |= READ; 873 874 } else if (i >= 4 && (a[i-4] == 'w' || a[i-4] == 'W') && 875 (a[i-3] == 'r' || a[i-3] == 'R') && 876 (a[i-2] == 'i' || a[i-2] == 'I') && 877 (a[i-1] == 't' || a[i-1] == 'T') && 878 (a[i] == 'e' || a[i] == 'E')) 879 { 880 matchlen = 5; 881 mask |= WRITE; 882 883 } else if (i >= 6 && (a[i-6] == 'e' || a[i-6] == 'E') && 884 (a[i-5] == 'x' || a[i-5] == 'X') && 885 (a[i-4] == 'e' || a[i-4] == 'E') && 886 (a[i-3] == 'c' || a[i-3] == 'C') && 887 (a[i-2] == 'u' || a[i-2] == 'U') && 888 (a[i-1] == 't' || a[i-1] == 'T') && 889 (a[i] == 'e' || a[i] == 'E')) 890 { 891 matchlen = 7; 892 mask |= EXECUTE; 893 894 } else if (i >= 5 && (a[i-5] == 'd' || a[i-5] == 'D') && 895 (a[i-4] == 'e' || a[i-4] == 'E') && 896 (a[i-3] == 'l' || a[i-3] == 'L') && 897 (a[i-2] == 'e' || a[i-2] == 'E') && 898 (a[i-1] == 't' || a[i-1] == 'T') && 899 (a[i] == 'e' || a[i] == 'E')) 900 { 901 matchlen = 6; 902 mask |= DELETE; 903 904 } else if (i >= 7 && (a[i-7] == 'r' || a[i-7] == 'R') && 905 (a[i-6] == 'e' || a[i-6] == 'E') && 906 (a[i-5] == 'a' || a[i-5] == 'A') && 907 (a[i-4] == 'd' || a[i-4] == 'D') && 908 (a[i-3] == 'l' || a[i-3] == 'L') && 909 (a[i-2] == 'i' || a[i-2] == 'I') && 910 (a[i-1] == 'n' || a[i-1] == 'N') && 911 (a[i] == 'k' || a[i] == 'K')) 912 { 913 matchlen = 8; 914 mask |= READLINK; 915 916 } else { 917 // parse error 918 throw new IllegalArgumentException( 919 "invalid permission: " + actions); 920 } 921 922 // make sure we didn't just match the tail of a word 923 // like "ackbarfaccept". Also, skip to the comma. 924 boolean seencomma = false; 925 while (i >= matchlen && !seencomma) { 926 switch(a[i-matchlen]) { 927 case ',': 928 seencomma = true; 929 break; 930 case ' ': case '\r': case '\n': 931 case '\f': case '\t': 932 break; 933 default: 934 throw new IllegalArgumentException( 935 "invalid permission: " + actions); 936 } 937 i--; 938 } 939 940 // point i at the location of the comma minus one (or -1). 941 i -= matchlen; 942 } 943 944 return mask; 945 } 946 947 /** 948 * Return the current action mask. Used by the FilePermissionCollection. 949 * 950 * @return the actions mask. 951 */ 952 int getMask() { 953 return mask; 954 } 955 956 /** 957 * Return the canonical string representation of the actions. 958 * Always returns present actions in the following order: 959 * read, write, execute, delete, readlink. 960 * 961 * @return the canonical string representation of the actions. 962 */ 963 private static String getActions(int mask) { 964 StringJoiner sj = new StringJoiner(","); 965 966 if ((mask & READ) == READ) { 967 sj.add("read"); 968 } 969 if ((mask & WRITE) == WRITE) { 970 sj.add("write"); 971 } 972 if ((mask & EXECUTE) == EXECUTE) { 973 sj.add("execute"); 974 } 975 if ((mask & DELETE) == DELETE) { 976 sj.add("delete"); 977 } 978 if ((mask & READLINK) == READLINK) { 979 sj.add("readlink"); 980 } 981 982 return sj.toString(); 983 } 984 985 /** 986 * Returns the "canonical string representation" of the actions. 987 * That is, this method always returns present actions in the following order: 988 * read, write, execute, delete, readlink. For example, if this FilePermission 989 * object allows both write and read actions, a call to <code>getActions</code> 990 * will return the string "read,write". 991 * 992 * @return the canonical string representation of the actions. 993 */ 994 @Override 995 public String getActions() { 996 if (actions == null) 997 actions = getActions(this.mask); 998 999 return actions; 1000 } 1001 1002 /** 1003 * Returns a new PermissionCollection object for storing FilePermission 1004 * objects. 1005 * <p> 1006 * FilePermission objects must be stored in a manner that allows them 1007 * to be inserted into the collection in any order, but that also enables the 1008 * PermissionCollection <code>implies</code> 1009 * method to be implemented in an efficient (and consistent) manner. 1010 * 1011 * <p>For example, if you have two FilePermissions: 1012 * <OL> 1013 * <LI> <code>"/tmp/-", "read"</code> 1014 * <LI> <code>"/tmp/scratch/foo", "write"</code> 1015 * </OL> 1016 * 1017 * <p>and you are calling the <code>implies</code> method with the FilePermission: 1018 * 1019 * <pre> 1020 * "/tmp/scratch/foo", "read,write", 1021 * </pre> 1022 * 1023 * then the <code>implies</code> function must 1024 * take into account both the "/tmp/-" and "/tmp/scratch/foo" 1025 * permissions, so the effective permission is "read,write", 1026 * and <code>implies</code> returns true. The "implies" semantics for 1027 * FilePermissions are handled properly by the PermissionCollection object 1028 * returned by this <code>newPermissionCollection</code> method. 1029 * 1030 * @return a new PermissionCollection object suitable for storing 1031 * FilePermissions. 1032 */ 1033 @Override 1034 public PermissionCollection newPermissionCollection() { 1035 return new FilePermissionCollection(); 1036 } 1037 1038 /** 1039 * WriteObject is called to save the state of the FilePermission 1040 * to a stream. The actions are serialized, and the superclass 1041 * takes care of the name. 1042 */ 1043 private void writeObject(ObjectOutputStream s) 1044 throws IOException 1045 { 1046 // Write out the actions. The superclass takes care of the name 1047 // call getActions to make sure actions field is initialized 1048 if (actions == null) 1049 getActions(); 1050 s.defaultWriteObject(); 1051 } 1052 1053 /** 1054 * readObject is called to restore the state of the FilePermission from 1055 * a stream. 1056 */ 1057 private void readObject(ObjectInputStream s) 1058 throws IOException, ClassNotFoundException 1059 { 1060 // Read in the actions, then restore everything else by calling init. 1061 s.defaultReadObject(); 1062 init(getMask(actions)); 1063 } 1064 1065 /** 1066 * Create a cloned FilePermission with a different actions. 1067 * @param effective the new actions 1068 * @return a new object 1069 */ 1070 FilePermission withNewActions(int effective) { 1071 return new FilePermission(this.getName(), 1072 this, 1073 this.npath, 1074 this.npath2, 1075 effective, 1076 null); 1077 } 1078 } 1079 1080 /** 1081 * A FilePermissionCollection stores a set of FilePermission permissions. 1082 * FilePermission objects 1083 * must be stored in a manner that allows them to be inserted in any 1084 * order, but enable the implies function to evaluate the implies 1085 * method. 1086 * For example, if you have two FilePermissions: 1087 * <OL> 1088 * <LI> "/tmp/-", "read" 1089 * <LI> "/tmp/scratch/foo", "write" 1090 * </OL> 1091 * And you are calling the implies function with the FilePermission: 1092 * "/tmp/scratch/foo", "read,write", then the implies function must 1093 * take into account both the /tmp/- and /tmp/scratch/foo 1094 * permissions, so the effective permission is "read,write". 1095 * 1096 * @see java.security.Permission 1097 * @see java.security.Permissions 1098 * @see java.security.PermissionCollection 1099 * 1100 * 1101 * @author Marianne Mueller 1102 * @author Roland Schemers 1103 * 1104 * @serial include 1105 * 1106 */ 1107 1108 final class FilePermissionCollection extends PermissionCollection 1109 implements Serializable 1110 { 1111 // Not serialized; see serialization section at end of class 1112 private transient ConcurrentHashMap<String, Permission> perms; 1113 1114 /** 1115 * Create an empty FilePermissionCollection object. 1116 */ 1117 public FilePermissionCollection() { 1118 perms = new ConcurrentHashMap<>(); 1119 } 1120 1121 /** 1122 * Adds a permission to the FilePermissionCollection. The key for the hash is 1123 * permission.path. 1124 * 1125 * @param permission the Permission object to add. 1126 * 1127 * @exception IllegalArgumentException - if the permission is not a 1128 * FilePermission 1129 * 1130 * @exception SecurityException - if this FilePermissionCollection object 1131 * has been marked readonly 1132 */ 1133 @Override 1134 public void add(Permission permission) { 1135 if (! (permission instanceof FilePermission)) 1136 throw new IllegalArgumentException("invalid permission: "+ 1137 permission); 1138 if (isReadOnly()) 1139 throw new SecurityException( 1140 "attempt to add a Permission to a readonly PermissionCollection"); 1141 1142 FilePermission fp = (FilePermission)permission; 1143 1144 // Add permission to map if it is absent, or replace with new 1145 // permission if applicable. 1146 perms.merge(fp.getName(), fp, 1147 new java.util.function.BiFunction<>() { 1148 @Override 1149 public Permission apply(Permission existingVal, 1150 Permission newVal) { 1151 int oldMask = ((FilePermission)existingVal).getMask(); 1152 int newMask = ((FilePermission)newVal).getMask(); 1153 if (oldMask != newMask) { 1154 int effective = oldMask | newMask; 1155 if (effective == newMask) { 1156 return newVal; 1157 } 1158 if (effective != oldMask) { 1159 return ((FilePermission)newVal) 1160 .withNewActions(effective); 1161 } 1162 } 1163 return existingVal; 1164 } 1165 } 1166 ); 1167 } 1168 1169 /** 1170 * Check and see if this set of permissions implies the permissions 1171 * expressed in "permission". 1172 * 1173 * @param permission the Permission object to compare 1174 * 1175 * @return true if "permission" is a proper subset of a permission in 1176 * the set, false if not. 1177 */ 1178 @Override 1179 public boolean implies(Permission permission) { 1180 if (! (permission instanceof FilePermission)) 1181 return false; 1182 1183 FilePermission fperm = (FilePermission) permission; 1184 1185 int desired = fperm.getMask(); 1186 int effective = 0; 1187 int needed = desired; 1188 1189 for (Permission perm : perms.values()) { 1190 FilePermission fp = (FilePermission)perm; 1191 if (((needed & fp.getMask()) != 0) && fp.impliesIgnoreMask(fperm)) { 1192 effective |= fp.getMask(); 1193 if ((effective & desired) == desired) { 1194 return true; 1195 } 1196 needed = (desired ^ effective); 1197 } 1198 } 1199 return false; 1200 } 1201 1202 /** 1203 * Returns an enumeration of all the FilePermission objects in the 1204 * container. 1205 * 1206 * @return an enumeration of all the FilePermission objects. 1207 */ 1208 @Override 1209 public Enumeration<Permission> elements() { 1210 return perms.elements(); 1211 } 1212 1213 private static final long serialVersionUID = 2202956749081564585L; 1214 1215 // Need to maintain serialization interoperability with earlier releases, 1216 // which had the serializable field: 1217 // private Vector permissions; 1218 1219 /** 1220 * @serialField permissions java.util.Vector 1221 * A list of FilePermission objects. 1222 */ 1223 private static final ObjectStreamField[] serialPersistentFields = { 1224 new ObjectStreamField("permissions", Vector.class), 1225 }; 1226 1227 /** 1228 * @serialData "permissions" field (a Vector containing the FilePermissions). 1229 */ 1230 /* 1231 * Writes the contents of the perms field out as a Vector for 1232 * serialization compatibility with earlier releases. 1233 */ 1234 private void writeObject(ObjectOutputStream out) throws IOException { 1235 // Don't call out.defaultWriteObject() 1236 1237 // Write out Vector 1238 Vector<Permission> permissions = new Vector<>(perms.values()); 1239 1240 ObjectOutputStream.PutField pfields = out.putFields(); 1241 pfields.put("permissions", permissions); 1242 out.writeFields(); 1243 } 1244 1245 /* 1246 * Reads in a Vector of FilePermissions and saves them in the perms field. 1247 */ 1248 private void readObject(ObjectInputStream in) 1249 throws IOException, ClassNotFoundException 1250 { 1251 // Don't call defaultReadObject() 1252 1253 // Read in serialized fields 1254 ObjectInputStream.GetField gfields = in.readFields(); 1255 1256 // Get the one we want 1257 @SuppressWarnings("unchecked") 1258 Vector<Permission> permissions = (Vector<Permission>)gfields.get("permissions", null); 1259 perms = new ConcurrentHashMap<>(permissions.size()); 1260 for (Permission perm : permissions) { 1261 perms.put(perm.getName(), perm); 1262 } 1263 } 1264 }