How can we write a UDEV rule that would allow read of USB/removable drives/flash drives but restrict write access in CentOS/RHEL? At the same time, the access to USB keyboard and mouse should work properly.
Please use following steps to configure udev rule which would automatically switch the USB disks to read-only mode when connected to the system:
1. Install the hdparm utility which could be used to set read-only/read-write access to the disks:
# yum install hdparm
Refer below post on disabling write access to USB devices using “hdparm”.
2. Lets create the UDEV rule to disable write access and only permit read access on USB. Create a udev rule file /etc/udev/rules.d/99-usb-disk.rules file with hdparm command to enable/disable write access to the usb disk:
# vi /etc/udev/rules.d/99-usb-disk.rules ACTION=="add", KERNEL=="sd*", DRIVERS=="usb", RUN+="/sbin/hdparm -r1 /dev/%k" ACTION=="remove", KERNEL=="sd*", DRIVERS=="usb", RUN+="/sbin/hdparm -r0 /dev/%k"
/sbin/hdparm -r1 /dev/%k – Enable read-only access to USB devices.
/sbin/hdparm -r0 /dev/%k – Enable Read-write access to USB devices.
3. Reload the UDEV rule by running the below command.
# udevadm control --reload
4. Once teh UDEV rules are reloaded, please try to connect a usb disk, mount it and verify if it allows read-only access. You can also use “dd” command to try writting on the USB device. It should fail as shown in the example below.
$ dd if=/dev/zero of=/dev/sdd bs=1k count=100 dd: writing `/dev/sdd': Operation not permitted 1+0 records in 0+0 records out 0 bytes (0 B) copied, 0.0005 seconds, 0 B/s