Java Code Examples for java.nio.file.Files#getPosixFilePermissions()

The following examples show how to use java.nio.file.Files#getPosixFilePermissions() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestPosixFilePermissions.java    From jsr203-hadoop with Apache License 2.0 6 votes vote down vote up
/**
 * Simple test to check posix file permission on createFile().
 * 
 * @throws IOException
 */
@Test
public void testWriteBuffered() throws IOException {
	Path rootPath = Paths.get(clusterUri);

	Path pathToTest = rootPath.resolve("tmp/out6.txt");

	Path path = pathToTest;
	Set<PosixFilePermission> perms = EnumSet.of(
			PosixFilePermission.OWNER_READ,
			PosixFilePermission.OWNER_WRITE,
			PosixFilePermission.GROUP_READ,
			PosixFilePermission.GROUP_WRITE);
	Files.createFile(path, PosixFilePermissions.asFileAttribute(perms));

	Set<PosixFilePermission> perms2 = Files.getPosixFilePermissions(path, LinkOption.NOFOLLOW_LINKS);
	assertNotNull(perms2);
	
	assertTrue(perms2.contains(PosixFilePermission.OWNER_READ));
}
 
Example 2
Source File: LocalJavaKeyStoreProvider.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Override
protected void stashOriginalFilePermissions() throws IOException {
  // save off permissions in case we need to
  // rewrite the keystore in flush()
  if (!Shell.WINDOWS) {
    Path path = Paths.get(file.getCanonicalPath());
    permissions = Files.getPosixFilePermissions(path);
  } else {
    // On Windows, the JDK does not support the POSIX file permission APIs.
    // Instead, we can do a winutils call and translate.
    String[] cmd = Shell.getGetPermissionCommand();
    String[] args = new String[cmd.length + 1];
    System.arraycopy(cmd, 0, args, 0, cmd.length);
    args[cmd.length] = file.getCanonicalPath();
    String out = Shell.execCommand(args);
    StringTokenizer t = new StringTokenizer(out, Shell.TOKEN_SEPARATOR_REGEX);
    // The winutils output consists of 10 characters because of the leading
    // directory indicator, i.e. "drwx------".  The JDK parsing method expects
    // a 9-character string, so remove the leading character.
    String permString = t.nextToken().substring(1);
    permissions = PosixFilePermissions.fromString(permString);
  }
}
 
Example 3
Source File: WebServerTask.java    From datacollector with Apache License 2.0 6 votes vote down vote up
private void validateRealmFile(File realmFile) {
  boolean checkRealmFilePermission = conf.get(REALM_FILE_PERMISSION_CHECK, REALM_FILE_PERMISSION_CHECK_DEFAULT);
  if(!checkRealmFilePermission) {
    return;
  }

  if (!realmFile.exists()) {
    throw new RuntimeException(Utils.format("Realm file '{}' does not exists", realmFile));
  }
  if (!realmFile.isFile()) {
    throw new RuntimeException(Utils.format("Realm file '{}' is not a file", realmFile));
  }
  try {
    Set<PosixFilePermission> permissions = Files.getPosixFilePermissions(realmFile.toPath());
    permissions.removeAll(OWNER_PERMISSIONS);
    if (!permissions.isEmpty()) {
      throw new RuntimeException(Utils.format("The permissions of the realm file '{}' should be owner only",
                                              realmFile));
    }
  } catch (IOException ex) {
    throw new RuntimeException(Utils.format("Could not get the permissions of the realm file '{}', {}", realmFile,
                                            ex.toString()), ex);
  }
}
 
Example 4
Source File: InitMojo.java    From helm-maven-plugin with MIT License 6 votes vote down vote up
private void addExecPermission(final Path helm) throws IOException {
	Set<String> fileAttributeView = FileSystems.getDefault().supportedFileAttributeViews();

	if (fileAttributeView.contains("posix")) {
		final Set<PosixFilePermission> permissions;
		try {
			permissions = Files.getPosixFilePermissions(helm);
		} catch (UnsupportedOperationException e) {
			getLog().debug("Exec file permission is not set", e);
			return;
		}
		permissions.add(PosixFilePermission.OWNER_EXECUTE);
		Files.setPosixFilePermissions(helm, permissions);

	} else if (fileAttributeView.contains("acl")) {
		String username = System.getProperty("user.name");
		UserPrincipal userPrincipal = FileSystems.getDefault().getUserPrincipalLookupService().lookupPrincipalByName(username);
		AclEntry aclEntry = AclEntry.newBuilder().setPermissions(AclEntryPermission.EXECUTE).setType(AclEntryType.ALLOW).setPrincipal(userPrincipal).build();

		AclFileAttributeView acl = Files.getFileAttributeView(helm, AclFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
		List<AclEntry> aclEntries = acl.getAcl();
		aclEntries.add(aclEntry);
		acl.setAcl(aclEntries);
	}
}
 
Example 5
Source File: LogSegmentTest.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * Test that the file permissions are correctly set based on permissions specified in {@link StoreConfig}.
 * @throws Exception
 */
@Test
public void setFilePermissionsTest() throws Exception {
  Properties props = new Properties();
  props.setProperty("store.set.file.permission.enabled", Boolean.toString(true));
  props.setProperty("store.data.file.permission", "rw-rw-r--");
  StoreConfig initialConfig = new StoreConfig(new VerifiableProperties(props));
  File segmentFile = new File(tempDir, "test_segment");
  assertTrue("Fail to create segment file", segmentFile.createNewFile());
  segmentFile.deleteOnExit();
  // create log segment instance by writing into brand new file (using initialConfig, file permission = "rw-rw-r--")
  new LogSegment(segmentFile.getName(), segmentFile, STANDARD_SEGMENT_SIZE, initialConfig, metrics, true);
  Set<PosixFilePermission> filePerm = Files.getPosixFilePermissions(segmentFile.toPath());
  assertEquals("File permissions are not expected", "rw-rw-r--", PosixFilePermissions.toString(filePerm));
  // create log segment instance by reading from existing file (using default store config, file permission = "rw-rw----")
  new LogSegment(segmentFile.getName(), segmentFile, config, metrics);
  filePerm = Files.getPosixFilePermissions(segmentFile.toPath());
  assertEquals("File permissions are not expected", "rw-rw----", PosixFilePermissions.toString(filePerm));
}
 
Example 6
Source File: MostFiles.java    From buck with Apache License 2.0 6 votes vote down vote up
/**
 * Tries to make the specified file executable. For file systems that do support the POSIX-style
 * permissions, the executable permission is set for each category of users that already has the
 * read permission.
 *
 * <p>If the file system does not support the executable permission or the operation fails, a
 * {@code java.io.IOException} is thrown.
 */
public static void makeExecutable(Path file) throws IOException {
  if (FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) {
    Set<PosixFilePermission> permissions = Files.getPosixFilePermissions(file);

    if (permissions.contains(PosixFilePermission.OWNER_READ)) {
      permissions.add(PosixFilePermission.OWNER_EXECUTE);
    }
    if (permissions.contains(PosixFilePermission.GROUP_READ)) {
      permissions.add(PosixFilePermission.GROUP_EXECUTE);
    }
    if (permissions.contains(PosixFilePermission.OTHERS_READ)) {
      permissions.add(PosixFilePermission.OTHERS_EXECUTE);
    }

    Files.setPosixFilePermissions(file, permissions);
  } else {
    if (!file.toFile().setExecutable(/* executable */ true, /* ownerOnly */ true)) {
      throw new IOException("The file could not be made executable");
    }
  }
}
 
Example 7
Source File: AbstractFilePermissionTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Test 1 - SSL config file is secure - VM should start
 */
private void test2() throws Exception {
    final Set<PosixFilePermission> perms = Files.getPosixFilePermissions(file2PermissionTest);
    perms.add(PosixFilePermission.OTHERS_READ);
    perms.add(PosixFilePermission.OTHERS_EXECUTE);
    Files.setPosixFilePermissions(file2PermissionTest, perms);

    if (doTest() == 0) {
        ++failures;
    }
}
 
Example 8
Source File: TestDataStore.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultPermission() throws IOException {
  File file = new File(createTestDir(), "x");
  DataStore ds = new DataStore(file);
  try {
    OutputStream outputStream = ds.getOutputStream();
    ds.commit(outputStream);
    ds.release();
  } finally {
    ds.close();
  }
  Set<PosixFilePermission> perms = Files.getPosixFilePermissions(file.toPath());
  Assert.assertEquals(ImmutableSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE), perms);
}
 
Example 9
Source File: SafeFilesTest.java    From util with Apache License 2.0 5 votes vote down vote up
private static void checkFilePermissions(Path path) {
    try {
        final Path tempFile = java.nio.file.Files.createTempFile("tmp", "tmp", PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwxrwxrwx")));
        final Set<PosixFilePermission> inverseUmask;
        try {
            inverseUmask = Files.getPosixFilePermissions(tempFile);
        } finally {
            java.nio.file.Files.delete(tempFile);
        }

        final Set<PosixFilePermission> posixFilePermissions = java.nio.file.Files.getPosixFilePermissions(path);
        if (inverseUmask.contains(PosixFilePermission.OWNER_READ)) {
            Assert.assertTrue("owner read permission not set", posixFilePermissions.contains(PosixFilePermission.OWNER_READ));
        }
        if (inverseUmask.contains(PosixFilePermission.OWNER_WRITE)) {
            Assert.assertTrue("owner write permission not set", posixFilePermissions.contains(PosixFilePermission.OWNER_WRITE));
        }
        if (inverseUmask.contains(PosixFilePermission.GROUP_READ)) {
            Assert.assertTrue("group read permission not set", posixFilePermissions.contains(PosixFilePermission.GROUP_READ));
        }
        if (inverseUmask.contains(PosixFilePermission.OTHERS_READ)) {
            Assert.assertTrue("other read permission not set", posixFilePermissions.contains(PosixFilePermission.OTHERS_READ));
        }
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}
 
Example 10
Source File: CustomLauncherTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static String[] getLauncher() throws IOException {
    String platform = getPlatform();
    if (platform == null) {
        return null;
    }

    String launcher = TEST_SRC + File.separator + platform + "-" + ARCH +
                      File.separator + "launcher";

    final FileSystem FS = FileSystems.getDefault();
    Path launcherPath = FS.getPath(launcher);

    final boolean hasLauncher = Files.isRegularFile(launcherPath, LinkOption.NOFOLLOW_LINKS)&&
                                Files.isReadable(launcherPath);
    if (!hasLauncher) {
        System.out.println("Launcher [" + launcher + "] does not exist. Skipping the test.");
        return null;
    }

    // It is impossible to store an executable file in the source control
    // We need to copy the launcher to the working directory
    // and set the executable flag
    Path localLauncherPath = FS.getPath(WORK_DIR, "launcher");
    Files.copy(launcherPath, localLauncherPath,
               StandardCopyOption.REPLACE_EXISTING,
               StandardCopyOption.COPY_ATTRIBUTES);
    if (!Files.isExecutable(localLauncherPath)) {
        Set<PosixFilePermission> perms = new HashSet<>(
            Files.getPosixFilePermissions(
                localLauncherPath,
                LinkOption.NOFOLLOW_LINKS
            )
        );
        perms.add(PosixFilePermission.OWNER_EXECUTE);
        Files.setPosixFilePermissions(localLauncherPath, perms);
    }
    return new String[] {launcher, localLauncherPath.toAbsolutePath().toString()};
}
 
Example 11
Source File: CustomLauncherTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static String[] getLauncher() throws IOException {
    String platform = getPlatform();
    if (platform == null) {
        return null;
    }

    String launcher = TEST_SRC + File.separator + platform + "-" + ARCH +
                      File.separator + "launcher";

    final FileSystem FS = FileSystems.getDefault();
    Path launcherPath = FS.getPath(launcher);

    final boolean hasLauncher = Files.isRegularFile(launcherPath, LinkOption.NOFOLLOW_LINKS)&&
                                Files.isReadable(launcherPath);
    if (!hasLauncher) {
        System.out.println("Launcher [" + launcher + "] does not exist. Skipping the test.");
        return null;
    }

    // It is impossible to store an executable file in the source control
    // We need to copy the launcher to the working directory
    // and set the executable flag
    Path localLauncherPath = FS.getPath(WORK_DIR, "launcher");
    Files.copy(launcherPath, localLauncherPath,
               StandardCopyOption.REPLACE_EXISTING,
               StandardCopyOption.COPY_ATTRIBUTES);
    if (!Files.isExecutable(localLauncherPath)) {
        Set<PosixFilePermission> perms = new HashSet<>(
            Files.getPosixFilePermissions(
                localLauncherPath,
                LinkOption.NOFOLLOW_LINKS
            )
        );
        perms.add(PosixFilePermission.OWNER_EXECUTE);
        Files.setPosixFilePermissions(localLauncherPath, perms);
    }
    return new String[] {launcher, localLauncherPath.toAbsolutePath().toString()};
}
 
Example 12
Source File: CustomLauncherTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private static String[] getLauncher() throws IOException {
    String platform = getPlatform();
    if (platform == null) {
        return null;
    }

    String launcher = TEST_SRC + File.separator + platform + "-" + ARCH +
                      File.separator + "launcher";

    final FileSystem FS = FileSystems.getDefault();
    Path launcherPath = FS.getPath(launcher);

    final boolean hasLauncher = Files.isRegularFile(launcherPath, LinkOption.NOFOLLOW_LINKS)&&
                                Files.isReadable(launcherPath);
    if (!hasLauncher) {
        System.out.println("Launcher [" + launcher + "] does not exist. Skipping the test.");
        return null;
    }

    // It is impossible to store an executable file in the source control
    // We need to copy the launcher to the working directory
    // and set the executable flag
    Path localLauncherPath = FS.getPath(WORK_DIR, "launcher");
    Files.copy(launcherPath, localLauncherPath,
               StandardCopyOption.REPLACE_EXISTING,
               StandardCopyOption.COPY_ATTRIBUTES);
    if (!Files.isExecutable(localLauncherPath)) {
        Set<PosixFilePermission> perms = new HashSet<>(
            Files.getPosixFilePermissions(
                localLauncherPath,
                LinkOption.NOFOLLOW_LINKS
            )
        );
        perms.add(PosixFilePermission.OWNER_EXECUTE);
        Files.setPosixFilePermissions(localLauncherPath, perms);
    }
    return new String[] {launcher, localLauncherPath.toAbsolutePath().toString()};
}
 
Example 13
Source File: FileHelperTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
private void assertPermissions(Path path) throws IOException
{
    Set<PosixFilePermission> permissions = Files.getPosixFilePermissions(path);
    assertTrue("Unexpected owner read permission", permissions.contains(PosixFilePermission.OWNER_READ));
    assertTrue("Unexpected owner write permission", permissions.contains(PosixFilePermission.OWNER_WRITE));
    assertTrue("Unexpected owner exec permission", permissions.contains(PosixFilePermission.OWNER_EXECUTE));
    assertTrue("Unexpected group read permission", permissions.contains(PosixFilePermission.GROUP_READ));
    assertFalse("Unexpected group write permission", permissions.contains(PosixFilePermission.GROUP_WRITE));
    assertTrue("Unexpected group exec permission", permissions.contains(PosixFilePermission.GROUP_EXECUTE));
    assertFalse("Unexpected others read permission", permissions.contains(PosixFilePermission.OTHERS_READ));
    assertFalse("Unexpected others write permission", permissions.contains(PosixFilePermission.OTHERS_WRITE));
    assertFalse("Unexpected others exec permission",
                       permissions.contains(PosixFilePermission.OTHERS_EXECUTE));
}
 
Example 14
Source File: FileUsageLoggingClientTest.java    From rtg-tools with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void testPermissions() throws IOException {
  try (TestDirectory dir = new TestDirectory()) {
    final FileUsageLoggingClient client = new FileUsageLoggingClient(dir, new UsageConfiguration(new Properties()), false);
    final UUID runId = UUID.randomUUID();
    final Date date = new Date();
    final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");
    final String expectedFilename = df.format(date) + ".usage";
    client.recordBeginning("unitTest", runId);
    FileUtils.appendToFile(new File(dir, expectedFilename), "some stuff" + StringUtils.LS);
    client.recordEnd(42, "unitTest", runId, true);
    final File[] files = dir.listFiles();
    assertNotNull(files);
    assertEquals(1, files.length);
    final File usageOut = files[0];

    assertTrue(usageOut.canRead());
    assertTrue(usageOut.canWrite());

    try {
      final Path path = FileSystems.getDefault().getPath(usageOut.getCanonicalPath());
      final Set<PosixFilePermission> perms = Files.getPosixFilePermissions(path);

      //System.err.println(perms);
      assertTrue(perms.contains(PosixFilePermission.GROUP_READ));
      assertTrue(perms.contains(PosixFilePermission.GROUP_WRITE));
      assertTrue(perms.contains(PosixFilePermission.OWNER_READ));
      assertTrue(perms.contains(PosixFilePermission.OWNER_WRITE));
      assertTrue(perms.contains(PosixFilePermission.OTHERS_READ));
      assertTrue(perms.contains(PosixFilePermission.OTHERS_WRITE));
    } catch (UnsupportedOperationException uoe) {
      // OK as file system may not be Posix compliant
    }
  }
}
 
Example 15
Source File: DflCache.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
private int loadAndCheck(Path p, AuthTimeWithHash time,
        KerberosTime currTime)
        throws IOException, KrbApErrException {
    int missed = 0;
    if (Files.isSymbolicLink(p)) {
        throw new IOException("Symlink not accepted");
    }
    try {
        Set<PosixFilePermission> perms =
                Files.getPosixFilePermissions(p);
        if (uid != -1 &&
                (Integer)Files.getAttribute(p, "unix:uid") != uid) {
            throw new IOException("Not mine");
        }
        if (perms.contains(PosixFilePermission.GROUP_READ) ||
                perms.contains(PosixFilePermission.GROUP_WRITE) ||
                perms.contains(PosixFilePermission.GROUP_EXECUTE) ||
                perms.contains(PosixFilePermission.OTHERS_READ) ||
                perms.contains(PosixFilePermission.OTHERS_WRITE) ||
                perms.contains(PosixFilePermission.OTHERS_EXECUTE)) {
            throw new IOException("Accessible by someone else");
        }
    } catch (UnsupportedOperationException uoe) {
        // No POSIX permissions? Ignore it.
    }
    chan = Files.newByteChannel(p, StandardOpenOption.WRITE,
            StandardOpenOption.READ);

    long timeLimit = currTime.getSeconds() - readHeader(chan);

    long pos = 0;
    boolean seeNewButNotSame = false;
    while (true) {
        try {
            pos = chan.position();
            AuthTime a = AuthTime.readFrom(chan);
            if (a instanceof AuthTimeWithHash) {
                if (time.equals(a)) {
                    // Exact match, must be a replay
                    throw new KrbApErrException(Krb5.KRB_AP_ERR_REPEAT);
                } else if (time.isSameIgnoresHash(a)) {
                    // Two different authenticators in the same second.
                    // Remember it
                    seeNewButNotSame = true;
                }
            } else {
                if (time.isSameIgnoresHash(a)) {
                    // Two authenticators in the same second. Considered
                    // same if we haven't seen a new style version of it
                    if (!seeNewButNotSame) {
                        throw new KrbApErrException(Krb5.KRB_AP_ERR_REPEAT);
                    }
                }
            }
            if (a.ctime < timeLimit) {
                missed++;
            } else {
                missed--;
            }
        } catch (BufferUnderflowException e) {
            // Half-written file?
            chan.position(pos);
            break;
        }
    }
    return missed;
}
 
Example 16
Source File: DflCache.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
private int loadAndCheck(Path p, AuthTimeWithHash time,
        KerberosTime currTime)
        throws IOException, KrbApErrException {
    int missed = 0;
    if (Files.isSymbolicLink(p)) {
        throw new IOException("Symlink not accepted");
    }
    try {
        Set<PosixFilePermission> perms =
                Files.getPosixFilePermissions(p);
        if (uid != -1 &&
                (Integer)Files.getAttribute(p, "unix:uid") != uid) {
            throw new IOException("Not mine");
        }
        if (perms.contains(PosixFilePermission.GROUP_READ) ||
                perms.contains(PosixFilePermission.GROUP_WRITE) ||
                perms.contains(PosixFilePermission.GROUP_EXECUTE) ||
                perms.contains(PosixFilePermission.OTHERS_READ) ||
                perms.contains(PosixFilePermission.OTHERS_WRITE) ||
                perms.contains(PosixFilePermission.OTHERS_EXECUTE)) {
            throw new IOException("Accessible by someone else");
        }
    } catch (UnsupportedOperationException uoe) {
        // No POSIX permissions? Ignore it.
    }
    chan = Files.newByteChannel(p, StandardOpenOption.WRITE,
            StandardOpenOption.READ);

    long timeLimit = currTime.getSeconds() - readHeader(chan);

    long pos = 0;
    boolean seeNewButNotSame = false;
    while (true) {
        try {
            pos = chan.position();
            AuthTime a = AuthTime.readFrom(chan);
            if (a instanceof AuthTimeWithHash) {
                if (time.equals(a)) {
                    // Exact match, must be a replay
                    throw new KrbApErrException(Krb5.KRB_AP_ERR_REPEAT);
                } else if (time.isSameIgnoresHash(a)) {
                    // Two different authenticators in the same second.
                    // Remember it
                    seeNewButNotSame = true;
                }
            } else {
                if (time.isSameIgnoresHash(a)) {
                    // Two authenticators in the same second. Considered
                    // same if we haven't seen a new style version of it
                    if (!seeNewButNotSame) {
                        throw new KrbApErrException(Krb5.KRB_AP_ERR_REPEAT);
                    }
                }
            }
            if (a.ctime < timeLimit) {
                missed++;
            } else {
                missed--;
            }
        } catch (BufferUnderflowException e) {
            // Half-written file?
            chan.position(pos);
            break;
        }
    }
    return missed;
}
 
Example 17
Source File: DflCache.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
private int loadAndCheck(Path p, AuthTimeWithHash time,
        KerberosTime currTime)
        throws IOException, KrbApErrException {
    int missed = 0;
    if (Files.isSymbolicLink(p)) {
        throw new IOException("Symlink not accepted");
    }
    try {
        Set<PosixFilePermission> perms =
                Files.getPosixFilePermissions(p);
        if (uid != -1 &&
                (Integer)Files.getAttribute(p, "unix:uid") != uid) {
            throw new IOException("Not mine");
        }
        if (perms.contains(PosixFilePermission.GROUP_READ) ||
                perms.contains(PosixFilePermission.GROUP_WRITE) ||
                perms.contains(PosixFilePermission.GROUP_EXECUTE) ||
                perms.contains(PosixFilePermission.OTHERS_READ) ||
                perms.contains(PosixFilePermission.OTHERS_WRITE) ||
                perms.contains(PosixFilePermission.OTHERS_EXECUTE)) {
            throw new IOException("Accessible by someone else");
        }
    } catch (UnsupportedOperationException uoe) {
        // No POSIX permissions? Ignore it.
    }
    chan = Files.newByteChannel(p, StandardOpenOption.WRITE,
            StandardOpenOption.READ);

    long timeLimit = currTime.getSeconds() - readHeader(chan);

    long pos = 0;
    boolean seeNewButNotSame = false;
    while (true) {
        try {
            pos = chan.position();
            AuthTime a = AuthTime.readFrom(chan);
            if (a instanceof AuthTimeWithHash) {
                if (time.equals(a)) {
                    // Exact match, must be a replay
                    throw new KrbApErrException(Krb5.KRB_AP_ERR_REPEAT);
                } else if (time.isSameIgnoresHash(a)) {
                    // Two different authenticators in the same second.
                    // Remember it
                    seeNewButNotSame = true;
                }
            } else {
                if (time.isSameIgnoresHash(a)) {
                    // Two authenticators in the same second. Considered
                    // same if we haven't seen a new style version of it
                    if (!seeNewButNotSame) {
                        throw new KrbApErrException(Krb5.KRB_AP_ERR_REPEAT);
                    }
                }
            }
            if (a.ctime < timeLimit) {
                missed++;
            } else {
                missed--;
            }
        } catch (BufferUnderflowException e) {
            // Half-written file?
            chan.position(pos);
            break;
        }
    }
    return missed;
}
 
Example 18
Source File: DflCache.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
private int loadAndCheck(Path p, AuthTimeWithHash time,
        KerberosTime currTime)
        throws IOException, KrbApErrException {
    int missed = 0;
    if (Files.isSymbolicLink(p)) {
        throw new IOException("Symlink not accepted");
    }
    try {
        Set<PosixFilePermission> perms =
                Files.getPosixFilePermissions(p);
        if (uid != -1 &&
                (Integer)Files.getAttribute(p, "unix:uid") != uid) {
            throw new IOException("Not mine");
        }
        if (perms.contains(PosixFilePermission.GROUP_READ) ||
                perms.contains(PosixFilePermission.GROUP_WRITE) ||
                perms.contains(PosixFilePermission.GROUP_EXECUTE) ||
                perms.contains(PosixFilePermission.OTHERS_READ) ||
                perms.contains(PosixFilePermission.OTHERS_WRITE) ||
                perms.contains(PosixFilePermission.OTHERS_EXECUTE)) {
            throw new IOException("Accessible by someone else");
        }
    } catch (UnsupportedOperationException uoe) {
        // No POSIX permissions? Ignore it.
    }
    chan = Files.newByteChannel(p, StandardOpenOption.WRITE,
            StandardOpenOption.READ);

    long timeLimit = currTime.getSeconds() - readHeader(chan);

    long pos = 0;
    boolean seeNewButNotSame = false;
    while (true) {
        try {
            pos = chan.position();
            AuthTime a = AuthTime.readFrom(chan);
            if (a instanceof AuthTimeWithHash) {
                if (time.equals(a)) {
                    // Exact match, must be a replay
                    throw new KrbApErrException(Krb5.KRB_AP_ERR_REPEAT);
                } else if (time.isSameIgnoresHash(a)) {
                    // Two different authenticators in the same second.
                    // Remember it
                    seeNewButNotSame = true;
                }
            } else {
                if (time.isSameIgnoresHash(a)) {
                    // Two authenticators in the same second. Considered
                    // same if we haven't seen a new style version of it
                    if (!seeNewButNotSame) {
                        throw new KrbApErrException(Krb5.KRB_AP_ERR_REPEAT);
                    }
                }
            }
            if (a.ctime < timeLimit) {
                missed++;
            } else {
                missed--;
            }
        } catch (BufferUnderflowException e) {
            // Half-written file?
            chan.position(pos);
            break;
        }
    }
    return missed;
}
 
Example 19
Source File: DflCache.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
private int loadAndCheck(Path p, AuthTimeWithHash time,
        KerberosTime currTime)
        throws IOException, KrbApErrException {
    int missed = 0;
    if (Files.isSymbolicLink(p)) {
        throw new IOException("Symlink not accepted");
    }
    try {
        Set<PosixFilePermission> perms =
                Files.getPosixFilePermissions(p);
        if (uid != -1 &&
                (Integer)Files.getAttribute(p, "unix:uid") != uid) {
            throw new IOException("Not mine");
        }
        if (perms.contains(PosixFilePermission.GROUP_READ) ||
                perms.contains(PosixFilePermission.GROUP_WRITE) ||
                perms.contains(PosixFilePermission.GROUP_EXECUTE) ||
                perms.contains(PosixFilePermission.OTHERS_READ) ||
                perms.contains(PosixFilePermission.OTHERS_WRITE) ||
                perms.contains(PosixFilePermission.OTHERS_EXECUTE)) {
            throw new IOException("Accessible by someone else");
        }
    } catch (UnsupportedOperationException uoe) {
        // No POSIX permissions? Ignore it.
    }
    chan = Files.newByteChannel(p, StandardOpenOption.WRITE,
            StandardOpenOption.READ);

    long timeLimit = currTime.getSeconds() - readHeader(chan);

    long pos = 0;
    boolean seeNewButNotSame = false;
    while (true) {
        try {
            pos = chan.position();
            AuthTime a = AuthTime.readFrom(chan);
            if (a instanceof AuthTimeWithHash) {
                if (time.equals(a)) {
                    // Exact match, must be a replay
                    throw new KrbApErrException(Krb5.KRB_AP_ERR_REPEAT);
                } else if (time.isSameIgnoresHash(a)) {
                    // Two different authenticators in the same second.
                    // Remember it
                    seeNewButNotSame = true;
                }
            } else {
                if (time.isSameIgnoresHash(a)) {
                    // Two authenticators in the same second. Considered
                    // same if we haven't seen a new style version of it
                    if (!seeNewButNotSame) {
                        throw new KrbApErrException(Krb5.KRB_AP_ERR_REPEAT);
                    }
                }
            }
            if (a.ctime < timeLimit) {
                missed++;
            } else {
                missed--;
            }
        } catch (BufferUnderflowException e) {
            // Half-written file?
            chan.position(pos);
            break;
        }
    }
    return missed;
}
 
Example 20
Source File: DflCache.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
private int loadAndCheck(Path p, AuthTimeWithHash time,
        KerberosTime currTime)
        throws IOException, KrbApErrException {
    int missed = 0;
    if (Files.isSymbolicLink(p)) {
        throw new IOException("Symlink not accepted");
    }
    try {
        Set<PosixFilePermission> perms =
                Files.getPosixFilePermissions(p);
        if (uid != -1 &&
                (Integer)Files.getAttribute(p, "unix:uid") != uid) {
            throw new IOException("Not mine");
        }
        if (perms.contains(PosixFilePermission.GROUP_READ) ||
                perms.contains(PosixFilePermission.GROUP_WRITE) ||
                perms.contains(PosixFilePermission.GROUP_EXECUTE) ||
                perms.contains(PosixFilePermission.OTHERS_READ) ||
                perms.contains(PosixFilePermission.OTHERS_WRITE) ||
                perms.contains(PosixFilePermission.OTHERS_EXECUTE)) {
            throw new IOException("Accessible by someone else");
        }
    } catch (UnsupportedOperationException uoe) {
        // No POSIX permissions? Ignore it.
    }
    chan = Files.newByteChannel(p, StandardOpenOption.WRITE,
            StandardOpenOption.READ);

    long timeLimit = currTime.getSeconds() - readHeader(chan);

    long pos = 0;
    boolean seeNewButNotSame = false;
    while (true) {
        try {
            pos = chan.position();
            AuthTime a = AuthTime.readFrom(chan);
            if (a instanceof AuthTimeWithHash) {
                if (time.equals(a)) {
                    // Exact match, must be a replay
                    throw new KrbApErrException(Krb5.KRB_AP_ERR_REPEAT);
                } else if (time.isSameIgnoresHash(a)) {
                    // Two different authenticators in the same second.
                    // Remember it
                    seeNewButNotSame = true;
                }
            } else {
                if (time.isSameIgnoresHash(a)) {
                    // Two authenticators in the same second. Considered
                    // same if we haven't seen a new style version of it
                    if (!seeNewButNotSame) {
                        throw new KrbApErrException(Krb5.KRB_AP_ERR_REPEAT);
                    }
                }
            }
            if (a.ctime < timeLimit) {
                missed++;
            } else {
                missed--;
            }
        } catch (BufferUnderflowException e) {
            // Half-written file?
            chan.position(pos);
            break;
        }
    }
    return missed;
}