USBGuard
Protect your Linux system from unauthorized USB devices.
USBGuard blocks USB devices by default, preventing attacks like BadUSB or unauthorized data theft when your machine is unattended.
Installation
Install USBGuard on Debian/Ubuntu:
sudo apt update
sudo apt install usbguard -y
Initial Setup
Generate a policy for your currently connected USB devices:
sudo usbguard generate-policy > /tmp/rules.conf
sudo mv /tmp/rules.conf /etc/usbguard/rules.conf
This whitelists your existing devices (keyboard, mouse, etc.) so they continue to work.
Start and enable the service:
sudo systemctl enable usbguard
sudo systemctl start usbguard
Quick Toggle Script
This script lets you easily enable or disable USB blocking:
- Enable — Block all new USB devices
- Disable — Allow all USB devices (default behavior)
Create the script:
sudo vim /usr/local/bin/usbtoggle
Add the following:
#!/bin/bash
CONFIG_FILE="/etc/usbguard/usbguard-daemon.conf"
if [ "$#" -ne 1 ]; then
echo "Usage: $0 <enable|disable>"
exit 1
fi
if [ "$1" == "enable" ]; then
NEW_VALUE="block"
elif [ "$1" == "disable" ]; then
NEW_VALUE="allow"
else
echo "Invalid argument. Use 'enable' or 'disable'."
exit 1
fi
if grep -q "^ImplicitPolicyTarget=" "$CONFIG_FILE"; then
sed -i "s/^ImplicitPolicyTarget=.*/ImplicitPolicyTarget=$NEW_VALUE/" "$CONFIG_FILE"
echo "USB policy updated: ImplicitPolicyTarget=$NEW_VALUE"
else
echo "Error: ImplicitPolicyTarget setting not found in $CONFIG_FILE."
exit 1
fi
echo "Restarting usbguard service..."
systemctl restart usbguard
if [ $? -eq 0 ]; then
echo "usbguard restarted successfully."
else
echo "Failed to restart usbguard. Check system logs for details."
exit 1
fi
Make it executable:
sudo chmod +x /usr/local/bin/usbtoggle
Since /usr/local/bin is in PATH by default, you can now use it from anywhere.
Usage
Block new USB devices:
sudo usbtoggle enable
Allow all USB devices:
sudo usbtoggle disable
When to Use
- Enable when leaving your laptop unattended (coffee shop, office, etc.)
- Enable when in high-security environments
- Disable when you need to connect a new USB device
Manual Device Management
List connected USB devices:
sudo usbguard list-devices
Allow a specific device temporarily:
sudo usbguard allow-device <device-id>
Block a specific device:
sudo usbguard block-device <device-id>
Add a device to the permanent whitelist:
sudo usbguard allow-device <device-id> -p
Troubleshooting
If your keyboard/mouse stops working after enabling USBGuard, you'll need to access the machine via SSH or a virtual console (Ctrl+Alt+F2) and run:
sudo usbtoggle disable
Or regenerate the policy with your devices connected:
sudo usbguard generate-policy > /tmp/rules.conf
sudo mv /tmp/rules.conf /etc/usbguard/rules.conf
sudo systemctl restart usbguard