I have a device I want to mount for root with full permissions and for everyone else as readonly.
sudo mkdir /root/mnt/foo
sudo mkdir /mnt/fooReadOnly
mount -oro /dev/sdaX /mnt/foo
- This ensures device /dev/sdaX is mounted readonly on /mnt/foo. I set this up first, because it is not possible to create a read-only bind mount in a single step. I don't want to let users access a read-write bind mount, even for an instant.
ls -ld /root - double-check this shows the mode
dr-xr-x--- and owner
sudo mount --bind /mnt/fooReadOnly /root/mnt/foo
sudo mount -oremount,rw /root/mnt/foo
Try the above commands. After each mount command, you can run
grep foo /proc/self/mountinfo, which shows the per-filesystem and per-mountpoint flags in separate columns.
To understand this, know that
mount -oremount,rw (or
mount -oremount,ro) changes both the per-filesystem flag and the per-mountpoint flag at the same time. But it does not affect the per-mountpoint flag of the other mount point(s).
It is not possible to try the above commands inside a user namespace (
unshare -rm), even if you switch to mounting a tmpfs instead of sdaX. It fails with "permission denied" at
mount -oremount,rw. Instead you would have to use the following sequence:
mount tmp -ttmpfs /root/mnt/foo
mount --bind /root/mnt/foo /root/mnt/fooReadOnly
mount -oremount,bind,ro /root/mnt/fooReadOnly
mount --bind /root/mnt/fooReadOnly /mnt/fooReadOnly
Also, how do I add this to /etc/fstab so that it will automatically remount on boot?
I would recommend not adapting the first sequence to fstab, because it is too much of a hack. You can adapt the second ordering instead.
/dev/sdaX /root/mnt/foo ...
/root/mnt/foo /root/mnt/fooReadOnly none bind,ro
/root/fooReadOnly /mnt/fooReadOnly none bind