bzip2recover: create output block files safely with O_EXCL
bzip2recover writes each recovered block to a file whose name is fully
predictable ("recNNNNN" + basename of the input, e.g. rec00001foo.bz2)
and which is created in the directory of the input file. The output
file was opened with a plain fopen(outFileName, "wb"), which follows
symbolic links and truncates whatever it finds.
If the input file lives in a directory that an attacker can write to
(a shared spool/incoming directory, or any directory whose path the
attacker supplied), the attacker can pre-create a symlink at the
predictable output name pointing at an arbitrary file. When the victim
runs bzip2recover, the plain fopen follows that symlink and overwrites
the target (CWE-59). Existing regular files are likewise clobbered,
and the files are created with lax umask permissions.
The main bzip2 tool already guards against this in fopen_output_safely()
by creating output files with open(O_WRONLY|O_CREAT|O_EXCL, S_IWUSR|
S_IRUSR); bzip2recover was never given the same treatment. Add a small
fopenOutputSafely() helper mirroring that function and use it for the
block files: O_EXCL makes the create fail rather than follow a symlink
or overwrite an existing file, and the mode creates the file 0600.
Non-Unix builds keep the previous fopen behaviour.
Signed-off-by: Naveed Khan <naveed@digiscrypt.com>
1 file changed