Dropping privileges
If you’re writing a tool that takes untrusted input, and you should treat almost all input as untrusted, then it’s a good idea to add a layer of defense against bugs in your code.
What good is a buffer overflow, if the process is fully sandboxed?
This applies to both processes running as root, and as normal users. Though there are some differences.
Standard POSIX
In POSIX you can only sandbox if you are root. The filesystem can be
hidden with chroot(), and you can then change user to be non-root
using setuid() and setgid().
There have been ways to break out of a chroot() jail, but if you
make sure to drop root privileges then chroot() is pretty effective
at preventing opening new files and running any new programs.
But which directory? Ideally you want it to be:
- read-only by the process (after dropping root)
- empty
- not shared by any other process that might write to it
The best way no ensure this is probably to create a temporary directory yourself, owned by root.
This is pretty tricky to do, though:
// Return 0 on success.
int do_chroot()
{
const char* tmpdir = getenv("TMPDIR");
if (tmpdir == NULL) Continue reading










