Created by Soumit Santra β AegisUSB: Professional USB Forensic Analysis Β© 2026 Soumit Santra. All rights reserved.
THIS TOOL IS STRICTLY FOR AUTHORIZED FORENSIC INVESTIGATIONS ONLY!
- DO NOT USE on systems or devices you don't own or without explicit written permission
- UNAUTHORIZED DEVICE SCANNING is illegal under the Computer Fraud and Abuse Act (USA), Computer Misuse Act (UK), and similar laws worldwide
- OBTAIN WRITTEN AUTHORIZATION before scanning any third-party systems or devices
- THE AUTHOR IS NOT RESPONSIBLE for misuse, damages, legal consequences, or illegal activities
- VIOLATORS FACE CRIMINAL PROSECUTION including fines and imprisonment
Ethical Use Only:
- Authorized digital forensics with written permission
- Incident response on systems you own or are contracted to protect
- Security auditing of your own infrastructure
- Educational learning in controlled lab environments
- Professional penetration testing with proper contracts
- Corporate USB policy enforcement with employee consent
- Never use against devices or systems without explicit written permission
This tool is designed to help security professionals, incident responders, and system administrators understand:
- USB-based attack vectors and BadUSB techniques
- Hardware-level threat detection and forensic methodology
- Malware payload identification and quarantine workflows
- Behavioral anomaly detection against a persistent baseline
- File forensics, SHA-256 evidence hashing, and chain of custody
- MITRE ATT&CK technique mapping for threat rule development
- Windows Registry Scanning β USBSTOR, USB, and HID branches for historic + live enumeration
- HID Device Scanning β Dedicated
_scan_hid()pass withClassGUID-to-class-name mapping (Keyboard, Mice, Network Adapter, HID Device, USB Hub) - WMI / PowerShell Integration β Real-time live device detection via
Win32_DiskDriveCIM query - Linux sysfs Scanning β Full
/sys/bus/usbdevice tree traversal viaLinuxDiscovery - Official USB ID Database β Resolves VID/PID via usb.ids with offline fallback and 30+ common vendor hardcodes
- USB Enrichment Pass β
_enrich_usb_info()back-fills missing VID/PID/vendor data by cross-referencing USBSTOR serials against the USB registry branch - Mount-Point Resolution β
_add_mount_info()maps drive letters fromSYSTEM\MountedDevicesby matching serial substrings in binary values - Multi-source Deduplication β
_merge_devices()performs serial-keyed merging, always preferring non-0000IDs and descriptive names over Unknown placeholders
- New Hardware Detection β Flags devices whose serial has never been seen on this machine
- New Vendor Detection β Secondary alert when an entirely new brand appears alongside a new serial
- Off-Hours Analysis β Detects connections outside working hours (06:00β22:00)
- Machine-Scoped Persistence β JSON baseline is keyed by
platform.node()so multi-machine baselines co-exist in the same file - Known-Users Tracking β
_known_usersset persisted and available for future correlation rules - System Whitelist β Suppresses alerts for Microsoft, Intel, Realtek, Standard USB Host Controllers, and similar system noise
- Magic Byte Analysis β PE/ELF headers, ZIP/JAR archives, shell shebangs, AutoRun markers, PowerShell/CMD references
- Suspicious Extensions β
.exe,.dll,.ps1,.bat,.vbs,.lnk, and 10+ additional types - AutoRun Detection β Identifies
autorun.infinfection markers - String Pattern Matching β
IEX,DownloadString,mimikatz,netcat,WScript.Shell,CreateObject,EncodedCommand, and more - Serial/IoT Port Inspection β Hidden serial interface and Arduino/ESP32 detection via
pyserial - Storage-Only Gate β Non-storage devices (HID, Bluetooth, Network) are skipped to prevent false-positive noise
- SHA-256 Evidence Hashing β Cryptographic integrity for every scanned file; files over 512 MB use a 4 MB partial hash to prevent DoS
- Shannon Entropy Calculation β Detects encrypted or packed payloads (threshold: entropy > 7.5)
- Double-Extension Detection β Catches filenames like
document.exe.pdfhiding a dangerous middle extension - Hidden File Detection β Flags files prefixed with
.(Unix-style hidden files) - YARA Rule Scanning β Custom signature-based malware detection; gracefully disabled if rules fail to load
- VirusTotal Hash Lookup β Optional cloud reputation check on every file's SHA-256 via the intel service
- Automatic Quarantine β Suspicious files copied to
quarantine/YYYYMMDD/<sha256>with.meta.jsonsidecar records - Path Traversal Protection β
os.path.commonpath()guard blocks directory escape attacks before every file inspection - Concurrent Scanning β
ThreadPoolExecutorwith 4 workers and a 30-second timeout for high-throughput device scanning - Result Prioritization β Results sorted with suspicious files first, then by descending size
- 60-Second Correlation Window β Catches processes spawned right after USB insertion
- High-Risk Process List β
powershell,cmd,wscript,mshta,certutil,netcat,python,curl,wget, and more - Drive Letter Correlation β Confirms if a suspicious process has files open on the USB mount point
- Full Cmdline Capture β Records up to 200 characters of process arguments for evidence
- Reflective Injection Detection β Identifies executable memory regions with no backing file on disk (orphaned RX/RWX segments)
- Sensitive Module Load Detection β Flags executable code loaded from high-risk paths:
\Temp\,\AppData\,\Users\Public\,\Downloads\ - Process-Correlated Scanning β Only activates for PIDs already flagged by the Process Correlator, eliminating noise
- Cross-Platform psutil Integration β Uses
proc.memory_maps(grouped=False)for per-region permission inspection
- VID:PID to Interface Mapping β Uses PowerShell
Win32_NetworkAdapterCIM query to match hardware to OS interface names - Real-time Packet Capture β Scapy-based 15-second PCAP on the matched interface (optional dependency)
- Malicious IP Detection β AbuseIPDB reputation check on every source IP seen in captured traffic
- DNS Tunnel Detection β Heuristic flagging of queries with subdomains over 50 characters or high-entropy labels
- Device-Class Gate β Only activates for
Network Adapterclass devices
- 13 Built-in MITRE ATT&CK Rules β Covering exfiltration, BadUSB/Rubber Ducky, bootkits, HID compound devices, unknown vendors, microcontrollers, and C2 adapters
- Custom JSON Rules β Load your own rules from any directory with
--rules - Rich Condition Operators β
equals,contains,exists,not_exists,matches(regex),length_gt,is_true,is_false,gt,gte,lt,lte - Nested Field Paths β Conditions can address nested dict fields like
properties.usersorproperties.exfiltration_alerts - Severity Levels β Critical / High / Medium / Low / Info
- Rule Override / Promotion β Rule engine can promote heuristic risk scores upward; heuristic can never override a higher rule match
- Two-Stage Scoring β Weighted heuristic factors (bootable +15, new hardware +20, suspicious files +40, memory anomaly +60, etc.) followed by rule engine override
- Risk Levels β Low / Medium / High / Critical with explicit score thresholds (20 / 40 / 70)
- Factor Stacking β Multiple signals combine: hardware + behavioral + payload + process + network + memory + exfiltration
- Contradiction-Free Logic β Rule severity is compared against heuristic level via a strict ordinal map; the worse value always wins
- SQLite Case Management β Persistent evidence database (
.usb_forensic_case.db) - Atomic Transactions β All writes wrapped in explicit
BEGIN TRANSACTION/COMMITblocks - SHA-256 Indexed Artifacts β
forensic_artifactstable is indexed onsha256for sub-second lookups - Upsert Logic β Re-scanning the same device updates
last_seenwithON CONFLICT DO UPDATE, never duplicates - Selective Storage β Only
suspicious=Trueartifacts are archived; clean files are not stored
- Professional Terminal UI β 256-colour device cards with risk badges, confidence bars, timeline sections, alert categories, rule matches with MITRE tags, and file forensics summaries
- HTML Forensic Dashboard β Styled report with per-device risk colour coding and file forensics tables
- PDF Forensic Report β ReportLab-powered professional report with custom styles and risk-colour badges
- JSON Export β Machine-readable output with full dataclass serialisation, suitable for SIEM ingestion
- Plain Text Evidence Log β Human-readable report for documentation and chain-of-custody records
- SIEM Integration Stub β
send_to_siem()hook for Syslog/UDP/HTTP forwarding - SQLite Snapshot β Full evidence database recorded per session via the Export Wizard
- Real-time Monitoring Mode β WMI
Win32_USBControllerDevicekernel-level event watcher on Windows with polling fallback on Linux
- AbuseIPDB Integration β IP reputation checks with configurable confidence threshold (>50)
- VirusTotal Integration β File hash reputation checks; reports detection count out of total engine count
- API Key via Environment Variables β
ABUSEIPDB_KEYandVIRUSTOTAL_KEYβ no hardcoded credentials
- Python 3.8+
- Windows: Administrator privileges required (Registry + WMI access)
- Linux: Root privileges required (
/sys/bus/usbaccess)
Install all dependencies (Recommended):
pip install -r requirements.txtCore dependencies included:
psutilβ System and process monitoringpython-dotenvβ Environment variable managementwmiβ Windows hardware event monitoringpywin32β Windows system integration
Optional (enhanced capabilities):
yara-pythonβ YARA rule-based file scanningpyserialβ Serial/IoT port detectionscapyβ Live packet capture for USB network adaptersreportlabβ PDF forensic report generationrequestsβ AbuseIPDB / VirusTotal intel lookups
git clone https://github.com/Soumit-Santra/AegisUSB.git
cd AegisUSB
# Create virtual environment (recommended)
python3 -m venv venv
source venv/bin/activate # Linux/macOS
venv\Scripts\activate # Windows
# Install dependencies
pip install -r requirements.txt- Download the repository as a ZIP from GitHub
- Extract and navigate into the folder
- Run
pip install -r requirements.txt - Launch with
python -m scanner.main
Note
Windows Users: AegisUSB includes Automatic UAC Elevation. If run from a standard terminal, it will attempt to relaunch itself as Administrator. However, for the best experience, manually launch your terminal as Administrator.
# Windows
python -m scanner.main
# Linux / macOS
sudo python -m scanner.mainusage: main.py [-h] [-v] [-j] [-m] [-r RULES] [-y YARA]
options:
-h, --help Show this help message and exit
-v, --verbose Enable debug logging
-j, --json Output raw JSON (suitable for piping to SIEM/jq)
-m, --monitor Real-time device monitoring mode (Ctrl+C to exit)
-r RULES, --rules Path to a directory of custom JSON threat rules
-y YARA, --yara Path to a compiled YARA rules file
Standard forensic scan with terminal UI:
sudo python -m scanner.mainJSON output β pipe into jq or a SIEM:
sudo python -m scanner.main --json | jq .Real-time USB monitoring:
sudo python -m scanner.main --monitorLoad custom threat rules + YARA signatures:
sudo python -m scanner.main --rules ./my_rules/ --yara ./signatures.yarEnable external intel lookups:
- Copy
.env.exampleto.env:cp .env.example .env # Linux/macOS copy .env.example .env # Windows
- Open
.envand enter your API keys. - Run the scanner normally:
python -m scanner.main
Alternatively, use temporary environment variables:
# Windows (PowerShell)
$env:ABUSEIPDB_KEY="your_key_here"; python -m scanner.main
# Linux / macOS
export ABUSEIPDB_KEY="your_key_here"
sudo -E python -m scanner.mainVerbose debug output:
sudo python -m scanner.main --verbosescanner/
βββ core/
β βββ device.py # USBDevice dataclass β central data model
β βββ risk.py # Two-stage weighted risk scoring engine
β βββ fingerprint.py # SHA-256 identity and device fingerprint hashing
β βββ pipeline.py # Async engine orchestration pipeline
β βββ registry.py # Engine dependency injection registry
β βββ intel.py # AbuseIPDB + VirusTotal external intel service
β βββ case_manager.py # SQLite evidence and case database
βββ engines/
β βββ baseline.py # Behavioral anomaly detection + Windows/Linux discovery
β βββ forensics.py # File-level forensics, entropy, YARA, quarantine
β βββ payload.py # Malware/payload signature and magic-byte detection
β βββ process.py # Live process correlation engine
β βββ memory.py # In-memory reflective injection & RWX detection
β βββ network.py # USB network adapter packet capture & DNS analysis
β βββ id_lookup.py # USB vendor/product ID resolution (usb.ids + hardcodes)
βββ rules/
β βββ engine.py # Threat rule engine (13 built-ins + custom JSON rules)
βββ ui/
β βββ renderer.py # Terminal card UI + HTML report generator
β βββ reports.py # PDF generation (ReportLab) + SIEM integration stub
βββ tests/
β βββ test_risk.py # Unit tests for RiskEngine
β βββ test_suite.py # Full test suite (Risk, Pipeline, CaseManager, Baseline, Payload)
βββ main.py # Entry point, CLI, privilege escalation, ScannerApp orchestrator
Each device renders as a detailed card showing serial number, VID/PID, manufacturer, connection timeline, confidence score, all alert categories, matched threat rules with MITRE tags, file forensics summary, and a risk level badge.
After every scan, an interactive export wizard offers:
| Option | Format | Best For |
|---|---|---|
| 1 | .txt |
Plain evidence log, documentation |
| 2 | .html |
Styled forensic dashboard, stakeholder reports |
| 3 | .json |
SIEM ingestion, automated pipelines |
| 4 | .pdf |
Professional forensic reports (requires ReportLab) |
| 5 | SIEM push | Real-time platform forwarding |
| 6 | .db |
SQLite evidence snapshot for case handoff |
| Rule | Severity | MITRE Tags |
|---|---|---|
| Mass File Exfiltration | π΄ Critical | T1052.001 |
| Exfiltration with Known User | π΄ Critical | T1052.001, attribution |
| High-Confidence BadUSB / AegisUSB Alert | π΄ Critical | T1200, initial-access |
| Suspicious Write Activity | π High | T1052.001 |
| HID + Storage Compound Device | π High | badusb, T1052.001 |
| Suspicious HID Host Controller | π High | badusb, T1200 |
| Bootable USB Detected | π High | T1542.001, persistence |
| Microcontroller / Attack Platform | π High | T1200, covert-hardware |
| High Risk Device (heuristic) | π High | general |
| Unknown Vendor Device | π‘ Medium | supply-chain |
| No Serial Number | π‘ Medium | unknown-hardware |
| Multiple Users Accessed Device | π‘ Medium | T1078, lateral-movement |
| USB Network Adapter | π‘ Medium | T1572, C2 |
Place .json files in a directory and load with --rules:
{
"rule_name": "Suspicious Raspberry Pi",
"description": "Raspberry Pi Foundation device β possible covert compute node.",
"severity": "High",
"tags": ["T1200", "covert-hardware"],
"match": "all",
"enabled": true,
"conditions": [
{ "field": "vendor_id", "op": "equals", "value": "2e8a" }
]
}Supported operators: exists, not_exists, equals, not_equals, contains, not_contains, is_true, is_false, gt, gte, lt, lte, matches (regex), length_gt, length_gte
Addressable fields: Any field on USBDevice, including nested dict paths like properties.users or properties.exfiltration_alerts.
# Full test suite
python -m scanner.tests.test_suite # AegisUSB Test Suite
# Risk engine unit tests only
python -m unittest scanner.tests.test_riskTest coverage includes:
- RiskEngine β heuristic scoring, rule override, multi-signal stacking, anomaly and payload alert escalation
- Async Pipeline β engine dispatch across multiple devices, crash isolation, empty device list handling
- CaseManager β SQLite table creation, device insert, upsert-on-conflict, artifact indexing, clean-file exclusion
- BehavioralBaseline β new hardware alerts, off-hours detection, system whitelist suppression, persistence round-trips
- PayloadDetector β non-storage device skipping, AutoRun detection, suspicious extension detection, PE magic byte detection
A AegisUSB database (.aegisusb_case.db) is automatically maintained in the working directory.
| Table | Contents |
|---|---|
devices |
Serial, VID/PID, vendor name, first/last seen timestamps, risk score |
forensic_artifacts |
Suspicious files with SHA-256 hashes, path, timestamp β SHA-256 indexed |
Direct forensic queries:
# List all suspicious artifacts
sqlite3 .aegisusb_case.db "SELECT * FROM forensic_artifacts WHERE suspicious=1;"
# Show all scanned devices
sqlite3 .aegisusb_case.db "SELECT serial, vendor_name, first_seen, last_seen FROM devices;"Permission Denied:
# Run as Administrator (Windows) or root (Linux)
sudo python -m scanner.mainModule Import Errors:
pip install --force-reinstall -r requirements.txtNo Devices Found (Linux):
# Confirm USB devices are visible to the kernel
ls /sys/bus/usb/devices/YARA Import Error:
pip install yara-python
# On some systems:
pip install yara-python --prePacket Capture Not Working:
pip install scapy
# Requires Npcap (Windows) or libpcap (Linux) to be installed at the OS levelPDF Export Fails:
pip install reportlabDatabase Locked:
- Only one instance of the scanner should run at a time
- Delete
.aegisusb_case.dbto start a fresh case database
- β Authorized digital forensics with written permission
- β Incident response on systems you own or are contracted to protect
- β Security auditing of your own infrastructure
- β Bug bounty programs with explicit USB/hardware scope
- β Educational use in controlled lab environments
- β Corporate USB policy enforcement with employee consent
- β Unauthorized scanning of devices or systems
- β Scanning systems without explicit written permission
- β Exploiting discovered vulnerabilities
- β Circumventing security measures
- β Any malicious or harmful activities
Be aware of these laws in your jurisdiction:
- Computer Fraud and Abuse Act (CFAA) β USA
- Computer Misuse Act β UK
- Cybercrime Act β Various countries
- GDPR and data protection laws β EU
- Information Technology Act β India
- Local cybersecurity legislation
If you discover vulnerabilities during authorized testing:
- Document carefully β Note all details without further exploitation
- Report responsibly β Contact the system owner immediately
- Follow disclosure guidelines β Respect coordinated disclosure timelines
- Provide remediation advice β Help fix the issue, not just report it
- Maintain confidentiality β Do not publicize until the issue is resolved
Contributions are welcome for:
- Additional threat detection rules and YARA signatures
- Improved vendor/device identification accuracy
- New export formats and reporting enhancements
- Performance optimizations for large device sets
- Bug fixes and stability improvements
- macOS support and discovery engine
Guidelines:
- Follow PEP 8 style conventions
- Add docstrings to new functions
- Include unit tests for new engines or scoring logic
- Update documentation for new features
- Maintain ethical use focus at all times
Recommended Resources:
- MITRE ATT&CK Framework β attack.mitre.org
- OWASP Testing Guide
- "The Art of Intrusion" by Kevin Mitnick
- NIST Cybersecurity Framework
- USB Rubber Ducky Documentation β Hak5
- SANS Digital Forensics & Incident Response resources
- CVE Database and USB vulnerability research
This tool performs active forensic operations that may:
- Trigger endpoint detection and response (EDR) systems
- Be logged and monitored by enterprise security platforms
- Violate organizational device policies if used without approval
- Result in criminal prosecution if used without proper authorization
- Copy and quarantine files from connected devices
Remember:
- Authorization is MANDATORY
- Documentation is ESSENTIAL
- Ethical conduct is NON-NEGOTIABLE
- Legal compliance is YOUR RESPONSIBILITY
When in doubt, DON'T SCAN. Always obtain explicit written permission first.
MIT License β See LICENSE file for details.
This tool is provided "as is" without warranty of any kind. Users are solely responsible for ensuring their use complies with all applicable laws and regulations.
"A forensic investigator doesn't just find the evidence β they preserve the truth. Handle every device as if it will testify in court, because one day, it just might."