Linux Security – How to Prevent a Process from Writing Files

apparmorcapabilitieslinuxSecurityselinux

I want to run a command on Linux in a way that it cannot create or open any files to write. It should still be able to read files as normal (so an empty chroot is not an option), and still be able to write to files already open (especially stdout).

Bonus points if writing files to certain directories (i.e. the current directory) is still possible.

I’m looking for a solution that is process-local, i.e. does not involve configuring things like AppArmor or SELinux for the whole system, nor root privileges. It may involve installing their kernel modules, though.

I was looking at capabilities and these would have been nice and easy, if there were a capability for creating files. ulimit is another approach that would be convenient, if it covered this use case.

Best Answer

How about creating an empty chroot, then bind-mount the main filesystem as read-only inside the chroot?

Should probably be something like this to create a read-only bind-mount:

mount --bind /foo/ /path/to/chroot/
mount -o remount,ro /path/to/chroot/

You can bind-mount other directories which you want the jail to have write access to as well. Be careful if you need to bind-mount special directories (/dev/, /proc/, /sys/), mounting them as-is may be insecure.

Related Question