1 <!-- subject: PSA: Creating world-unreadable files -->
2 <!-- date: 2017-02-05 20:35:55 -->
3 <!-- tags: linux, unix, chmod -->
4 <!-- categories: Articles, Techblog -->
6 <p>I’ve been reading tutorials on using key-files for disk encryption. Common
7 approach for generating such files is to create it using something similar
8 to
<code>head -c
4096 /dev/urandom
>key-file
</code> and only then change
9 it’s permissions (usually with a plain
<code>chmod
400 key-file
</code>) to
10 prevent others from reading it.
12 <p><em>Please
</em>, stop doing this and spreading that method. The correct way
13 of achieving the effect is:
15 <pre>(umask
077; head -c
64 /dev/random
>key-file)
</pre>
17 <p>Or if the file needs to be created as root while command is run by
20 <pre>sudo sh -c 'umask
077; head -c
64 /dev/random
>key-file'
</pre>
22 <p id=b1
>The first method creates the file as
23 world-readable
<a href=/self#f1
><sup>1</sup></a> and before its permission are
24 changed
<em>anyone
</em> can read it. The second method creates the file as
25 readable only by its owner from the beginning thus preventing the secret
30 <p>This attack is possible even if data are written after permissions are
31 tightened. For example in situation such as:
36 head -c
64 /dev/random
>&3
40 <p>Changing file permissions does not affect existing file descriptors
41 so if attacker opens the file prior to the invocation of
42 <code>chmod
</code> command they can keep it open and wait for the
45 <p>This may sound like a theoretical exercise which has no barring on
46 reality but the proper way of doing things is so trivial there’s no
47 reason not to go with it. Indeed, it’s actually
<em>shorter
</em>.
49 <p>PS. If anyone wonders while I also changed the key-file’s size from
4096 to
50 measly
64 bytes I’ve
<a href=
"/2017/key-file-size/">explained it in another
53 <p id=f1
><a href=#b1
>1</a> This does depend on various factors. For example
54 whether the directory the file is created in has executable bit set.
55 Some
<del>paranoid
</del> security-conscious users may already have
56 <code>umask
</code> set to
<code>077</code> but beware
57 that
<code>sudo
</code> resets it to the default
<code>022</code>.