copy control on USB

为了防止有人私自用U盘拷贝东西,设置U盘拷贝密码。

以root权限挂载U盘,并设置U盘访问权限为755。

Config

The main idea is to use udev to control the access of device.

udev-rules10-udev-copy-control.rules
1
2
3
KERNEL=="sd[b-z]", NAME="%k", SYMLINK="udisk", GROUP="root", OPTIONS="last_rule"
ACTION=="add", KERNEL=="sd[b-z][0-9]", RUN+="/bin/sh /utils/addUSBDev.sh %k", OPTIONS="last_rule"
ACTION=="remove", KERNEL=="sd[b-z][0-9]", RUN+="/bin/sh /utils/rmUSBDev.sh %k", OPTIONS="last_rule"

Use blkid to get device information, mainly the LABEL of the USB device.

addUSBDev.shaddUSBDev.sh
1
2
3
4
5
6
7
8
9
10
# Get device LABEL by blkid
str=$(blkid -s LABEL /dev/$1)
str=${str%\"*}
str=${str##*\"}
# create a mount point
mkdir -p /media/usb/$1/$str
# mount the usb device on /media/usb/
mount -t auto -o dmask=022 /dev/$1 /media/usb/$1/$str
rmUSBDev.shrmUSBDev.sh
1
2
3
4
5
6
7
8
# kill all processes using this device
fuser -km /media/usb/$1/*
# umount the device
umount /media/usb/$1/*
# clean the mount point
rmdir /media/usb/$1/* /media/usb/$1

Notes

Becareful with rmUSBDev.sh, whatever done in this script will not output any message on terminal, not generate any error or warming, and run as root.

Actually, the initial version use rm -rf /media/udisk to clean the work directory, when I modify it with rm -rf /media/%c and has error when execute the early RUN, it become rm -rf /media/, with the USB plugout, all disks mounted under /media/ are cleaned!!!