Bash – How to decrypt a file to use in another command without writing decrypted file to disk

bashio-redirection

I have a command (ansible-vault decrypt) that decrypts a file and writes it out. I can write it out to a file or to -/stdout.

I would then like to use this decrypted file (a private key) with another command that expects an argument like mycommand --key-file <path to file>.

My current script runs ansible-vault decrypt --output mykey.key to write the decrypted file to disk, then mycommand --key-file mykey.key, and finally deleting it with rm mykey.key.

Is there a way to somehow not write the decrypted file to disk at all, and still have mycommand be able to access it as if it was a file?

I can't pipe to the second command, because it doesn't read the key from stdin at all. The only thing I could think of is to create a ramdisk before running the commands, writing the key there, and unmounting the ramdisk once all commands have run which (I think) would make the decrypted key disappear without a trace.

Best Answer

If the command expects a file name, but doesn't care about the file type, you can pass the data through a pipe and specify /dev/stdin as the file name. /dev/stdin refers to the standard input.

ansible-vault decrypt | mycommand --key-file /dev/stdin

This won't work if mycommand doesn't accept a pipe (which usually happens if the program requires the file to be seekable). In that case, you will need to write the key to a temporary file.

Most Linux systems (and many other Unix variants) do have an in-memory filesystem out of the box. Where this filesystem is mounted and what permissions are required to use it depends on the distribution. Modern Linux systems have a tmpfs filesystem mounted at several locations, including /run. Normally every user gets a directory /run/user/1234 at login time where 1234 is their user ID. Many services create their own directory under /run, and /var/run is usually a symbolic link to /run. Check what is available on your system with df -t tmpfs.

Note that data written to a temporary filesystem can end up in swap. So can the content of memory. If the theft of your hard disk is a threat that you want to defend against, you must encrypt your swap. If you don't use hibernation, you can use a random key for the swap encryption which is generated at each boot and not stored anywhere.

Related Question