Mastering Udev Rules on Linux: Device Naming, Permissions, and Automation

Linux tutorial - IT technology blog
Linux tutorial - IT technology blog

The Headaches of Linux Dynamic Device Naming

Last year, our team managed 42 edge gateways deployed across field substations. Every time a maintenance tech swapped a cellular modem or power-cycled an industrial hub, Linux reassigned device nodes at random. Our RS-485 Modbus interface mapped to /dev/ttyUSB0 at 08:00 would quietly shift to /dev/ttyUSB1 after a midday brownout. Downstream telemetry scripts died instantly. Worse, our night-time database backups failed whenever a SanDisk external drive swapped from /dev/sdb1 to /dev/sdc1.

Permissions made things even messier. System daemons running under unprivileged service accounts couldn't open newly attached serial ports without manual chmod 666 fixes or dangerous root escalation. Production servers cannot rely on default kernel device enumeration. You need predictable device paths, sticky group permissions, and isolated automation hooks that fire the moment hardware clicks into a socket.

Core Concepts: How Udev Handles Kernel Events

When you plug a device into a running Linux machine, the kernel registers the hardware and sends an event notification called a uevent over a Netlink socket. The userspace daemon systemd-udevd catches these events, searches /sys (sysfs) for hardware attributes, and matches them against your rule files.

Rule Evaluation and Priority

Udev processes rule files sequentially in lexical order across three filesystem locations:

  • /usr/lib/udev/rules.d/: Default system rules packaged by distributions like Debian, RHEL, or Ubuntu. Treat these as read-only.
  • /run/udev/rules.d/: Volatile runtime rules generated on the fly in memory. They disappear on reboot.
  • /etc/udev/rules.d/: Your custom configuration space. Files placed here take precedence over vendor rules with identical filenames.

Two-digit numerical prefixes govern execution order (for example, 10-local.rules runs before 99-custom.rules). Place custom rules at 90 or higher. This guarantees basic device setup completes before your custom match triggers.

Match Keys vs Assignment Keys

Every rule joins match conditions with action assignments using comma separation:

  • Match operators: == checks equality, while != checks inequality. Common targets include SUBSYSTEM, ATTRS{idVendor}, ATTRS{idProduct}, and ATTRS{serial}.
  • Assignment operators: = sets a value, += appends to an existing list, and := assigns a final value that downstream rules cannot override. Frequently used keys include SYMLINK, OWNER, GROUP, and MODE.

Watch out: confusing = with == is the single most common syntax error in udev configurations. Accidental assignment in a match field breaks rule parsing without throwing obvious syntax errors.

Hands-on Practice: Building Production Udev Rules

Step 1: Extract Device Attributes

Never guess hardware parameters. Plug in your device and walk the sysfs tree with udevadm info:

# Walk the device hierarchy to inspect hardware parameters
udevadm info --attribute-walk --name=/dev/ttyUSB0

This command prints the primary device followed by each parent bus in ascending order. Here is a truncated excerpt from an FTDI FT232R USB-to-serial converter:

  looking at device '/devices/pci0000:00/0000:00:14.0/usb1/1-2/1-2.1/1-2.1:1.0/ttyUSB0/tty/ttyUSB0':
    KERNEL=="ttyUSB0"
    SUBSYSTEM=="tty"

  looking at parent device '/devices/pci0000:00/0000:00:14.0/usb1/1-2/1-2.1':
    ATTRS{idVendor}=="0403"
    ATTRS{idProduct}=="6001"
    ATTRS{serial}=="FT89X42A"
    ATTRS{manufacturer}=="FTDI"

Keep one strict rule in mind: you can combine attributes from the target node with attributes from one parent device block. Mixing keys from multiple distinct parent levels within a single rule prevents the pattern from ever matching.

Step 2: Assign Persistent Symlinks and Non-Root Permissions

Hardcoding volatile device nodes like ttyUSB0 into your telemetry stack invites breakage. Let udev map a static symlink instead—such as /dev/modbus_gateway—and hand access rights to a designated system group.

Create a rule file at /etc/udev/rules.d/99-serial-devices.rules:

# Map FTDI serial chip to /dev/modbus_gateway with dialout group read/write
SUBSYSTEM=="tty", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6001", ATTRS{serial}=="FT89X42A", \
    MODE="0660", GROUP="dialout", SYMLINK+="modbus_gateway"

Now, whenever serial chip FT89X42A connects, udev creates a symlink at /dev/modbus_gateway pointing to the dynamic ttyUSB* node. It sets file mode 0660 (rw-rw----) under group dialout. Any service user added to dialout (via usermod -aG dialout edge-agent) can read and write to the port without requiring root rights.

Step 3: Triggering Automated Actions on USB Hotplug

Executing shell scripts directly through RUN+="/path/to/script.sh" comes with serious caveats. Modern systemd-udevd workers run inside private mount namespaces. Any filesystem mount executed directly inside RUN stays trapped in the worker's temporary namespace and remains invisible to the rest of the OS. Furthermore, udev kills any process that exceeds its event timeout (defaulting to 180 seconds), blocking further hardware events in the queue.

The standard pattern hands execution off to systemd asynchronously through ENV{SYSTEMD_WANTS}.

First, create a parameterized systemd unit at /etc/systemd/system/[email protected]:

[Unit]
Description=Automated USB Backup Service for %I
BindsTo=dev-%i.device
After=dev-%i.device

[Service]
Type=oneshot
TimeoutStartSec=600
ExecStart=/usr/local/bin/usb-sync.sh %I

Next, write the backup script at /usr/local/bin/usb-sync.sh:

#!/usr/bin/env bash
set -euo pipefail

DEVNAME="$1"
MOUNT_DIR="/mnt/external_backup"
LOG_FILE="/var/log/usb_sync.log"

echo "[$(date '+%Y-%m-%d %H:%M:%S')] Drive /dev/${DEVNAME} detected. Starting backup..." >> "${LOG_FILE}"
mkdir -p "${MOUNT_DIR}"
mount "/dev/${DEVNAME}" "${MOUNT_DIR}"

# Synchronize 12 GB of daily telemetry exports
rsync -aq --delete /var/data/exports/ "${MOUNT_DIR}/archive/"

sync
umount "${MOUNT_DIR}"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Sync completed. Drive unmounted safely." >> "${LOG_FILE}"

Apply execute permissions: sudo chmod +x /usr/local/bin/usb-sync.sh.

Finally, register the udev trigger in /etc/udev/rules.d/99-usb-backup.rules. This example matches a 128 GB SanDisk Ultra USB 3.0 drive (Vendor 0781, Product 5583):

ACTION=="add", SUBSYSTEM=="block", ENV{DEVTYPE}=="partition", \
    ATTRS{idVendor}=="0781", ATTRS{idProduct}=="5583", \
    SYMLINK+="backup_drive", TAG+="systemd", ENV{SYSTEMD_WANTS}="usb-backup@backup_drive.service"

The rule tags the partition for systemd and starts our one-shot unit. System resources stay quiet until the drive physically seats in the socket. Once inserted, the task runs in its own systemd cgroup, logs cleanly to journalctl -u usb-backup@backup_drive.service, and leaves the udev daemon free to process subsequent device interrupts.

Step 4: Reload and Verify Rules

Apply your new configurations without rebooting by reloading the rule table and replaying kernel events:

# 1. Reload the udev rule definition cache
sudo udevadm control --reload-rules

# 2. Test rule evaluation dry-run without unplugging hardware
sudo udevadm test $(udevadm info -q path -n /dev/ttyUSB0)

# 3. Trigger events for connected devices to enforce changes
sudo udevadm trigger --subsystem-match=tty
sudo udevadm trigger --subsystem-match=block

Confirm the new node permissions and symlink targets:

ls -l /dev/modbus_gateway
# Output: lrwxrwxrwx 1 root root 7 Nov 22 10:14 /dev/modbus_gateway -> ttyUSB0

Conclusion

Predictable udev rules turn chaotic Linux hardware detection into a reliable operational baseline. Matching against immutable vendor, product, and serial strings lets you expose stable device nodes regardless of physical port position or reboot order. For hotplug tasks, skipping RUN directives in favor of ENV{SYSTEMD_WANTS} protects you from mount namespace traps, isolates execution timeouts, and keeps your system event pipeline clean.

Share: