Turn off the system if a strange USB is plugged in

Turn off the system if a strange USB is plugged in

·

2 min read

Welcome back Hackers!

What you're going to learn

A Pro Cyberwarrior is going to show you, how to create a BASH script that turns off the System every time a strange USB device connects to the System.

Step 1: Create systemd service

Syntax:
sudo vim /etc/systemd/system/usb-shutdown.service

Add the following content:
[Unit]
Description=USB Shutdown Service
After=multi-user.target

[Service]
Type=simple
ExecStart=/usr/local/bin/usb-shutdown-script.sh

[Install]
WantedBy=multi-user.target

Now save it and exit

Step 2: Create the script

Syntax:
vim /usr/local/bin/usb-shutdown-script.sh

#!/bin/bash

# Turns on the Script, if this option is set to false the script will not analyze the USBs.
USB_CHECK_ENABLED=true

# Function to check for unknown USB devices and shut down if conditions are not met
# If a USB device that is NOT in the list connects, then it will shut down.
check_unknown_devices() {
    if lsusb | grep -q -v "1f75:0917\|054c:0243"; then
        echo "Unknown USB device connected, shutting down..."
        /sbin/shutdown -h now
    fi

So now, you can check your USB devices with the command: lsusb
see what your USB ID is and put it in the list above. mine is "1f75:0917" thats the first USB and the second is "054c:0243", put yours in the list as above, you can add as many USBs as you want. I put an option to turn of or on the script, as i said if it's set to true, it will check and if it's set to false it will allow all USBs connections. I also added an option that runs the script every 10 seconds (you can change that) in case someone plugs in a USB device before the system is on, it will check every 30 second so even if someone plug it in while the system is off, the script will know it. Let's continue coding!

# Main logic
while true; do
    if [ "$USB_CHECK_ENABLED" = true ]; then
        check_unknown_devices
    else
        echo "USB device check is disabled. Allowing connection..."
    fi
    sleep 10 # Check every 10 seconds (change if you want)
done

# Save and exit

Step 3: Make the script executable

syntax:
sudo chmod +x /usr/local/bin/usb-shutdown-script.sh

Step 4: Enable and start the systemd service

syntax:
systemctl enable usb-shutdown.service
systemctl start usb-shutdown.service

End

Now if someones connect an unknown USB device the system will shutdown.

Stay safe!