USBGuard / usbguard

USBGuard is a software framework for implementing USB device authorization policies (what kind of USB devices are authorized) as well as method of use policies (how a USB device may interact with the system)
https://usbguard.github.io/
GNU General Public License v2.0
1.1k stars 133 forks source link

Feature Request: Built-in Shutdown Option for Unauthorized USB Devices #633

Open nickt28 opened 2 weeks ago

nickt28 commented 2 weeks ago

It would be beneficial to have a built-in option to automatically shut down the system when an unauthorized USB device is detected. This feature would:

While this can be achieved through scripts, having it as a native feature would improve ease of use and performance. For someone not deeply familiar with Linux systems, there must be many optimizations to improve this workaround.

Guide for my current workaround

#!/bin/bash

LOG_FILE="/var/log/usbguard_events.log"

# Ensure the script has permission to write to the log file
touch "$LOG_FILE"
chmod 644 "$LOG_FILE"

shutdown_flag=false

# Log the PolicyApplied USB-related event details
if [ "$USBGUARD_IPC_SIGNAL" == "Device.PolicyApplied" ]; then
    {
        echo "--- New Device Policy Applied: $(date '+%Y-%m-%d %H:%M:%S') ---"
        echo "Device ID: $USBGUARD_DEVICE_ID"
        echo "Device Rule: $USBGUARD_DEVICE_RULE"
        echo "Device Target: $USBGUARD_DEVICE_TARGET_NEW"

        if [ "$USBGUARD_DEVICE_TARGET_NEW" == "block" ]; then
            shutdown_flag=true
        fi

        echo "----------------------------------------"
    } >> "$LOG_FILE"

    if $shutdown_flag; then
        echo "Initiating shutdown due to blocked USB device..."
        sudo shutdown -h now
    fi
fi
  1. Save it to a file, for example /usr/local/bin/usbguard_logger.sh
  2. Make it executable: sudo chmod +x /usr/local/bin/usbguard_logger.sh

Create service pipe - /etc/systemd/system/usbguard-logger.service

  1. Create a systemd service file: sudo nano /etc/systemd/system/usbguard-logger.service
  2. Add code
    
    [Unit]
    Description=USBGuard Logger Service
    After=usbguard.service
    Wants=usbguard.service

[Service] ExecStart=/usr/local/bin/usbguard watch --exec /usr/local/bin/usbguard_logger.sh Restart=always User=root

[Install] WantedBy=multi-user.target


3. Save and exit the editor (in nano, press Ctrl+X, then Y, then Enter).
4. Reload the systemd manager configuration `sudo systemctl daemon-reload`
5. Enable the service to start on boot `sudo systemctl enable usbguard-logger.service`
6. Start the service `sudo systemctl start usbguard-logger.service`
7. Check the status of the service: `sudo systemctl status usbguard-logger.service`

### Summary
- watch script - /usr/local/bin/usbguard_logger.sh
- service pipe - /etc/systemd/system/usbguard-logger.service
- event logs - /var/log/usbguard_events.log
- service logs - sudo journalctl -u usbguard-logger.service -f