• mina86.com

  • Categories
  • Code
  • Contact
  • PSA: Creating world-unreadable files

    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-readable1 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 are 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.

    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.