Read-only bind mounts with systemd

I have a few bind mounts, in order to serve websites without forcing users to compromise their home directory permission security. However, it’s preferable to have these read-only, to prevent a rogue httpd from doing anything bad.

In order do make a bind mount read-only, you must mount it read-write and then remount it read-only. I used to do this in /etc/fstab by listing the mount twice, once with the bind option, the second with bind, remount and ro options. But this totally fails when systemd takes care of the mounting.

After searching and giving up a few times, I came across this page which explains how to do it.

The following instructions have to be applied to each mount.

First, declare the mount in /etc/fstab as usual:

/home/user/website_dir            /srv/http/website    none  bind            0 0

Then, create a systemd service to remount the bind read-only. Name it srv-http-website-mount-ro.service.

[Unit]
Description=remount /srv/http/website as read-only.
After=srv-http-website.mount

[Service]
Type=oneshot
ExecStart=/usr/bin/mount -o remount,ro /srv/http/website

[Install]
RequiredBy=srv-http-website.mount

The RequiredBy line refers to the systemd .mount that is auto-generated from /etc/fstab at boot.

Then install the new service:

# cp srv-http-website-mount-ro.service /etc/systemd/system
# systemctl daemon-reload
# systemctl enable srv-http-website-mount-ro.service