Ubuntu – Creating disk images as a normal user

loop-devicemountpermissions

I want to be able to run the following script as normal user (as root it runs fine):

#!/bin/sh

dd if=/dev/zero bs=8192 count=128 of=disk.img
mkfs -t ext2 -F disk.img
losetup /dev/loop0 disk.img
mount /dev/loop0
echo aaaa > /mnt/aa
umount /mnt
losetup -d /dev/loop0

To that end, I

1) added appropriate entry to /etc/fstab (only then normal user can run 'mount /dev/loop0' ):

/dev/loop0  /mnt  ext2    defaults,loop,users,noauto      0 0

2) added the user in question to the 'disk' group (only then the user is able to run 'losetup' – /dev/loop0 is owned by the 'disk' group)

Now, hopefully the last problem is that when I run as normal user, I get 'permission denied' error from 'echo'. No wonder, because after mounting, the permissions of the /mnt directory change to 755 root:root, and obviously a normal user cannot create files inside.

How should I create my 'disk.img' so that when mounted it is writeable by the very user that created it?

Edit:

The proposed 'pmount' solution appears to have the same problem. Reproduction steps:

1) install 'pmount' and add '/dev/loop0' to /etc/pmount.allow

2) run the following as a normal user:

#!/bin/sh

dd if=/dev/zero bs=8192 count=128 of=disk.img
mkfs -t ext2 -F disk.img
losetup /dev/loop0 disk.img
pmount -w /dev/loop0
echo aaaa > /media/loop0/aa
pumount /media/loop0
losetup -d /dev/loop0

You will still get 'permission denied' from echo for the same reason we got it before – the permissions of the /media/loop0/ directory are 755:

[user@server test]$ ls -l /media/
total 1
drwxr-xr-x 3 root root 1024 Jul 22 13:40 loop0
[user@server test]$ ls -l /media/loop0/
total 12
drwx------ 2 root root 12288 Jul 22 13:40 lost+found

Edit2:

I managed to solve this – option 'root_owner' to mkfs.ext3 comes in handy:

#!/bin/sh

WHOAMI=`whoami`

uid=$(id -u $WHOAMI)
gid=$(id -g $WHOAMI)

dd if=/dev/zero bs=8192 count=128 of=disk.img
mkfs.ext3 -E root_owner=$uid:$gid disk.img
losetup /dev/loop0 disk.img
mount /dev/loop0
echo aaaa > /mnt/aa
umount /mnt
losetup -d /dev/loop0

Then after mounting the mountpoint is owned by the user who is running the script, and then the user is able to write inside 🙂

Best Answer

Use pmount instead of mount.

pmount ("policy mount") is a wrapper around the standard mount program which permits normal users to mount removable devices without a matching /etc/fstab entry.

Probably want the ...

-w, --read-write

Force the device to be mounted read/write. If neither -r nor -w is specified, the kernel will choose an appropriate default.

So you can drop the fstab entry and do not need to add the user to the disk group.

It allows mounting anywhere under /media/ if the device is listed in /etc/pmount.allow so it will also solve any permissions problems.

Related Question