2

I've already searched for an answer, but can not find exact solution for this task.

I'm new to Linux but I want to learn and I want to know how to disallow any usb device type except flash drive inserted in specified USB port. I know how to write matching rule for udev but I can't find real example of a script that will block specified USB port on udevadm event.

At first I created a rule /etc/udev/rules.d/96-myusb.rules to match usb device type:

ACTION=="add", SUBSYSTEM=="usb", ENV{ID_TYPE}!="disk", ENV{ID_USB_DRIVER}!="usb-storage",RUN+="/lib/udev/unmount.sh"

Please correct me if I wrong.

Then I have to write a shell script that will be executed by the previous rule to block unmatched devices on specified USB port — and this is the problem for me.

1 Answer 1

1

To do this properly with udev, you actually need to set things up to block by default on all USB ports, and then write rules to match the devices and allow through what you want (in this case, everything on most ports, and only MSC and UAS devices on a particular port). If not done this way, you have a very short period of time during which the device is visible to the system before it gets blocked, which can completely negate any benefit to blocking it in the first place, as the kernel drivers will start talking to it beyond enumeration before you block it.

As far as the script itself, you may not need it. Depending on where in the hierarchy you match with the udev rule, you should be able to just set the authorized attribute to allow things.

Alternatively, take a look at usbguard. It's a dedicated service for handling this type of thing. Unfortunately, it's not pre-packaged on many distros, but looking at how it works may be helpful in figuring out how to do this with udev.

2
  • Thank you sir. I've recently tried to check out usbguard on Ubuntu 16.04 but it fails during the installation. Great advice about usb port blocking by default, but the problem is that I have to block only one specified usb port and then unblock it immediately on udevadm event somehow. Is it possible? So, other posts as "how to block all usb ports by BIOS" e.t.c are useless in my case. It would be great if you provide some real example, please. I have read a lot of posts but there is no exact solution yet. I think many people would like to see working example related to this issue.
    – mr.boris
    Oct 18, 2017 at 11:03
  • The problem is that I'm not quite sure about it myself. That's part of why I mentioned usbguard, looking at the source for that may give some insights. I know there's a switch somewhere to set the kernel to block by default, but I'm not sure where it is. Once you do that, you can set udev to unblock things on the other ports by default, and then do whatever filtering you want on the required port. Oct 18, 2017 at 11:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .