java.nio.file.attribute.AclEntry Java Examples

The following examples show how to use java.nio.file.attribute.AclEntry. 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: TestVMOptionsFile.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static void makeFileNonReadable(String file) throws IOException {
    Path filePath = Paths.get(file);
    Set<String> supportedAttr = filePath.getFileSystem().supportedFileAttributeViews();

    if (supportedAttr.contains("posix")) {
        Files.setPosixFilePermissions(filePath, PosixFilePermissions.fromString("-w--w----"));
    } else if (supportedAttr.contains("acl")) {
        UserPrincipal fileOwner = Files.getOwner(filePath);

        AclFileAttributeView view = Files.getFileAttributeView(filePath, AclFileAttributeView.class);

        AclEntry entry = AclEntry.newBuilder()
                .setType(AclEntryType.DENY)
                .setPrincipal(fileOwner)
                .setPermissions(AclEntryPermission.READ_DATA)
                .build();

        List<AclEntry> acl = view.getAcl();
        acl.add(0, entry);
        view.setAcl(acl);
    }
}
 
Example #2
Source File: AclAttributeProviderTest.java    From jimfs with Apache License 2.0 6 votes vote down vote up
@Test
public void testView() throws IOException {
  AclFileAttributeView view =
      provider.view(
          fileLookup(),
          ImmutableMap.<String, FileAttributeView>of(
              "owner", new OwnerAttributeProvider().view(fileLookup(), NO_INHERITED_VIEWS)));
  assertNotNull(view);

  assertThat(view.name()).isEqualTo("acl");

  assertThat(view.getAcl()).isEqualTo(defaultAcl);

  view.setAcl(ImmutableList.<AclEntry>of());
  view.setOwner(FOO);

  assertThat(view.getAcl()).isEqualTo(ImmutableList.<AclEntry>of());
  assertThat(view.getOwner()).isEqualTo(FOO);

  assertThat(file.getAttribute("acl", "acl")).isEqualTo(ImmutableList.<AclEntry>of());
}
 
Example #3
Source File: PersistanceResourceTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private AclEntry createConfigurationAccessACLEntry(UserPrincipal user) {
    AclEntry entry = AclEntry
            .newBuilder()
            .setType(AclEntryType.ALLOW)
            .setPrincipal(user)
            .setPermissions(
                    AclEntryPermission.WRITE_NAMED_ATTRS,
                    AclEntryPermission.WRITE_DATA,
                    AclEntryPermission.WRITE_ATTRIBUTES,
                    AclEntryPermission.READ_ATTRIBUTES,
                    AclEntryPermission.APPEND_DATA,
                    AclEntryPermission.READ_DATA,
                    AclEntryPermission.READ_NAMED_ATTRS,
                    AclEntryPermission.READ_ACL,
                    AclEntryPermission.SYNCHRONIZE,
                    AclEntryPermission.DELETE)
            .setFlags(AclEntryFlag.FILE_INHERIT)
            .build();
    return entry;
}
 
Example #4
Source File: FilePersistenceUtils.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static List<FileAttribute<List<AclEntry>>> getAclAttributes(Path file) throws IOException {
    if (Files.exists(file) && supportsFileOwnerAttributeView(file, AclFileAttributeView.class)) {
        AclFileAttributeView aclView = Files.getFileAttributeView(file, AclFileAttributeView.class);
        if (aclView != null) {
            final List<AclEntry> entries = aclView.getAcl();
            return Collections.singletonList(new FileAttribute<List<AclEntry>>() {

                @Override
                public List<AclEntry> value() {
                    return entries;
                }

                @Override
                public String name() {
                    return "acl:acl";
                }

            });
        }
    }
    return Collections.emptyList();
}
 
Example #5
Source File: CliGitAPIImpl.java    From git-client-plugin with MIT License 6 votes vote down vote up
void fixSshKeyOnWindows(File key) throws GitException {
    if (launcher.isUnix()) return;

    Path file = Paths.get(key.toURI());

    AclFileAttributeView fileAttributeView = Files.getFileAttributeView(file, AclFileAttributeView.class);
    if (fileAttributeView == null) return;

    try {
        UserPrincipal userPrincipal = fileAttributeView.getOwner();
        AclEntry aclEntry = AclEntry.newBuilder()
            .setType(AclEntryType.ALLOW)
            .setPrincipal(userPrincipal)
            .setPermissions(ACL_ENTRY_PERMISSIONS)
            .build();
        fileAttributeView.setAcl(Collections.singletonList(aclEntry));
    } catch (IOException | UnsupportedOperationException e) {
        throw new GitException("Error updating file permission for \"" + key.getAbsolutePath() + "\"", e);
    }
}
 
Example #6
Source File: WindowsFilePermissionHelper.java    From hashicorp-vault-plugin with MIT License 6 votes vote down vote up
public static void fixSshKeyOnWindows(Path file) {
    AclFileAttributeView fileAttributeView = Files
        .getFileAttributeView(file, AclFileAttributeView.class);
    if (fileAttributeView == null) return;

    try {
        UserPrincipal userPrincipal = fileAttributeView.getOwner();
        AclEntry aclEntry = AclEntry.newBuilder()
            .setType(AclEntryType.ALLOW)
            .setPrincipal(userPrincipal)
            .setPermissions(ACL_ENTRY_PERMISSIONS)
            .build();
        fileAttributeView.setAcl(Collections.singletonList(aclEntry));
    } catch (IOException | UnsupportedOperationException e) {
        throw new IllegalStateException("Error updating file permission for \"" + file + "\"", e);
    }
}
 
Example #7
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 #8
Source File: AESKeyFileEncrypterFactory.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
private void makeKeyFileReadOnly(File file) throws IOException
{
    if(isPosixFileSystem(file))
    {
        Files.setPosixFilePermissions(file.toPath(), EnumSet.of(PosixFilePermission.OWNER_READ));
    }
    else if(isAclFileSystem(file))
    {
        AclFileAttributeView attributeView = Files.getFileAttributeView(file.toPath(), AclFileAttributeView.class);
        ArrayList<AclEntry> acls = new ArrayList<>(attributeView.getAcl());
        ListIterator<AclEntry> iter = acls.listIterator();
        file.setReadOnly();
        while(iter.hasNext())
        {
            AclEntry acl = iter.next();
            Set<AclEntryPermission> originalPermissions = acl.permissions();
            Set<AclEntryPermission> updatedPermissions = EnumSet.copyOf(originalPermissions);

            if(updatedPermissions.removeAll(EnumSet.of(AclEntryPermission.APPEND_DATA,
                                                       AclEntryPermission.DELETE,
                                                       AclEntryPermission.EXECUTE,
                                                       AclEntryPermission.WRITE_ACL,
                                                       AclEntryPermission.WRITE_DATA,
                                                       AclEntryPermission.WRITE_ATTRIBUTES,
                                                       AclEntryPermission.WRITE_NAMED_ATTRS,
                                                       AclEntryPermission.WRITE_OWNER)))
            {
                AclEntry.Builder builder = AclEntry.newBuilder(acl);
                builder.setPermissions(updatedPermissions);
                iter.set(builder.build());
            }
        }
        attributeView.setAcl(acls);
    }
    else
    {
        throw new IllegalArgumentException(ILLEGAL_ARG_EXCEPTION);
    }
}
 
Example #9
Source File: WindowsFilePermissionsTest.java    From hashicorp-vault-plugin with MIT License 5 votes vote down vote up
@Test
public void test_windows_file_permission_is_set_correctly() throws Exception {
    fixSshKeyOnWindows(file);
    assertEquals(1, fileAttributeView.getAcl().size());
    AclEntry aclEntry = fileAttributeView.getAcl().get(0);
    assertTrue(aclEntry.flags().isEmpty());
    assertEquals(ACL_ENTRY_PERMISSIONS, aclEntry.permissions());
    assertEquals(userPrincipal, aclEntry.principal());
    assertEquals(AclEntryType.ALLOW, aclEntry.type());
}
 
Example #10
Source File: WindowsFilePermissionsTest.java    From hashicorp-vault-plugin with MIT License 5 votes vote down vote up
@Test
public void test_windows_file_permission_are_incorrect() throws Exception {
    // By default files include System and builtin administrators
    assertNotSame(1, fileAttributeView.getAcl().size());
    for (AclEntry entry : fileAttributeView.getAcl()) {
        if (entry.principal().equals(userPrincipal)) {
            assertNotSame(ACL_ENTRY_PERMISSIONS, entry.permissions());
        }
    }
}
 
Example #11
Source File: CliGitAPIWindowsFilePermissionsTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Test
public void test_windows_file_permission_are_incorrect() throws Exception {
    // By default files include System and builtin administrators
    assertNotSame(1, fileAttributeView.getAcl().size());
    for (AclEntry entry : fileAttributeView.getAcl()) {
        if (entry.principal().equals(userPrincipal)) {
            assertNotSame(CliGitAPIImpl.ACL_ENTRY_PERMISSIONS, entry.permissions());
        }
    }
}
 
Example #12
Source File: CliGitAPIWindowsFilePermissionsTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Test
public void test_windows_file_permission_is_set_correctly() throws Exception {
    cliGit.fixSshKeyOnWindows(file);
    assertEquals(1, fileAttributeView.getAcl().size());
    AclEntry aclEntry = fileAttributeView.getAcl().get(0);
    assertTrue(aclEntry.flags().isEmpty());
    assertEquals(CliGitAPIImpl.ACL_ENTRY_PERMISSIONS, aclEntry.permissions());
    assertEquals(userPrincipal, aclEntry.principal());
    assertEquals(AclEntryType.ALLOW, aclEntry.type());
}
 
Example #13
Source File: Directories.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
private static void makeWritable(Path dir, boolean writable) throws IOException {
  FileStore fileStore = Files.getFileStore(dir);
  if (fileStore.supportsFileAttributeView("posix")) {
    if (writable) {
      Files.setPosixFilePermissions(dir, writablePerms);
    } else {
      Files.setPosixFilePermissions(dir, nonWritablePerms);
    }
  } else if (fileStore.supportsFileAttributeView("acl")) {
    // windows, we hope
    UserPrincipal authenticatedUsers =
        dir.getFileSystem()
            .getUserPrincipalLookupService()
            .lookupPrincipalByName("Authenticated Users");
    AclEntry entry =
        AclEntry.newBuilder()
            .setType(writable ? AclEntryType.ALLOW : AclEntryType.DENY)
            .setPrincipal(authenticatedUsers)
            .setPermissions(
                AclEntryPermission.DELETE,
                AclEntryPermission.DELETE_CHILD,
                AclEntryPermission.ADD_FILE,
                AclEntryPermission.ADD_SUBDIRECTORY)
            .build();

    AclFileAttributeView view = Files.getFileAttributeView(dir, AclFileAttributeView.class);
    List<AclEntry> acl = view.getAcl();
    acl.add(0, entry);
    view.setAcl(acl);
  } else {
    throw new UnsupportedOperationException("no recognized attribute view");
  }
}
 
Example #14
Source File: EvenMoreFiles.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
public static void setReadOnlyPerms(Path path, boolean executable) throws IOException {
  FileStore fileStore = Files.getFileStore(path);
  if (fileStore.supportsFileAttributeView("posix")) {
    if (executable) {
      Files.setPosixFilePermissions(path, readOnlyExecPerms);
    } else {
      Files.setPosixFilePermissions(path, readOnlyPerms);
    }
  } else if (fileStore.supportsFileAttributeView("acl")) {
    // windows, we hope
    UserPrincipal authenticatedUsers =
        path.getFileSystem()
            .getUserPrincipalLookupService()
            .lookupPrincipalByName("Authenticated Users");
    AclEntry denyWriteEntry =
        AclEntry.newBuilder()
            .setType(AclEntryType.DENY)
            .setPrincipal(authenticatedUsers)
            .setPermissions(AclEntryPermission.APPEND_DATA, AclEntryPermission.WRITE_DATA)
            .build();
    AclEntry execEntry =
        AclEntry.newBuilder()
            .setType(executable ? AclEntryType.ALLOW : AclEntryType.DENY)
            .setPrincipal(authenticatedUsers)
            .setPermissions(AclEntryPermission.EXECUTE)
            .build();

    AclFileAttributeView view = Files.getFileAttributeView(path, AclFileAttributeView.class);
    List<AclEntry> acl = view.getAcl();
    acl.add(0, execEntry);
    acl.add(0, denyWriteEntry);
    view.setAcl(acl);
  } else {
    throw new UnsupportedOperationException("no recognized attribute view");
  }
}
 
Example #15
Source File: PersistanceResourceTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Set<AclEntryPermission> getOwnerPermissions(Collection<AclEntry> entries, UserPrincipal owner) {
    Set<AclEntryPermission> set = new HashSet<>();
    for (AclEntry aclEntry : entries) {
        if (aclEntry.principal().equals(owner)) {
            Set<AclEntryPermission> permissions = aclEntry.permissions();
            for (AclEntryPermission aclEntryPermission : permissions) {
                set.add(aclEntryPermission);
            }
        }
    }
    return set;
}
 
Example #16
Source File: AclAttributeProvider.java    From jimfs with Apache License 2.0 5 votes vote down vote up
@Override
public ImmutableMap<String, ?> defaultValues(Map<String, ?> userProvidedDefaults) {
  Object userProvidedAcl = userProvidedDefaults.get("acl:acl");

  ImmutableList<AclEntry> acl = DEFAULT_ACL;
  if (userProvidedAcl != null) {
    acl = toAcl(checkType("acl", "acl", userProvidedAcl, List.class));
  }

  return ImmutableMap.of("acl:acl", acl);
}
 
Example #17
Source File: AclAttributeProvider.java    From jimfs with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked") // only cast after checking each element's type
private static ImmutableList<AclEntry> toAcl(List<?> list) {
  ImmutableList<?> copy = ImmutableList.copyOf(list);
  for (Object obj : copy) {
    if (!(obj instanceof AclEntry)) {
      throw new IllegalArgumentException(
          "invalid element for attribute 'acl:acl': should be List<AclEntry>, "
              + "found element of type "
              + obj.getClass());
    }
  }

  return (ImmutableList<AclEntry>) copy;
}
 
Example #18
Source File: FilePermissionSample.java    From cloud-search-samples with Apache License 2.0 4 votes vote down vote up
/**
 * Sample for mapping permissions from a source repository to Cloud Search
 * ACLs. In this example, NFS file system ACls are used as the source
 * permissions.
 *
 * @return Acl
 * @throws IOException if unable to read file permissions
 */
// [START cloud_search_nfs_acl]
static Acl mapNfsAclToCloudSearchAcl(Path pathToFile) throws IOException {
  // Id of the identity source for external user/group IDs. Shown here,
  // but may be omitted in the SDK as it is automatically applied
  // based on the `api.identitySourceId` configuration parameter.
  String identitySourceId = "abcdef12345";

  // Retrieve the file system ACLs
  AclFileAttributeView aclView = Files.getFileAttributeView(
      pathToFile,
      AclFileAttributeView.class,
      LinkOption.NOFOLLOW_LINKS);

  if (aclView == null) {
    // Can't read, return empty ACl
    return new Acl.Builder().build();
  }

  // Owner, for search quality and owner: filters
  // Note that for principals the name is not the primary
  // email address in Cloud Directory, but the local ID defined
  // by the OS. Users and groups must be referred to by their
  // external ID and mapped via an identity source. The SDK
  // will automatically prepend the identity source prefix based on
  // the `api.identitySourceId` configuration parameter.
  List<Principal> owners = Collections.singletonList(
      Acl.getUserPrincipal(aclView.getOwner().getName(), identitySourceId)
  );
  // Principals allowed to access item
  List<Principal> allowedReaders = new ArrayList<>();
  // Principals denied access to item
  List<Principal> deniedReaders = new ArrayList<>();

  for(AclEntry entry: aclView.getAcl()) {
    UserPrincipal fsPrincipal = entry.principal();
    Principal cloudSearchPrincipal = fsPrincipal instanceof GroupPrincipal ?
        Acl.getGroupPrincipal(fsPrincipal.getName(), identitySourceId) :
        Acl.getUserPrincipal(fsPrincipal.getName(), identitySourceId);
    if (entry.type() == AclEntryType.ALLOW) {
      allowedReaders.add(cloudSearchPrincipal);
    } else if (entry.type() == AclEntryType.DENY) {
      deniedReaders.add(cloudSearchPrincipal);
    }
  }

  // Build the Cloud Search ACL. Note that inheritance of permissions
  // from parents is omitted. See `setInheritFrom()` and `setInheritanceType()`
  // methods on the builder if required by your implementation.
  return new Acl.Builder()
      .setReaders(allowedReaders)
      .setDeniedReaders(deniedReaders)
      .setOwners(owners)
      .build();
}
 
Example #19
Source File: Server.java    From sftpserver with Apache License 2.0 4 votes vote down vote up
@Override
public void setFileAccessControl(final ServerSession session, final SftpSubsystemProxy subsystem,
		final Path file, final List<AclEntry> acl, final LinkOption... options) throws IOException {
	throw new UnsupportedOperationException("ACL set not supported");
}
 
Example #20
Source File: AclAttributeProvider.java    From jimfs with Apache License 2.0 4 votes vote down vote up
@Override
public void setAcl(List<AclEntry> acl) throws IOException {
  checkNotNull(acl);
  lookupFile().setAttribute("acl", "acl", ImmutableList.copyOf(acl));
}
 
Example #21
Source File: AclAttributeProvider.java    From jimfs with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public List<AclEntry> getAcl() throws IOException {
  return (List<AclEntry>) lookupFile().getAttribute("acl", "acl");
}
 
Example #22
Source File: LocalFilesystemConnector.java    From cloudsync with GNU General Public License v2.0 4 votes vote down vote up
private List<AclEntry> getLocalAclEntries(ItemType type, List<AclEntry> parentAclList, List<AclEntry> childAclList)
{
	List<AclEntry> aclList = new ArrayList<>();

	for (AclEntry childEntry : childAclList)
	{
		boolean found = false;
		for (AclEntry parentEntry : parentAclList)
		{
			if (!parentEntry.type().equals(childEntry.type())) continue;
			if (!parentEntry.principal().equals(childEntry.principal())) continue;
			if (!parentEntry.permissions().equals(childEntry.permissions())) continue;
			if (!parentEntry.flags().equals(childEntry.flags()))
			{
				if (parentEntry.flags().contains(AclEntryFlag.INHERIT_ONLY))
				{
					found = true;
					break;
				}
				else
				{
					if (type.equals(ItemType.FOLDER))
					{
						if (parentEntry.flags().contains(AclEntryFlag.DIRECTORY_INHERIT))
						{
							found = true;
							break;
						}
					}
					else
					{
						if (parentEntry.flags().contains(AclEntryFlag.FILE_INHERIT))
						{
							found = true;
							break;
						}
					}
				}
				continue;
			}
			found = true;
			break;
		}

		if (found) continue;

		// System.out.println("CHILD: "+childEntry.toString());
		/*
		 * System.out.println("\n\n");
		 * System.out.println("CHILD: "+childEntry.toString());
		 * 
		 * for(AclEntry parentEntry : parentAclList){
		 * 
		 * System.out.println("PARENT: "+parentEntry.toString()); }
		 * 
		 * System.out.println("\n\n");
		 */

		aclList.add(childEntry);
	}
	return aclList;
}
 
Example #23
Source File: LocalOperationHandlerTest.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void testCopy() throws Exception {
	super.testCopy();
	
	CloverURI source;
	CloverURI target;
	CopyResult result;
	
	source = relativeURI("W.TMP");
	if (manager.exists(source)) { // case insensitive file system
		target = relativeURI("w.tmp");
		result = manager.copy(source, target);
		assertFalse(result.success());
		assertTrue(manager.exists(source));
	}
	
	{
		// CLO-4658:
		source = relativeURI("unreadable.tmp");
		target = relativeURI("unreadable_destination/");
		manager.create(source);
		manager.create(target);
		File file = new File(source.getAbsoluteURI().getSingleURI().toURI());
		Path path = file.toPath();
		assertTrue(file.exists());
		if (!file.setReadable(false)) {
			AclFileAttributeView view = Files.getFileAttributeView(path, AclFileAttributeView.class);
			UserPrincipal owner = view.getOwner();
			List<AclEntry> acl = view.getAcl();
			for (ListIterator<AclEntry> it = acl.listIterator(); it.hasNext(); ) {
				AclEntry entry = it.next();
				if (entry.principal().equals(owner)) {
					Set<AclEntryPermission> permissions = entry.permissions();
					permissions.remove(AclEntryPermission.READ_DATA);
					AclEntry.Builder builder = AclEntry.newBuilder(entry);
					builder.setPermissions(permissions);
					it.set(builder.build());
					break;
				}
			}
			view.setAcl(acl);
		}
		assertFalse(Files.isReadable(path));
		result = manager.copy(source, target);
		assertFalse(result.success());
		assertFalse(manager.exists(relativeURI("unreadable_destination/unreadable.tmp")));
	}
	
}
 
Example #24
Source File: FileDataStoreFactory.java    From google-http-java-client with Apache License 2.0 4 votes vote down vote up
private static void setPermissionsToOwnerOnlyWindows(File file) throws IOException {
  Path path = Paths.get(file.getAbsolutePath());
  FileOwnerAttributeView fileAttributeView =
      Files.getFileAttributeView(path, FileOwnerAttributeView.class);
  UserPrincipal owner = fileAttributeView.getOwner();

  // get view
  AclFileAttributeView view = Files.getFileAttributeView(path, AclFileAttributeView.class);

  // All available entries
  Set<AclEntryPermission> permissions =
      ImmutableSet.of(
          AclEntryPermission.APPEND_DATA,
          AclEntryPermission.DELETE,
          AclEntryPermission.DELETE_CHILD,
          AclEntryPermission.READ_ACL,
          AclEntryPermission.READ_ATTRIBUTES,
          AclEntryPermission.READ_DATA,
          AclEntryPermission.READ_NAMED_ATTRS,
          AclEntryPermission.SYNCHRONIZE,
          AclEntryPermission.WRITE_ACL,
          AclEntryPermission.WRITE_ATTRIBUTES,
          AclEntryPermission.WRITE_DATA,
          AclEntryPermission.WRITE_NAMED_ATTRS,
          AclEntryPermission.WRITE_OWNER);

  // create ACL to give owner everything
  AclEntry entry =
      AclEntry.newBuilder()
          .setType(AclEntryType.ALLOW)
          .setPrincipal(owner)
          .setPermissions(permissions)
          .build();

  // Overwrite the ACL with only this permission
  try {
    view.setAcl(ImmutableList.of(entry));
  } catch (SecurityException ex) {
    throw new IOException("Unable to set permissions for " + file, ex);
  }
}
 
Example #25
Source File: AESKeyFileEncrypterFactory.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
private void checkFilePermissions(String fileLocation, File file) throws IOException
{
    if(isPosixFileSystem(file))
    {
        Set<PosixFilePermission> permissions = Files.getPosixFilePermissions(file.toPath());

        if (permissions.contains(PosixFilePermission.GROUP_READ)
                || permissions.contains(PosixFilePermission.OTHERS_READ)
                || permissions.contains(PosixFilePermission.GROUP_WRITE)
                || permissions.contains(PosixFilePermission.OTHERS_WRITE)) {
            throw new IllegalArgumentException("Key file '"
                    + fileLocation
                    + "' has incorrect permissions.  Only the owner "
                    + "should be able to read or write this file.");
        }
    }
    else if(isAclFileSystem(file))
    {
        AclFileAttributeView attributeView = Files.getFileAttributeView(file.toPath(), AclFileAttributeView.class);
        ArrayList<AclEntry> acls = new ArrayList<>(attributeView.getAcl());
        ListIterator<AclEntry> iter = acls.listIterator();
        UserPrincipal owner = Files.getOwner(file.toPath());
        while(iter.hasNext())
        {
            AclEntry acl = iter.next();
            if(acl.type() == AclEntryType.ALLOW)
            {
                Set<AclEntryPermission> originalPermissions = acl.permissions();
                Set<AclEntryPermission> updatedPermissions = EnumSet.copyOf(originalPermissions);


                if (updatedPermissions.removeAll(EnumSet.of(AclEntryPermission.APPEND_DATA,
                        AclEntryPermission.EXECUTE,
                        AclEntryPermission.WRITE_ACL,
                        AclEntryPermission.WRITE_DATA,
                        AclEntryPermission.WRITE_OWNER))) {
                    throw new IllegalArgumentException("Key file '"
                            + fileLocation
                            + "' has incorrect permissions.  The file should not be modifiable by any user.");
                }
                if (!owner.equals(acl.principal()) && updatedPermissions.removeAll(EnumSet.of(AclEntryPermission.READ_DATA))) {
                    throw new IllegalArgumentException("Key file '"
                            + fileLocation
                            + "' has incorrect permissions.  Only the owner should be able to read from the file.");
                }
            }
        }
    }
    else
    {
        throw new IllegalArgumentException(ILLEGAL_ARG_EXCEPTION);
    }
}