qemu |9p

Mount share folder in QEMU with same permission as host

franzwong

Franz Wong

Posted on July 14, 2024

Mount share folder in QEMU with same permission as host

Background

I would like to share a folder between guest and host in QEMU. File permission should be the same as the user in host.

Solution

1. Create a folder called shared in host

mkdir -p shared
Enter fullscreen mode Exit fullscreen mode

2. Add a parameter virtfs when starting VM with QEMU

-virtfs local,path=shared,mount_tag=shared,security_model=mapped-xattr
Enter fullscreen mode Exit fullscreen mode

3. After the VM is started, login to the VM and create mount point

mkdir -p /mnt/shared
Enter fullscreen mode Exit fullscreen mode

4. Mount the folder

sudo mount -t 9p -o trans=virtio,version=9p2000.L shared /mnt/shared
Enter fullscreen mode Exit fullscreen mode

5. Check the permission of mount point

ls -l -d /mnt/shared
Enter fullscreen mode Exit fullscreen mode

It should be something like the following. On my host machine, my user ID is 501 and primary group ID is 20. (It's common setting in MacOS). In the guest VM, the group with ID 20 is called dialout. (You can check in /etc/group).

drwxr-xr-x 3 501 dialout 96 Jul 14 03:44 /mnt/shared
Enter fullscreen mode Exit fullscreen mode

However, my user in guest VM has uid 1000 and the primary group id is 1000 too. We need to make a mapping.

id
uid=1000(franz) gid=1000(dev_users) groups=1000(dev_users),27(sudo)
Enter fullscreen mode Exit fullscreen mode

6. Install bindfs in guest VM

sudo apt install -y bindfs
Enter fullscreen mode Exit fullscreen mode

7. Create the mapping

sudo bindfs --map=501/1000:@dialout/@1000 /mnt/shared /mnt/shared
Enter fullscreen mode Exit fullscreen mode

8. Check the permission of mount point again

ls -l -d /mnt/shared
Enter fullscreen mode Exit fullscreen mode

This time the permission is correct.

drwxr-xr-x 3 franz dev_users 96 Jul 14 03:44 /mnt/shared
Enter fullscreen mode Exit fullscreen mode

Or you can make it as a systemd service (.service). Because the mount point is duplicated, we can't create systemd mount (.mount).

1. Create a file /etc/systemd/system/bindfs_mnt_shared.service

[Unit]
Description=Map uid and gid of /mnt/shared with bindfs
Requires=mnt-shared.mount

[Service]
Type=forking
ExecStart=bindfs --map=501/1000:@20/@1000 /mnt/shared /mnt/shared

[Install]
WantedBy=multi-user.target
Enter fullscreen mode Exit fullscreen mode

2. Start and enable it.

sudo systemctl daemon-reload
sudo systemctl start bindfs_mnt_shared.service
sudo systemctl enable bindfs_mnt_shared.service
Enter fullscreen mode Exit fullscreen mode

References:
9p/virtfs share not writable

💖 💪 🙅 🚩
franzwong
Franz Wong

Posted on July 14, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related