I'm writing a daemon that monitors something in the OS and flips execution permissions on a file in /run/ back and forth. The file has static contents and the file name is hardcoded in the daemon. I made the daemon run as root to make it able to write to /run/.
The daemon is supposed to be used on a large number of desktop Linux machines, so I want to make sure it's not exploitable. I'm not particularly concerned by DDoS attacks though because the daemon is not mission-critical. However, all the ways to make a file executable or not executable seem to have a security flaw.
Way #1: chmod() back and forth
Create the file and chmod()
it back and forth. I'm not fond with the idea because if an attacker manages to replace the file with a symlink to something else, an arbitrary file or folder will be chmod'ed into readability and possibly executability. The attacker would need root permissions for that, though.
Way #2: remove the file and atomically recreate it with open()
Delete the the file first and then atomically create a new one with the correct permissions using open(path, O_CREAT|O_WRONLY|O_TRUNC|O_EXCL, permissions)
, then write contents to the stream and close it. I like this one more because the only thing that can be exploited is removing a file with a hardcoded name by substituting the target directory with a symlink to some other directory, and if you can overwrite root dirs you should not need tricking daemons into removing a file with a hardcoded filename anyway.
What happens if the file gets deleted while the daemon is writing to stream in this case?
Is using g_remove() okay or shall I use unlink() only and abort if it fails?
Am I missing something or I'm just being paranoid and way #2 is secure enough?