- Build: make -C /lib/modules/$(uname -r)/build M=$(pwd) modules
- Install:sudo insmod usb_filter.ko
- Test: dmesg
- Remove: sudo rmmod usb_filter
Created
July 24, 2023 08:12
-
-
Save M0nteCarl0/b6d5b4539d4a2ada42ee1699baae9639 to your computer and use it in GitHub Desktop.
Linux USB filter kernel module example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <linux/module.h> | |
#include <linux/kernel.h> | |
#include <linux/usb.h> | |
static struct usb_device_id blacklist[] = { | |
{ USB_DEVICE(0x1234, 0x5678) }, // Example blacklist entry | |
{ } // Terminating entry | |
}; | |
MODULE_DEVICE_TABLE(usb, blacklist); | |
static int is_device_blacklisted(struct usb_device *dev) { | |
struct usb_device_id *id; | |
for (id = blacklist; id->match_flags != 0; id++) { | |
if (id->idVendor == le16_to_cpu(dev->descriptor.idVendor) && | |
id->idProduct == le16_to_cpu(dev->descriptor.idProduct)) { | |
return 1; // Device is blacklisted | |
} | |
} | |
return 0; // Device is not blacklisted | |
} | |
static int usb_filter_probe(struct usb_interface *interface, const struct usb_device_id *id) { | |
struct usb_device *dev = interface_to_usbdev(interface); | |
if (is_device_blacklisted(dev)) { | |
printk(KERN_INFO "USB device (%04X:%04X) is blacklisted\n", | |
le16_to_cpu(dev->descriptor.idVendor), | |
le16_to_cpu(dev->descriptor.idProduct)); | |
return -ENODEV; // Reject the device | |
} | |
// Continue handling the device as needed | |
return 0; // Success | |
} | |
static void usb_filter_disconnect(struct usb_interface *interface) { | |
// Handle device disconnect event | |
} | |
static struct usb_driver usb_filter_driver = { | |
.name = "usb_filter", | |
.probe = usb_filter_probe, | |
.disconnect = usb_filter_disconnect, | |
.id_table = blacklist, | |
}; | |
static int __init usb_filter_init(void) { | |
int result = usb_register(&usb_filter_driver); | |
if (result < 0) { | |
printk(KERN_ERR "Failed to register USB filter driver: %d\n", result); | |
return result; | |
} | |
printk(KERN_INFO "USB filter driver registered\n"); | |
return 0; // Success | |
} | |
static void __exit usb_filter_exit(void) { | |
usb_deregister(&usb_filter_driver); | |
printk(KERN_INFO "USB filter driver unregistered\n"); | |
} | |
module_init(usb_filter_init); | |
module_exit(usb_filter_exit); | |
MODULE_LICENSE("GPL"); | |
MODULE_AUTHOR("Your Name"); | |
MODULE_DESCRIPTION("USB filter kernel module"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment