Search in sources :

Example 1 with AclFileAttributeView

use of java.nio.file.attribute.AclFileAttributeView in project derby by apache.

the class FileUtil method limitAccessToOwnerViaFileAttributeView.

/**
 * Limit access to owner using a
 * {@code java.nio.file.attribute.FileAttributeView}.
 * Such views are only available on Java 7 and higher, and only on
 * file systems that support changing file permissions. Currently,
 * this is supported on POSIX file systems and file systems that
 * maintain access control lists (ACLs).
 *
 * @param file the file to limit access to
 * @return {@code true} on success, or {@code false} if some of the
 * permissions could not be changed
 */
private static boolean limitAccessToOwnerViaFileAttributeView(File file) throws IOException {
    Path fileP = file.toPath();
    PosixFileAttributeView posixView = Files.getFileAttributeView(fileP, PosixFileAttributeView.class);
    if (posixView != null) {
        // This is a POSIX file system. Usually,
        // FileUtil.limitAccessToOwnerViaFile() will successfully set
        // the permissions on such file systems using the java.io.File
        // class, so we don't get here. If, however, that approach failed,
        // we try again here using a PosixFileAttributeView. That's likely
        // to fail too, but at least now we will get an IOException that
        // explains why it failed.
        EnumSet<PosixFilePermission> perms = EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE);
        if (file.isDirectory()) {
            perms.add(PosixFilePermission.OWNER_EXECUTE);
        }
        posixView.setPermissions(perms);
        return true;
    }
    AclFileAttributeView aclView = Files.getFileAttributeView(fileP, AclFileAttributeView.class);
    if (aclView != null) {
        // Since we have an AclFileAttributeView which is not a
        // PosixFileAttributeView, we probably have an NTFS file
        // system.
        // Remove existing ACEs, build a new one which simply
        // gives all possible permissions to current owner.
        AclEntry ace = AclEntry.newBuilder().setPrincipal(Files.getOwner(fileP)).setType(AclEntryType.ALLOW).setPermissions(EnumSet.allOf(AclEntryPermission.class)).build();
        aclView.setAcl(Collections.singletonList(ace));
        return true;
    }
    // We don't know how to set permissions on this file system.
    return false;
}
Also used : Path(java.nio.file.Path) AclFileAttributeView(java.nio.file.attribute.AclFileAttributeView) AclEntry(java.nio.file.attribute.AclEntry) PosixFilePermission(java.nio.file.attribute.PosixFilePermission) PosixFileAttributeView(java.nio.file.attribute.PosixFileAttributeView)

Example 2 with AclFileAttributeView

use of java.nio.file.attribute.AclFileAttributeView in project fess-crawler by codelibs.

the class FileSystemClient method getResponseData.

protected ResponseData getResponseData(final String uri, final boolean includeContent) {
    final ResponseData responseData = new ResponseData();
    try {
        responseData.setMethod(Constants.GET_METHOD);
        final String filePath = preprocessUri(uri);
        responseData.setUrl(filePath);
        File file = null;
        try {
            file = new File(new URI(filePath));
        } catch (final URISyntaxException e) {
            logger.warn("Could not parse url: " + filePath, e);
        }
        if (file == null) {
            responseData.setHttpStatusCode(Constants.NOT_FOUND_STATUS_CODE);
            responseData.setCharSet(charset);
            responseData.setContentLength(0);
        } else if (file.isFile()) {
            // check file size
            responseData.setContentLength(file.length());
            checkMaxContentLength(responseData);
            try {
                final FileOwnerAttributeView ownerAttrView = Files.getFileAttributeView(file.toPath(), FileOwnerAttributeView.class);
                if (ownerAttrView != null) {
                    UserPrincipal owner = ownerAttrView.getOwner();
                    if (owner != null) {
                        responseData.addMetaData(FS_FILE_USER, owner.getName());
                    }
                }
            } catch (Exception e) {
                logger.warn("Failed to parse FileOwnerAttributeView.", e);
            }
            try {
                final AclFileAttributeView aclView = Files.getFileAttributeView(file.toPath(), AclFileAttributeView.class);
                if (aclView != null) {
                    responseData.addMetaData(FILE_ATTRIBUTE_VIEW, aclView);
                    responseData.addMetaData(FS_FILE_GROUPS, aclView.getAcl().stream().map(acl -> acl.principal().getName()).toArray(n -> new String[n]));
                }
            } catch (Exception e) {
                logger.warn("Failed to parse AclFileAttributeView.", e);
            }
            try {
                final PosixFileAttributeView posixView = Files.getFileAttributeView(file.toPath(), PosixFileAttributeView.class);
                if (posixView != null) {
                    responseData.addMetaData(FILE_ATTRIBUTE_VIEW, posixView);
                    responseData.addMetaData(FS_FILE_GROUPS, new String[] { posixView.readAttributes().group().getName() });
                }
            } catch (Exception e) {
                logger.warn("Failed to parse PosixFileAttributeView.", e);
            }
            responseData.setHttpStatusCode(Constants.OK_STATUS_CODE);
            responseData.setCharSet(geCharSet(file));
            responseData.setLastModified(new Date(file.lastModified()));
            if (file.canRead()) {
                final MimeTypeHelper mimeTypeHelper = crawlerContainer.getComponent("mimeTypeHelper");
                try (final InputStream is = new BufferedInputStream(new FileInputStream(file))) {
                    responseData.setMimeType(mimeTypeHelper.getContentType(is, file.getName()));
                } catch (final Exception e) {
                    responseData.setMimeType(mimeTypeHelper.getContentType(null, file.getName()));
                }
                if (contentLengthHelper != null) {
                    final long maxLength = contentLengthHelper.getMaxLength(responseData.getMimeType());
                    if (responseData.getContentLength() > maxLength) {
                        throw new MaxLengthExceededException("The content length (" + responseData.getContentLength() + " byte) is over " + maxLength + " byte. The url is " + filePath);
                    }
                }
                if (includeContent) {
                    if (file.length() < maxCachedContentSize) {
                        try (InputStream contentStream = new BufferedInputStream(new FileInputStream(file))) {
                            responseData.setResponseBody(InputStreamUtil.getBytes(contentStream));
                        } catch (final Exception e) {
                            logger.warn("I/O Exception.", e);
                            responseData.setHttpStatusCode(Constants.SERVER_ERROR_STATUS_CODE);
                        }
                    } else {
                        responseData.setResponseBody(file, false);
                    }
                }
            } else {
                // Forbidden
                responseData.setHttpStatusCode(Constants.FORBIDDEN_STATUS_CODE);
                responseData.setMimeType(APPLICATION_OCTET_STREAM);
            }
        } else if (file.isDirectory()) {
            final Set<RequestData> requestDataSet = new HashSet<>();
            if (includeContent) {
                final File[] files = file.listFiles();
                if (files != null) {
                    for (final File f : files) {
                        final String chileUri = f.toURI().toASCIIString();
                        requestDataSet.add(RequestDataBuilder.newRequestData().get().url(chileUri).build());
                    }
                }
            }
            throw new ChildUrlsException(requestDataSet, this.getClass().getName() + "#getResponseData");
        } else {
            responseData.setHttpStatusCode(Constants.NOT_FOUND_STATUS_CODE);
            responseData.setCharSet(charset);
            responseData.setContentLength(0);
        }
    } catch (final CrawlerSystemException e) {
        CloseableUtil.closeQuietly(responseData);
        throw e;
    } catch (final Exception e) {
        CloseableUtil.closeQuietly(responseData);
        throw new CrawlingAccessException("Could not access " + uri, e);
    }
    return responseData;
}
Also used : FileOwnerAttributeView(java.nio.file.attribute.FileOwnerAttributeView) CrawlingAccessException(org.codelibs.fess.crawler.exception.CrawlingAccessException) BufferedInputStream(java.io.BufferedInputStream) Date(java.util.Date) URISyntaxException(java.net.URISyntaxException) PosixFileAttributeView(java.nio.file.attribute.PosixFileAttributeView) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MaxLengthExceededException(org.codelibs.fess.crawler.exception.MaxLengthExceededException) CrawlerSystemException(org.codelibs.fess.crawler.exception.CrawlerSystemException) AbstractCrawlerClient(org.codelibs.fess.crawler.client.AbstractCrawlerClient) HashSet(java.util.HashSet) UserPrincipal(java.nio.file.attribute.UserPrincipal) URI(java.net.URI) ContentLengthHelper(org.codelibs.fess.crawler.helper.ContentLengthHelper) MimeTypeHelper(org.codelibs.fess.crawler.helper.MimeTypeHelper) InputStreamUtil(org.codelibs.core.io.InputStreamUtil) AclFileAttributeView(java.nio.file.attribute.AclFileAttributeView) Logger(org.slf4j.Logger) Files(java.nio.file.Files) Resource(javax.annotation.Resource) StringUtil(org.codelibs.core.lang.StringUtil) Set(java.util.Set) FileInputStream(java.io.FileInputStream) FileOwnerAttributeView(java.nio.file.attribute.FileOwnerAttributeView) CrawlerContainer(org.codelibs.fess.crawler.container.CrawlerContainer) File(java.io.File) CloseableUtil(org.codelibs.core.io.CloseableUtil) Constants(org.codelibs.fess.crawler.Constants) URLEncoder(java.net.URLEncoder) RequestData(org.codelibs.fess.crawler.entity.RequestData) AccessTimeoutTarget(org.codelibs.fess.crawler.client.AccessTimeoutTarget) TimeoutManager(org.codelibs.core.timer.TimeoutManager) TimeoutTask(org.codelibs.core.timer.TimeoutTask) ChildUrlsException(org.codelibs.fess.crawler.exception.ChildUrlsException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) RequestDataBuilder(org.codelibs.fess.crawler.builder.RequestDataBuilder) InputStream(java.io.InputStream) ResponseData(org.codelibs.fess.crawler.entity.ResponseData) ChildUrlsException(org.codelibs.fess.crawler.exception.ChildUrlsException) AclFileAttributeView(java.nio.file.attribute.AclFileAttributeView) MaxLengthExceededException(org.codelibs.fess.crawler.exception.MaxLengthExceededException) CrawlingAccessException(org.codelibs.fess.crawler.exception.CrawlingAccessException) MimeTypeHelper(org.codelibs.fess.crawler.helper.MimeTypeHelper) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ResponseData(org.codelibs.fess.crawler.entity.ResponseData) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) UserPrincipal(java.nio.file.attribute.UserPrincipal) CrawlingAccessException(org.codelibs.fess.crawler.exception.CrawlingAccessException) URISyntaxException(java.net.URISyntaxException) MaxLengthExceededException(org.codelibs.fess.crawler.exception.MaxLengthExceededException) CrawlerSystemException(org.codelibs.fess.crawler.exception.CrawlerSystemException) ChildUrlsException(org.codelibs.fess.crawler.exception.ChildUrlsException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Date(java.util.Date) FileInputStream(java.io.FileInputStream) PosixFileAttributeView(java.nio.file.attribute.PosixFileAttributeView) BufferedInputStream(java.io.BufferedInputStream) RequestData(org.codelibs.fess.crawler.entity.RequestData) CrawlerSystemException(org.codelibs.fess.crawler.exception.CrawlerSystemException) File(java.io.File) HashSet(java.util.HashSet)

Example 3 with AclFileAttributeView

use of java.nio.file.attribute.AclFileAttributeView in project neo4j by neo4j.

the class ConfigTest method shouldNotEvaluateWithIncorrectFilePermission.

@Test
void shouldNotEvaluateWithIncorrectFilePermission() throws IOException {
    assumeUnixOrWindows();
    Path confFile = testDirectory.file("test.conf");
    Files.createFile(confFile);
    Files.write(confFile, List.of(TestSettings.intSetting.name() + "=$(foo bar)"));
    if (IS_OS_WINDOWS) {
        AclFileAttributeView attrs = Files.getFileAttributeView(confFile, AclFileAttributeView.class);
        attrs.setAcl(List.of(AclEntry.newBuilder().setType(AclEntryType.ALLOW).setPrincipal(attrs.getOwner()).setPermissions(AclEntryPermission.READ_DATA, AclEntryPermission.WRITE_DATA, AclEntryPermission.READ_ATTRIBUTES, AclEntryPermission.WRITE_ATTRIBUTES, AclEntryPermission.READ_NAMED_ATTRS, AclEntryPermission.WRITE_NAMED_ATTRS, AclEntryPermission.APPEND_DATA, AclEntryPermission.READ_ACL, AclEntryPermission.SYNCHRONIZE, AclEntryPermission.EXECUTE).build()));
    } else {
        setPosixFilePermissions(confFile, PosixFilePermissions.fromString("rw-----w-"));
    }
    // Given
    Config.Builder builder = Config.newBuilder().allowCommandExpansion().addSettingsClass(TestSettings.class).fromFile(confFile);
    // Then
    String msg = assertThrows(IllegalArgumentException.class, builder::build).getMessage();
    String expectedErrorMessage = IS_OS_WINDOWS ? "does not have the correct ACL for owner" : "does not have the correct file permissions";
    assertThat(msg).contains(expectedErrorMessage);
}
Also used : Path(java.nio.file.Path) AclFileAttributeView(java.nio.file.attribute.AclFileAttributeView) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 4 with AclFileAttributeView

use of java.nio.file.attribute.AclFileAttributeView in project che by eclipse.

the class WindowsSshScript method protectPrivateKeyFile.

@Override
protected void protectPrivateKeyFile(File sshKey) throws ServerException {
    try {
        AclFileAttributeView attributes = Files.getFileAttributeView(sshKey.toPath(), AclFileAttributeView.class);
        AclEntry.Builder builder = AclEntry.newBuilder();
        builder.setType(ALLOW);
        String ownerName = System.getProperty(OWNER_NAME_PROPERTY);
        UserPrincipal userPrincipal = FileSystems.getDefault().getUserPrincipalLookupService().lookupPrincipalByName(ownerName);
        builder.setPrincipal(userPrincipal);
        builder.setPermissions(READ_DATA, APPEND_DATA, READ_NAMED_ATTRS, READ_ATTRIBUTES, DELETE, READ_ACL, SYNCHRONIZE);
        AclEntry entry = builder.build();
        List<AclEntry> aclEntryList = new ArrayList<>();
        aclEntryList.add(entry);
        attributes.setAcl(aclEntryList);
    } catch (IOException e) {
        throw new ServerException("Failed to set file permissions");
    }
}
Also used : ServerException(org.eclipse.che.api.core.ServerException) AclFileAttributeView(java.nio.file.attribute.AclFileAttributeView) AclEntry(java.nio.file.attribute.AclEntry) ArrayList(java.util.ArrayList) IOException(java.io.IOException) UserPrincipal(java.nio.file.attribute.UserPrincipal)

Example 5 with AclFileAttributeView

use of java.nio.file.attribute.AclFileAttributeView in project qpid-broker-j by apache.

the class AESKeyFileEncrypterFactory method createEmptyKeyFile.

private void createEmptyKeyFile(File file) throws IOException {
    final Path parentFilePath = file.getAbsoluteFile().getParentFile().toPath();
    if (isPosixFileSystem(file)) {
        Set<PosixFilePermission> ownerOnly = EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE, PosixFilePermission.OWNER_EXECUTE);
        Files.createDirectories(parentFilePath, PosixFilePermissions.asFileAttribute(ownerOnly));
        Files.createFile(file.toPath(), PosixFilePermissions.asFileAttribute(EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE)));
    } else if (isAclFileSystem(file)) {
        Files.createDirectories(parentFilePath);
        final UserPrincipal owner = Files.getOwner(parentFilePath);
        AclFileAttributeView attributeView = Files.getFileAttributeView(parentFilePath, AclFileAttributeView.class);
        List<AclEntry> acls = new ArrayList<>(attributeView.getAcl());
        ListIterator<AclEntry> iter = acls.listIterator();
        boolean found = false;
        while (iter.hasNext()) {
            AclEntry acl = iter.next();
            if (!owner.equals(acl.principal())) {
                iter.remove();
            } else if (acl.type() == AclEntryType.ALLOW) {
                found = true;
                AclEntry.Builder builder = AclEntry.newBuilder(acl);
                Set<AclEntryPermission> permissions = acl.permissions().isEmpty() ? new HashSet<AclEntryPermission>() : EnumSet.copyOf(acl.permissions());
                permissions.addAll(Arrays.asList(AclEntryPermission.ADD_FILE, AclEntryPermission.ADD_SUBDIRECTORY, AclEntryPermission.LIST_DIRECTORY));
                builder.setPermissions(permissions);
                iter.set(builder.build());
            }
        }
        if (!found) {
            AclEntry.Builder builder = AclEntry.newBuilder();
            builder.setPermissions(AclEntryPermission.ADD_FILE, AclEntryPermission.ADD_SUBDIRECTORY, AclEntryPermission.LIST_DIRECTORY);
            builder.setType(AclEntryType.ALLOW);
            builder.setPrincipal(owner);
            acls.add(builder.build());
        }
        attributeView.setAcl(acls);
        Files.createFile(file.toPath(), new FileAttribute<List<AclEntry>>() {

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

            @Override
            public List<AclEntry> value() {
                AclEntry.Builder builder = AclEntry.newBuilder();
                builder.setType(AclEntryType.ALLOW);
                builder.setPermissions(EnumSet.allOf(AclEntryPermission.class));
                builder.setPrincipal(owner);
                return Collections.singletonList(builder.build());
            }
        });
    } else {
        throw new IllegalArgumentException("Unable to determine a mechanism to protect access to the key file on this filesystem");
    }
}
Also used : Path(java.nio.file.Path) AclFileAttributeView(java.nio.file.attribute.AclFileAttributeView) AclEntry(java.nio.file.attribute.AclEntry) AclEntryPermission(java.nio.file.attribute.AclEntryPermission) PosixFilePermission(java.nio.file.attribute.PosixFilePermission) ListIterator(java.util.ListIterator) UserPrincipal(java.nio.file.attribute.UserPrincipal) ArrayList(java.util.ArrayList) List(java.util.List) FileAttribute(java.nio.file.attribute.FileAttribute)

Aggregations

AclFileAttributeView (java.nio.file.attribute.AclFileAttributeView)7 Path (java.nio.file.Path)3 AclEntry (java.nio.file.attribute.AclEntry)3 UserPrincipal (java.nio.file.attribute.UserPrincipal)3 IOException (java.io.IOException)2 PosixFileAttributeView (java.nio.file.attribute.PosixFileAttributeView)2 PosixFilePermission (java.nio.file.attribute.PosixFilePermission)2 ArrayList (java.util.ArrayList)2 BufferedInputStream (java.io.BufferedInputStream)1 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1 InputStream (java.io.InputStream)1 UncheckedIOException (java.io.UncheckedIOException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 URI (java.net.URI)1 URISyntaxException (java.net.URISyntaxException)1 URLEncoder (java.net.URLEncoder)1 Files (java.nio.file.Files)1 AclEntryPermission (java.nio.file.attribute.AclEntryPermission)1 FileAttribute (java.nio.file.attribute.FileAttribute)1