Video in progress

Strong Middle 📁 IO and NIO

When writing a secret key or token file to disk, how do you set the permissions correctly?

Creating the file first and then calling setPosixFilePermissions leaves it open to others in between. The right way is to give the permissions at creation time: Files.createFile(path, PosixFilePermissions.asFileAttribute(...)) or an attribute on newByteChannel. The umask affects the result too.

📖 Answer

The wrong sequence:

Files.writeString(keyFile, secret);                       // 0644: everyone can read it
Files.setPosixFilePermissions(keyFile, PosixFilePermissions.fromString("rw-------"));

Between the two lines the file is briefly open to other users. If another process opens it in that window, the later permission change does not close it: the descriptor is already held.

The right way:

var perms = PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------"));
try (SeekableByteChannel ch = Files.newByteChannel(keyFile,
        EnumSet.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE), perms)) {
    ch.write(ByteBuffer.wrap(secret.getBytes(StandardCharsets.UTF_8)));
}

CREATE_NEW matters: if the file already exists (perhaps someone created it ahead of time with different permissions), the attribute is not applied. It is better to get an error than to end up writing into someone else's file.

Other things to know:

  • the permissions at creation are trimmed by the process's umask. For rw------- that is not a problem, but if you want to give the group rw-rw---- and the umask is 027, the result is rw-r-----. If you need an exact value, also call setPosixFilePermissions after creation;
  • Files.createTempFile already creates with rw------- on POSIX systems;
  • Windows has no POSIX attributes: UnsupportedOperationException. There you need AclFileAttributeView. You can check ahead of time with Files.getFileStore(dir).supportsFileAttributeView("posix");
  • with atomic replacement (tmp + rename), the permissions are set on the temporary file, because rename doesn't change permissions.

In a container, secrets usually arrive through a Kubernetes Secret volume and the permissions are set with defaultMode. If your code doesn't write the file itself, even better.