I want to safely write to a destination file (as root, unter common Linux'es) with "echo" (or catany other Bash built-in stuff) like this
echo "foo" > /destination/dir/filename
But the problem is that /destination/dir could be accessible for normal system users, so there is the risk of symlink conditions.
I read all the "how to" for preventing TOC-TOU stuff when using C, so NOT checking for symlink/remove it and open then (the common recommendations seems to be to open() with O_NOFOLLOW).
But all of this (access to kernel open() and it's flags) is not possible via Bash (or am I wrong?).
Then I got the idea of
- creating a tempfile with mktemp
- chown+chmod the tempfile appropriately
- write the contents to write to the tempfile
- move the tempfile to the destination dir with the Bash param "-T"
So as some Bash peudo-code (without error checking at some places)
TEMPFILE=$(mktemp) chown root:root $TEMPFILE chmod 0600 $TEMPFILE echo "contents" > $TEMPFILE mv -T $TEMPFILE /destination/dir/filename
I just tested it with "/destination/dir/filename" to be a symlink to a system file, but it worked: "mv" did move the tempfile correctly to the "filename", the symlink was removed (which is was I intended), no file was overwritten.
Is there anythink I missed out with regards to security/race conditions etc.?