Single process accessible temporary file

filesprocesstmp

I want to create a file that is only accessible to the process that created it (and potentially its children), and that disappears when the process exits, ideally never persisting the file to disk. As an example, I want to create /mylocation/myfile.txt, where that file can only be read from the current process, but not any other processes, even from the same user. I am happy to use some magic location other than /mylocation, e.g. somewhere under /prod/PID, but it needs to work for any filename.

The background is that I am using an existing library which reads a password from $FOO/mypassword. Several processes are running under the same user account, but have different secret passwords. I wish to communicate the password to the library securely from the other processes. I appreciate the ideal solutions would user different user accounts or have the library not read the password from a file, but I do not have control over either of those aspects.

Best Answer

Well, it depends on what you mean by "file" and how exactly the library accesses it. Here are a few approaches (both kluges) that come to mind:

  1. Use a temporary file, in the normal mkstemp meaning. mkstemp returns a file descriptor number to an unlinked file. You can then create $FOO/mypasswd as a symlink to /proc/self/fd/returned_number. There is a small window where the file exists (between open and unlink), and something else running as the same user could open it, and hold the file descriptor to later read the password. You can be sure it'll not be written to disk if your temporary directory is on a tmpfs.
  2. If it doesn't need to seek the password file, use pipe/pipe2 to create your file descriptors, then proceed as above with the symlink. You'll need to fork a child process to handle feeding the password to the pipe.
  3. You can probably abuse FUSE to do this.
  4. You could use LD_PRELOAD (or other dynamic linker tricks) to "fix" the library by intercepting the open/read/close, and feed it the password from somewhere sane.

None of these are really secure from other processes. Other processes running as the same user could, for example, ptrace your process and read the password directly out of memory.

Related Question