Java 类java.io.FilePermission 实例源码

项目:openjdk-jdk10    文件:FilePermissionTest.java   
private static void check(List<String> files, String expected) {

        StringBuilder actual = new StringBuilder();
        files.forEach(f -> {
            StringBuilder result = new StringBuilder();
            FilePermission fp1 = new FilePermission(f, "read");
            FilePermission fp2 = new FilePermission(
                    new File(f).getAbsolutePath(), "read");
            result.append(fp1.equals(fp2));
            result.append(fp1.implies(fp2));
            result.append(fp1.hashCode() == fp2.hashCode());
            System.out.println(fp1 + " Vs. " + fp2 + " : Result: " + result);
            actual.append(result);
        });
        if (!expected.equals(actual.toString())) {
            throw new RuntimeException("Failed: " + expected + "/" + actual);
        }
    }
项目:elasticsearch_my    文件:EvilSecurityTests.java   
/**
 * checks exact file permissions, meaning those and only those for that path.
 */
static void assertExactPermissions(FilePermission expected, PermissionCollection actual) {
    String target = expected.getName(); // see javadocs
    Set<String> permissionSet = asSet(expected.getActions().split(","));
    boolean read = permissionSet.remove("read");
    boolean readlink = permissionSet.remove("readlink");
    boolean write = permissionSet.remove("write");
    boolean delete = permissionSet.remove("delete");
    boolean execute = permissionSet.remove("execute");
    assertTrue("unrecognized permission: " + permissionSet, permissionSet.isEmpty());
    assertEquals(read, actual.implies(new FilePermission(target, "read")));
    assertEquals(readlink, actual.implies(new FilePermission(target, "readlink")));
    assertEquals(write, actual.implies(new FilePermission(target, "write")));
    assertEquals(delete, actual.implies(new FilePermission(target, "delete")));
    assertEquals(execute, actual.implies(new FilePermission(target, "execute")));
}
项目:elasticsearch_my    文件:Security.java   
/** Adds access to classpath jars/classes for jar hell scan, etc */
@SuppressForbidden(reason = "accesses fully qualified URLs to configure security")
static void addClasspathPermissions(Permissions policy) throws IOException {
    // add permissions to everything in classpath
    // really it should be covered by lib/, but there could be e.g. agents or similar configured)
    for (URL url : JarHell.parseClassPath()) {
        Path path;
        try {
            path = PathUtils.get(url.toURI());
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
        // resource itself
        policy.add(new FilePermission(path.toString(), "read,readlink"));
        // classes underneath
        if (Files.isDirectory(path)) {
            policy.add(new FilePermission(path.toString() + path.getFileSystem().getSeparator() + "-", "read,readlink"));
        }
    }
}
项目:gemini.blueprint    文件:BaseIntegrationTest.java   
/**
 * Returns the list of permissions for the running test.
 * 
 * @return
 */
protected List<Permission> getTestPermissions() {
    List<Permission> perms = new ArrayList<Permission>();
    perms.add(new PackagePermission("*", PackagePermission.EXPORT));
    perms.add(new PackagePermission("*", PackagePermission.IMPORT));
    perms.add(new BundlePermission("*", BundlePermission.HOST));
    perms.add(new BundlePermission("*", BundlePermission.PROVIDE));
    perms.add(new BundlePermission("*", BundlePermission.REQUIRE));
    perms.add(new ServicePermission("*", ServicePermission.REGISTER));
    perms.add(new ServicePermission("*", ServicePermission.GET));
    perms.add(new PropertyPermission("*", "read,write"));
    // required by Spring
    perms.add(new RuntimePermission("*", "accessDeclaredMembers"));
    perms.add(new ReflectPermission("*", "suppressAccessChecks"));
    // logging permission
    perms.add(new FilePermission("-", "write"));
    perms.add(new FilePermission("-", "read"));
    return perms;
}
项目:gemini.blueprint    文件:BaseIntegrationTest.java   
protected List<Permission> getIAndTPermissions() {
    List<Permission> perms = new ArrayList<Permission>();
    // export package
    perms.add(new PackagePermission("*", PackagePermission.EXPORT));
    perms.add(new PackagePermission("*", PackagePermission.IMPORT));
    perms.add(new BundlePermission("*", BundlePermission.FRAGMENT));
    perms.add(new BundlePermission("*", BundlePermission.PROVIDE));
    perms.add(new ServicePermission("*", ServicePermission.REGISTER));
    perms.add(new ServicePermission("*", ServicePermission.GET));
    perms.add(new PropertyPermission("*", "read,write"));

    // required by Spring
    perms.add(new RuntimePermission("*", "accessDeclaredMembers"));
    perms.add(new ReflectPermission("*", "suppressAccessChecks"));

    // logging permission
    perms.add(new FilePermission("-", "write"));
    perms.add(new FilePermission("-", "read"));

    return perms;
}
项目:openjdk-jdk10    文件:SimpleUpdateConfigurationTest.java   
public SimplePolicy(TestCase test) {
    basic = new Permissions();
    control = new Permissions();
    control.add(new LoggingPermission("control", null));

    // These permissions are required to call updateConfiguration(Function)
    control.add(new PropertyPermission("java.util.logging.config.file", "read"));
    control.add(new PropertyPermission("java.home", "read"));
    control.add(new FilePermission(
            Paths.get(System.getProperty("user.dir", "."),"-").toString(), "read"));
    control.add(new FilePermission(
            Paths.get(System.getProperty("java.home"),"conf","-").toString(), "read"));

    // these are used for configuring the test itself...
    all = new Permissions();
    all.add(new java.security.AllPermission());

}
项目:openjdk-jdk10    文件:MergeName.java   
public static void main(String[] args) throws Exception {
    if (args.length == 0) {
        test("p1", "read", "write", "delete", "execute");
        test("p2", "read,write", "delete,execute");
        test("p3", "read,write,delete", "execute");
        test("p4", "read,write,delete,execute");
    } else {
        SecurityManager sm = System.getSecurityManager();
        for (String arg : args) {
            // Use bits to create powerset of ALL_ACTIONS
            IntStream.range(1, 16)
                    .mapToObj(n -> IntStream.range(0, 4)
                            .filter(x -> (n & (1 << x)) != 0)
                            .mapToObj(x -> ALL_ACTIONS[x])
                            .collect(Collectors.joining(",")))
                    .forEach(a -> sm.checkPermission(
                            new FilePermission(arg, a)));
        }
    }
}
项目:Equella    文件:InPlaceEditAppletLauncher.java   
public CachedFile(File tempFile)
{
    this.tempFile = tempFile;

    final Permissions filePermissions = new Permissions();
    final FilePermission crudPermission = new FilePermission(tempFile.getAbsolutePath(), "read,write,delete");
    filePermissions.add(crudPermission);
    debug("filePermissions Added FilePermission for 'read', 'write', 'delete' on " + tempFile.getAbsolutePath());
    filePermissionContext = new AccessControlContext(new ProtectionDomain[]{new ProtectionDomain(null,
        filePermissions)});

    final Permissions openPermissions = new Permissions();
    openPermissions.add(crudPermission);
    debug("openPermissions Added FilePermission for 'read', 'write', 'delete' on " + tempFile.getAbsolutePath());
    openPermissions.add(new FilePermission("<<ALL FILES>>", "execute"));
    debug("openPermissions Added FilePermission for 'execute' on <<ALL FILES>>");
    openPermissions.add(new AWTPermission("showWindowWithoutWarningBanner"));
    debug("openPermissions Added AWTPermission for 'showWindowWithoutWarningBanner'");
    openPermissionContext = new AccessControlContext(new ProtectionDomain[]{new ProtectionDomain(null,
        openPermissions)});

    setAsSynced();
}
项目:OpenJSharp    文件:ProxyClassesDumper.java   
public static ProxyClassesDumper getInstance(String path) {
    if (null == path) {
        return null;
    }
    try {
        path = path.trim();
        final Path dir = Paths.get(path.length() == 0 ? "." : path);
        AccessController.doPrivileged(new PrivilegedAction<Void>() {
                @Override
                public Void run() {
                    validateDumpDir(dir);
                    return null;
                }
            }, null, new FilePermission("<<ALL FILES>>", "read, write"));
        return new ProxyClassesDumper(dir);
    } catch (InvalidPathException ex) {
        PlatformLogger.getLogger(ProxyClassesDumper.class.getName())
                      .warning("Path " + path + " is not valid - dumping disabled", ex);
    } catch (IllegalArgumentException iae) {
        PlatformLogger.getLogger(ProxyClassesDumper.class.getName())
                      .warning(iae.getMessage() + " - dumping disabled");
    }
    return null;
}
项目:OpenJSharp    文件:PolicyFile.java   
/**
 * Creates one of the well-known permissions directly instead of
 * via reflection. Keep list short to not penalize non-JDK-defined
 * permissions.
 */
private static final Permission getKnownInstance(Class<?> claz,
    String name, String actions) {
    if (claz.equals(FilePermission.class)) {
        return new FilePermission(name, actions);
    } else if (claz.equals(SocketPermission.class)) {
        return new SocketPermission(name, actions);
    } else if (claz.equals(RuntimePermission.class)) {
        return new RuntimePermission(name, actions);
    } else if (claz.equals(PropertyPermission.class)) {
        return new PropertyPermission(name, actions);
    } else if (claz.equals(NetPermission.class)) {
        return new NetPermission(name, actions);
    } else if (claz.equals(AllPermission.class)) {
        return SecurityConstants.ALL_PERMISSION;
    } else {
        return null;
    }
}
项目:OpenJSharp    文件:UnixFileSystemProvider.java   
@Override
public Path readSymbolicLink(Path obj1) throws IOException {
    UnixPath link = UnixPath.toUnixPath(obj1);
    // permission check
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        FilePermission perm = new FilePermission(link.getPathForPermissionCheck(),
            SecurityConstants.FILE_READLINK_ACTION);
        sm.checkPermission(perm);
    }
    try {
        byte[] target = readlink(link);
        return new UnixPath(link.getFileSystem(), target);
    } catch (UnixException x) {
       if (x.errno() == UnixConstants.EINVAL)
            throw new NotLinkException(link.getPathForExceptionMessage());
        x.rethrowAsIOException(link);
        return null;    // keep compiler happy
    }
}
项目:openjdk-jdk10    文件:XSLTFunctionsTest.java   
/**
 * @bug 8165116
 * Verifies that redirect works properly when extension function is enabled
 *
 * @param xml the XML source
 * @param xsl the stylesheet that redirect output to a file
 * @param output the output file
 * @param redirect the redirect file
 * @throws Exception if the test fails
 **/
@Test(dataProvider = "redirect")
public void testRedirect(String xml, String xsl, String output, String redirect) throws Exception {

    TransformerFactory tf = TransformerFactory.newInstance();
    tf.setFeature(ORACLE_ENABLE_EXTENSION_FUNCTION, true);
    Transformer t = tf.newTransformer(new StreamSource(new StringReader(xsl)));

    //Transform the xml
    tryRunWithTmpPermission(
            () -> t.transform(new StreamSource(new StringReader(xml)), new StreamResult(new StringWriter())),
            new FilePermission(output, "write"), new FilePermission(redirect, "write"));

    // Verifies that the output is redirected successfully
    String userDir = getSystemProperty("user.dir");
    Path pathOutput = Paths.get(userDir, output);
    Path pathRedirect = Paths.get(userDir, redirect);
    Assert.assertTrue(Files.exists(pathOutput));
    Assert.assertTrue(Files.exists(pathRedirect));
    System.out.println("Output to " + pathOutput + " successful.");
    System.out.println("Redirect to " + pathRedirect + " successful.");
    Files.deleteIfExists(pathOutput);
    Files.deleteIfExists(pathRedirect);
}
项目:jdk8u-jdk    文件:ProxyClassesDumper.java   
public static ProxyClassesDumper getInstance(String path) {
    if (null == path) {
        return null;
    }
    try {
        path = path.trim();
        final Path dir = Paths.get(path.length() == 0 ? "." : path);
        AccessController.doPrivileged(new PrivilegedAction<Void>() {
                @Override
                public Void run() {
                    validateDumpDir(dir);
                    return null;
                }
            }, null, new FilePermission("<<ALL FILES>>", "read, write"));
        return new ProxyClassesDumper(dir);
    } catch (InvalidPathException ex) {
        PlatformLogger.getLogger(ProxyClassesDumper.class.getName())
                      .warning("Path " + path + " is not valid - dumping disabled", ex);
    } catch (IllegalArgumentException iae) {
        PlatformLogger.getLogger(ProxyClassesDumper.class.getName())
                      .warning(iae.getMessage() + " - dumping disabled");
    }
    return null;
}
项目:jdk8u-jdk    文件:PolicyFile.java   
/**
 * Creates one of the well-known permissions directly instead of
 * via reflection. Keep list short to not penalize non-JDK-defined
 * permissions.
 */
private static final Permission getKnownInstance(Class<?> claz,
    String name, String actions) {
    if (claz.equals(FilePermission.class)) {
        return new FilePermission(name, actions);
    } else if (claz.equals(SocketPermission.class)) {
        return new SocketPermission(name, actions);
    } else if (claz.equals(RuntimePermission.class)) {
        return new RuntimePermission(name, actions);
    } else if (claz.equals(PropertyPermission.class)) {
        return new PropertyPermission(name, actions);
    } else if (claz.equals(NetPermission.class)) {
        return new NetPermission(name, actions);
    } else if (claz.equals(AllPermission.class)) {
        return SecurityConstants.ALL_PERMISSION;
    } else {
        return null;
    }
}
项目:openjdk-jdk10    文件:Flag.java   
public static void main(String[] args) throws Exception {

        boolean test1;
        boolean test2;

        String here = System.getProperty("user.dir");
        File abs = new File(here, "x");
        FilePermission fp1 = new FilePermission("x", "read");
        FilePermission fp2 = new FilePermission(abs.toString(), "read");
        test1 = fp1.equals(fp2);

        try {
            System.getSecurityManager().checkPermission(fp2);
            test2 = true;
        } catch (SecurityException se) {
            test2 = false;
        }

        if (test1 != Boolean.parseBoolean(args[0]) ||
                test2 != Boolean.parseBoolean(args[1])) {
            throw new Exception("Test failed: " + test1 + " " + test2);
        }
    }
项目:jdk8u-jdk    文件:FieldSetAccessibleTest.java   
public SimplePolicy(TestCase test, ThreadLocal<AtomicBoolean> allowAll) {
    this.allowAll = allowAll;

    // Permission needed by the tested code exercised in the test
    permissions = new Permissions();
    permissions.add(new RuntimePermission("fileSystemProvider"));
    permissions.add(new RuntimePermission("createClassLoader"));
    permissions.add(new RuntimePermission("closeClassLoader"));
    permissions.add(new RuntimePermission("getClassLoader"));
    permissions.add(new RuntimePermission("accessDeclaredMembers"));
    permissions.add(new ReflectPermission("suppressAccessChecks"));
    permissions.add(new PropertyPermission("*", "read"));
    permissions.add(new FilePermission("<<ALL FILES>>", "read"));

    // these are used for configuring the test itself...
    allPermissions = new Permissions();
    allPermissions.add(new java.security.AllPermission());
}
项目:jdk8u-jdk    文件:FileHandlerPath.java   
public SimplePolicy(TestCase test, AtomicBoolean allowAll) {
    this.allowAll = allowAll;
    permissions = new Permissions();
    permissions.add(new LoggingPermission("control", null)); // needed by new FileHandler()
    permissions.add(new FilePermission("<<ALL FILES>>", "read")); // needed by new FileHandler()
    permissions.add(new FilePermission(logFile, "write,delete")); // needed by new FileHandler()
    permissions.add(new FilePermission(logFile+".lck", "write,delete")); // needed by FileHandler.close()
    permissions.add(new FilePermission(logFile+".1", "write,delete")); // needed by new FileHandler()
    permissions.add(new FilePermission(logFile+".1.lck", "write,delete")); // needed by FileHandler.close()
    permissions.add(new FilePermission(tmpLogFile, "write,delete")); // needed by new FileHandler()
    permissions.add(new FilePermission(tmpLogFile+".lck", "write,delete")); // needed by FileHandler.close()
    permissions.add(new FilePermission(tmpLogFile+".1", "write,delete")); // needed by new FileHandler()
    permissions.add(new FilePermission(tmpLogFile+".1.lck", "write,delete")); // needed by FileHandler.close()
    permissions.add(new FilePermission(userDir, "write")); // needed by new FileHandler()
    permissions.add(new FilePermission(tmpDir, "write")); // needed by new FileHandler()
    permissions.add(new PropertyPermission("user.dir", "read"));
    permissions.add(new PropertyPermission("java.io.tmpdir", "read"));
    allPermissions = new Permissions();
    allPermissions.add(new java.security.AllPermission());
}
项目:openjdk-jdk10    文件:ProxyClassesDumper.java   
public static ProxyClassesDumper getInstance(String path) {
    if (null == path) {
        return null;
    }
    try {
        path = path.trim();
        final Path dir = Paths.get(path.length() == 0 ? "." : path);
        AccessController.doPrivileged(new PrivilegedAction<>() {
                @Override
                public Void run() {
                    validateDumpDir(dir);
                    return null;
                }
            }, null, new FilePermission("<<ALL FILES>>", "read, write"));
        return new ProxyClassesDumper(dir);
    } catch (InvalidPathException ex) {
        PlatformLogger.getLogger(ProxyClassesDumper.class.getName())
                      .warning("Path " + path + " is not valid - dumping disabled", ex);
    } catch (IllegalArgumentException iae) {
        PlatformLogger.getLogger(ProxyClassesDumper.class.getName())
                      .warning(iae.getMessage() + " - dumping disabled");
    }
    return null;
}
项目:openjdk-jdk10    文件:PolicyFile.java   
/**
 * Creates one of the well-known permissions in the java.base module
 * directly instead of via reflection. Keep list short to not penalize
 * permissions from other modules.
 */
private static Permission getKnownPermission(Class<?> claz, String name,
                                             String actions) {
    if (claz.equals(FilePermission.class)) {
        return new FilePermission(name, actions);
    } else if (claz.equals(SocketPermission.class)) {
        return new SocketPermission(name, actions);
    } else if (claz.equals(RuntimePermission.class)) {
        return new RuntimePermission(name, actions);
    } else if (claz.equals(PropertyPermission.class)) {
        return new PropertyPermission(name, actions);
    } else if (claz.equals(NetPermission.class)) {
        return new NetPermission(name, actions);
    } else if (claz.equals(AllPermission.class)) {
        return SecurityConstants.ALL_PERMISSION;
    } else if (claz.equals(SecurityPermission.class)) {
        return new SecurityPermission(name, actions);
    } else {
        return null;
    }
}
项目:openjdk-jdk10    文件:UnixFileSystemProvider.java   
@Override
public Path readSymbolicLink(Path obj1) throws IOException {
    UnixPath link = UnixPath.toUnixPath(obj1);
    // permission check
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        FilePermission perm = new FilePermission(link.getPathForPermissionCheck(),
            SecurityConstants.FILE_READLINK_ACTION);
        sm.checkPermission(perm);
    }
    try {
        byte[] target = readlink(link);
        return new UnixPath(link.getFileSystem(), target);
    } catch (UnixException x) {
       if (x.errno() == UnixConstants.EINVAL)
            throw new NotLinkException(link.getPathForExceptionMessage());
        x.rethrowAsIOException(link);
        return null;    // keep compiler happy
    }
}
项目:openjdk-jdk10    文件:PermissionTest.java   
public void setBasicPermissions() {
    permissions.add(new SecurityPermission("getPolicy"));
    permissions.add(new SecurityPermission("setPolicy"));
    permissions.add(new RuntimePermission("getClassLoader"));
    permissions.add(new RuntimePermission("setSecurityManager"));
    permissions.add(new RuntimePermission("createSecurityManager"));
    permissions.add(new PropertyPermission("testng.show.stack.frames",
            "read"));
    permissions.add(new PropertyPermission("user.dir", "read"));
    permissions.add(new PropertyPermission("test.src", "read"));
    permissions.add(new PropertyPermission("file.separator", "read"));
    permissions.add(new PropertyPermission("line.separator", "read"));
    permissions.add(new PropertyPermission("fileStringBuffer", "read"));
    permissions.add(new PropertyPermission("dataproviderthreadcount", "read"));
    permissions.add(new FilePermission("<<ALL FILES>>", "execute"));
}
项目:openjdk-jdk10    文件:FieldSetAccessibleTest.java   
public SimplePolicy(TestCase test, ThreadLocal<AtomicBoolean> allowAll) {
    this.allowAll = allowAll;

    // Permission needed by the tested code exercised in the test
    permissions = new Permissions();
    permissions.add(new RuntimePermission("fileSystemProvider"));
    permissions.add(new RuntimePermission("createClassLoader"));
    permissions.add(new RuntimePermission("closeClassLoader"));
    permissions.add(new RuntimePermission("getClassLoader"));
    permissions.add(new RuntimePermission("accessDeclaredMembers"));
    permissions.add(new RuntimePermission("accessSystemModules"));
    permissions.add(new ReflectPermission("suppressAccessChecks"));
    permissions.add(new PropertyPermission("*", "read"));
    permissions.add(new FilePermission("<<ALL FILES>>", "read"));

    // these are used for configuring the test itself...
    allPermissions = new Permissions();
    allPermissions.add(new java.security.AllPermission());
}
项目:elasticsearch_my    文件:ESPolicyUnitTests.java   
/**
 * Test policy with null codesource.
 * <p>
 * This can happen when restricting privileges with doPrivileged,
 * even though ProtectionDomain's ctor javadocs might make you think
 * that the policy won't be consulted.
 */
public void testNullCodeSource() throws Exception {
    assumeTrue("test cannot run with security manager", System.getSecurityManager() == null);
    // create a policy with AllPermission
    Permission all = new AllPermission();
    PermissionCollection allCollection = all.newPermissionCollection();
    allCollection.add(all);
    ESPolicy policy = new ESPolicy(allCollection, Collections.emptyMap(), true);
    // restrict ourselves to NoPermission
    PermissionCollection noPermissions = new Permissions();
    assertFalse(policy.implies(new ProtectionDomain(null, noPermissions), new FilePermission("foo", "read")));
}
项目:elasticsearch_my    文件:ESPolicyUnitTests.java   
/**
 * test with null location
 * <p>
 * its unclear when/if this happens, see https://bugs.openjdk.java.net/browse/JDK-8129972
 */
public void testNullLocation() throws Exception {
    assumeTrue("test cannot run with security manager", System.getSecurityManager() == null);
    PermissionCollection noPermissions = new Permissions();
    ESPolicy policy = new ESPolicy(noPermissions, Collections.emptyMap(), true);
    assertFalse(policy.implies(new ProtectionDomain(new CodeSource(null, (Certificate[]) null), noPermissions),
            new FilePermission("foo", "read")));
}
项目:elasticsearch_my    文件:EvilSecurityTests.java   
/**
 * checks that this path has no permissions
 */
static void assertNoPermissions(Path path, PermissionCollection actual) {
    String target = path.toString();
    assertFalse(actual.implies(new FilePermission(target, "read")));
    assertFalse(actual.implies(new FilePermission(target, "readlink")));
    assertFalse(actual.implies(new FilePermission(target, "write")));
    assertFalse(actual.implies(new FilePermission(target, "delete")));
    assertFalse(actual.implies(new FilePermission(target, "execute")));
}
项目:elasticsearch_my    文件:Security.java   
/**
 * Add access to path (and all files underneath it)
 * @param policy current policy to add permissions to
 * @param configurationName the configuration name associated with the path (for error messages only)
 * @param path the path itself
 * @param permissions set of file permissions to grant to the path
 */
static void addPath(Permissions policy, String configurationName, Path path, String permissions) {
    // paths may not exist yet, this also checks accessibility
    try {
        ensureDirectoryExists(path);
    } catch (IOException e) {
        throw new IllegalStateException("Unable to access '" + configurationName + "' (" + path + ")", e);
    }

    // add each path twice: once for itself, again for files underneath it
    policy.add(new FilePermission(path.toString(), permissions));
    policy.add(new FilePermission(path.toString() + path.getFileSystem().getSeparator() + "-", permissions));
}
项目:elasticsearch_my    文件:Security.java   
/**
 * Add access to a directory iff it exists already
 * @param policy current policy to add permissions to
 * @param configurationName the configuration name associated with the path (for error messages only)
 * @param path the path itself
 * @param permissions set of file permissions to grant to the path
 */
static void addPathIfExists(Permissions policy, String configurationName, Path path, String permissions) {
    if (Files.isDirectory(path)) {
        // add each path twice: once for itself, again for files underneath it
        policy.add(new FilePermission(path.toString(), permissions));
        policy.add(new FilePermission(path.toString() + path.getFileSystem().getSeparator() + "-", permissions));
        try {
            path.getFileSystem().provider().checkAccess(path.toRealPath(), AccessMode.READ);
        } catch (IOException e) {
            throw new IllegalStateException("Unable to access '" + configurationName + "' (" + path + ")", e);
        }
    }
}
项目:elasticsearch_my    文件:ESPolicy.java   
@Override @SuppressForbidden(reason = "fast equals check is desired")
public boolean implies(ProtectionDomain domain, Permission permission) {
    CodeSource codeSource = domain.getCodeSource();
    // codesource can be null when reducing privileges via doPrivileged()
    if (codeSource == null) {
        return false;
    }

    URL location = codeSource.getLocation();
    // location can be null... ??? nobody knows
    // https://bugs.openjdk.java.net/browse/JDK-8129972
    if (location != null) {
        // run scripts with limited permissions
        if (BootstrapInfo.UNTRUSTED_CODEBASE.equals(location.getFile())) {
            return untrusted.implies(domain, permission);
        }
        // check for an additional plugin permission: plugin policy is
        // only consulted for its codesources.
        Policy plugin = plugins.get(location.getFile());
        if (plugin != null && plugin.implies(domain, permission)) {
            return true;
        }
    }

    // Special handling for broken Hadoop code: "let me execute or my classes will not load"
    // yeah right, REMOVE THIS when hadoop is fixed
    if (permission instanceof FilePermission && "<<ALL FILES>>".equals(permission.getName())) {
        for (StackTraceElement element : Thread.currentThread().getStackTrace()) {
            if ("org.apache.hadoop.util.Shell".equals(element.getClassName()) &&
                  "runCommand".equals(element.getMethodName())) {
                // we found the horrible method: the hack begins!
                // force the hadoop code to back down, by throwing an exception that it catches.
                rethrow(new IOException("no hadoop, you cannot do this."));
            }
        }
    }

    // otherwise defer to template + dynamic file permissions
    return template.implies(domain, permission) || dynamic.implies(permission) || system.implies(domain, permission);
}
项目:acdebugger    文件:BreakpointProcessor.java   
private void extractFilePermActions(ObjectReference permission, StringBuilder sb) {
  IntegerValue value =
      (IntegerValue) permission.getValue(permission.referenceType().fieldByName("mask"));
  Integer mask = value.value();

  try {
    Method meth = FilePermission.class.getDeclaredMethod("getActions", int.class);
    meth.setAccessible(true);
    String actions = (String) meth.invoke(null, mask);

    sb.append(actions);
  } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
    sb.append("FILEPERMS ACTIONS UNKNOWN");
  }
}
项目:elasticsearch_my    文件:TikaImpl.java   
@SuppressForbidden(reason = "adds access to jar resources")
static void addReadPermissions(Permissions perms, URL resources[]) {
    try {
        for (URL url : resources) {
            Path path = PathUtils.get(url.toURI());
            // resource itself
            perms.add(new FilePermission(path.toString(), "read,readlink"));
            // classes underneath
            perms.add(new FilePermission(path.toString() + System.getProperty("file.separator") + "-", "read,readlink"));
        }
    } catch (URISyntaxException bogus) {
        throw new RuntimeException(bogus);
    }
}
项目:guava-mock    文件:ClassPathTest.java   
private void doTestExistsThrowsSecurityException() throws IOException, URISyntaxException {
  URLClassLoader myLoader = (URLClassLoader) getClass().getClassLoader();
  URL[] urls = myLoader.getURLs();
  ImmutableList.Builder<File> filesBuilder = ImmutableList.builder();
  for (URL url : urls) {
    if (url.getProtocol().equalsIgnoreCase("file")) {
      filesBuilder.add(new File(url.toURI()));
    }
  }
  ImmutableList<File> files = filesBuilder.build();
  assertThat(files).isNotEmpty();
  SecurityManager disallowFilesSecurityManager = new SecurityManager() {
    @Override
    public void checkPermission(Permission p) {
      if (p instanceof FilePermission) {
        throw new SecurityException("Disallowed: " + p);
      }
    }
  };
  System.setSecurityManager(disallowFilesSecurityManager);
  try {
    files.get(0).exists();
    fail("Did not get expected SecurityException");
  } catch (SecurityException expected) {
  }
  ClassPath classPath = ClassPath.from(myLoader);
  assertThat(classPath.getResources()).isEmpty();
}
项目:gemini.blueprint    文件:DuplicateClassTest.java   
protected List getTestPermissions() {
    List list = super.getTestPermissions();
    list.add(new FilePermission("<<ALL FILES>>", "read"));
    list.add(new AdminPermission("*", AdminPermission.EXECUTE));
    list.add(new AdminPermission("*", AdminPermission.LIFECYCLE));
    list.add(new AdminPermission("*", AdminPermission.RESOLVE));
    list.add(new AdminPermission("*", AdminPermission.METADATA));
    return list;
}
项目:gemini.blueprint    文件:ExtenderTest.java   
protected List getTestPermissions() {
    List perms = super.getTestPermissions();
    // export package
    perms.add(new AdminPermission("*", AdminPermission.EXECUTE));
    perms.add(new AdminPermission("*", AdminPermission.LIFECYCLE));
    perms.add(new AdminPermission("*", AdminPermission.RESOLVE));
    perms.add(new FilePermission("<<ALL FILES>>", "read"));
    return perms;
}
项目:gemini.blueprint    文件:ExtenderVersionTest.java   
protected List getTestPermissions() {
    List perms = super.getTestPermissions();
    // export package
    perms.add(new AdminPermission("*", AdminPermission.EXECUTE));
    perms.add(new AdminPermission("*", AdminPermission.LIFECYCLE));
    perms.add(new AdminPermission("*", AdminPermission.RESOLVE));
    perms.add(new FilePermission("<<ALL FILES>>", "read"));
    return perms;
}
项目:openjdk-jdk10    文件:UpdateConfigurationTest.java   
public SimplePolicy(TestCase test, ThreadLocal<AtomicBoolean> allowAll) {
    this.allowAll = allowAll;
    permissions = new Permissions();
    permissions.add(new LoggingPermission("control", null));
    permissions.add(new FilePermission(PREFIX+".lck", "read,write,delete"));
    permissions.add(new FilePermission(PREFIX, "read,write"));

    // these are used for configuring the test itself...
    allPermissions = new Permissions();
    allPermissions.add(new java.security.AllPermission());

}
项目:openjdk-jdk10    文件:Bug6555001.java   
@Test
public void testReplacing() throws Exception {
    JAXPTestUtilities.tryRunWithTmpPermission(() -> {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        factory.setProperty("javax.xml.stream.isReplacingEntityReferences", true);

        StringReader sr = new StringReader(XML);
        XMLEventReader reader = factory.createXMLEventReader(sr);

        boolean sawUndef = false;
        boolean sawDef = false;

        while (reader.hasNext()) {
            XMLEvent event = reader.nextEvent();
            // System.out.println("Event: " + event);
            if (event.isEntityReference()) {
                EntityReference ref = (EntityReference) event;
                if ("def".equals(ref.getName())) {
                    sawDef = true;
                } else if ("undef".equals(ref.getName())) {
                    sawUndef = true;
                } else {
                    throw new IllegalArgumentException("Unexpected entity name");
                }
            }
        }

        Assert.assertEquals(false, sawDef);
        Assert.assertEquals(true, sawUndef);
        reader.close();
    }, new FilePermission("/tmp/this/does/not/exist/but/that/is/ok", "read"));
}
项目:openjdk-jdk10    文件:HandlersOnComplexResetUpdate.java   
public SimplePolicy(TestCase test, ThreadLocal<AtomicBoolean> allowAll) {
    this.allowAll = allowAll;
    permissions = new Permissions();
    permissions.add(new LoggingPermission("control", null));
    permissions.add(new FilePermission(PREFIX+".lck", "read,write,delete"));
    permissions.add(new FilePermission(PREFIX, "read,write"));

    // these are used for configuring the test itself...
    allPermissions = new Permissions();
    allPermissions.add(new java.security.AllPermission());

}
项目:gemini.blueprint    文件:Cardinality0to1Test.java   
protected List getTestPermissions() {
    List perms = super.getTestPermissions();
    perms.add(new FilePermission("<<ALL FILES>>", "read"));
    perms.add(new AdminPermission("*", AdminPermission.EXECUTE));
    perms.add(new AdminPermission("*", AdminPermission.LIFECYCLE));
    perms.add(new AdminPermission("*", AdminPermission.RESOLVE));
    perms.add(new PropertyPermission("*", "read"));
    perms.add(new PropertyPermission("*", "write"));
    return perms;
}
项目:gemini.blueprint    文件:OsgiLifecycleNotificationTest.java   
protected List getTestPermissions() {
    List perms = super.getTestPermissions();
    // export package
    perms.add(new AdminPermission("*", AdminPermission.EXECUTE));
    perms.add(new AdminPermission("*", AdminPermission.LIFECYCLE));
    perms.add(new AdminPermission("*", AdminPermission.RESOLVE));
    perms.add(new FilePermission("<<ALL FILES>>", "read"));
    return perms;
}
项目:gemini.blueprint    文件:BehaviorBaseTest.java   
protected List getTestPermissions() {
    List list = super.getTestPermissions();
    list.add(new FilePermission("<<ALL FILES>>", "read"));
    list.add(new AdminPermission("*", AdminPermission.LIFECYCLE));
    list.add(new AdminPermission("*", AdminPermission.EXECUTE));
    list.add(new AdminPermission("*", AdminPermission.RESOLVE));
    return list;
}