PSA: Creating world-unreadable files

Posted by Michał ‘mina86’ Nazarewicz on 5th of February 2017

I’ve been reading tutorials on using key-files for disk encryption. Common approach for generating such files is to create it using something similar to head -c 4096 /dev/urandom >key-file and only then change it’s permissions (usually with a plain chmod 400 key-file) to prevent others from reading it.

Please, stop doing this and spreading that method. The correct way of achieving the effect is:

(umask 077; head -c 64 /dev/random >key-file)

Or if the file needs to be created as root while command is run by a different user:

sudo sh -c 'umask 077; head -c 64 /dev/random >key-file'

The first method creates the file as world-readable and before its permission are changed anyone can read it. The second method creates the file as readable only by its owner from the beginning thus preventing the secret disclosure.

This attack is possible even if data is written after permissions are tightened. For example in situation such as:

exec 3>key-file
chmod 400 key-file
head -c 64 /dev/random >&3
exec 3>&-

Changing file permissions does not affect existing file descriptors so if attacker opens the file prior to the invocation of chmod command they can keep it open and wait for the data to trickle in.

This may sound like a theoretical exercise which has no barring on reality but the proper way of doing things is so trivial there’s no reason not to go with it. Indeed, it’s actually shorter.

This does depend on various factors. For example whether the directory the file is created in has executable bit set. Some paranoid security-conscious users may already have umask set to 077 but beware that sudo resets it to the default 022.

PS. If anyone wonders while I also changed the key-file’s size from 4096 to measly 64 bytes I’ve explained it in another article.