Skip to content

Soumit-Santra/AegisUSB

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

5 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ›‘οΈ AegisUSB β€” Advanced USB Forensic Analysis & Threat Detection Tool

Python Platform Privileges Security License

Created by Soumit Santra β€” AegisUSB: Professional USB Forensic Analysis Β© 2026 Soumit Santra. All rights reserved.


⚠️ CRITICAL LEGAL & ETHICAL NOTICE

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

πŸ“š Educational Purpose

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

✨ Features

πŸ–₯️ Device Discovery & Identification

  • Windows Registry Scanning β€” USBSTOR, USB, and HID branches for historic + live enumeration
  • HID Device Scanning β€” Dedicated _scan_hid() pass with ClassGUID-to-class-name mapping (Keyboard, Mice, Network Adapter, HID Device, USB Hub)
  • WMI / PowerShell Integration β€” Real-time live device detection via Win32_DiskDrive CIM query
  • Linux sysfs Scanning β€” Full /sys/bus/usb device tree traversal via LinuxDiscovery
  • 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 from SYSTEM\MountedDevices by matching serial substrings in binary values
  • Multi-source Deduplication β€” _merge_devices() performs serial-keyed merging, always preferring non-0000 IDs and descriptive names over Unknown placeholders

🧠 Behavioral Baseline Engine

  • 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_users set persisted and available for future correlation rules
  • System Whitelist β€” Suppresses alerts for Microsoft, Intel, Realtek, Standard USB Host Controllers, and similar system noise

🦠 Payload Detection

  • 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.inf infection 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

πŸ”¬ File Forensics

  • 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.pdf hiding 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.json sidecar records
  • Path Traversal Protection β€” os.path.commonpath() guard blocks directory escape attacks before every file inspection
  • Concurrent Scanning β€” ThreadPoolExecutor with 4 workers and a 30-second timeout for high-throughput device scanning
  • Result Prioritization β€” Results sorted with suspicious files first, then by descending size

βš™οΈ Live Process Correlation

  • 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

🧬 Memory Forensics

  • 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

πŸ“‘ Network Intelligence

  • VID:PID to Interface Mapping β€” Uses PowerShell Win32_NetworkAdapter CIM 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 Adapter class devices

πŸ›‘οΈ Threat Rule Engine

  • 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.users or properties.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

πŸ“Š Risk Scoring

  • 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

πŸ—„οΈ Evidence Database

  • SQLite Case Management β€” Persistent evidence database (.usb_forensic_case.db)
  • Atomic Transactions β€” All writes wrapped in explicit BEGIN TRANSACTION / COMMIT blocks
  • SHA-256 Indexed Artifacts β€” forensic_artifacts table is indexed on sha256 for sub-second lookups
  • Upsert Logic β€” Re-scanning the same device updates last_seen with ON CONFLICT DO UPDATE, never duplicates
  • Selective Storage β€” Only suspicious=True artifacts are archived; clean files are not stored

πŸ“‹ Reporting & Output

  • 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_USBControllerDevice kernel-level event watcher on Windows with polling fallback on Linux

πŸ”— External Intelligence

  • 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_KEY and VIRUSTOTAL_KEY β€” no hardcoded credentials

πŸ› οΈ Requirements

  • Python 3.8+
  • Windows: Administrator privileges required (Registry + WMI access)
  • Linux: Root privileges required (/sys/bus/usb access)

Install all dependencies (Recommended):

pip install -r requirements.txt

Core dependencies included:

  • psutil β€” System and process monitoring
  • python-dotenv β€” Environment variable management
  • wmi β€” Windows hardware event monitoring
  • pywin32 β€” Windows system integration

Optional (enhanced capabilities):

  • yara-python β€” YARA rule-based file scanning
  • pyserial β€” Serial/IoT port detection
  • scapy β€” Live packet capture for USB network adapters
  • reportlab β€” PDF forensic report generation
  • requests β€” AbuseIPDB / VirusTotal intel lookups

πŸ’» Installation

Option 1: Clone from GitHub (Recommended)

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

Option 2: Direct Download

  1. Download the repository as a ZIP from GitHub
  2. Extract and navigate into the folder
  3. Run pip install -r requirements.txt
  4. Launch with python -m scanner.main

🚦 Usage

Basic Scan

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.main

Command-Line Options

usage: 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

Example Workflows

Standard forensic scan with terminal UI:

sudo python -m scanner.main

JSON output β€” pipe into jq or a SIEM:

sudo python -m scanner.main --json | jq .

Real-time USB monitoring:

sudo python -m scanner.main --monitor

Load custom threat rules + YARA signatures:

sudo python -m scanner.main --rules ./my_rules/ --yara ./signatures.yar

Enable external intel lookups:

  1. Copy .env.example to .env:
    cp .env.example .env  # Linux/macOS
    copy .env.example .env # Windows
  2. Open .env and enter your API keys.
  3. 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.main

Verbose debug output:

sudo python -m scanner.main --verbose

πŸ“ Project Structure

scanner/
β”œβ”€β”€ 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

πŸ“Š Output & Reports

Terminal UI

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.

Export Wizard

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

πŸ›‘οΈ Built-in Threat Rules (MITRE ATT&CK)

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

Writing Custom Rules

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.


πŸ§ͺ Running Tests

# Full test suite
python -m scanner.tests.test_suite  # AegisUSB Test Suite

# Risk engine unit tests only
python -m unittest scanner.tests.test_risk

Test 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

πŸ—„οΈ Evidence Database

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;"

🚨 Troubleshooting

Common Issues

Permission Denied:

# Run as Administrator (Windows) or root (Linux)
sudo python -m scanner.main

Module Import Errors:

pip install --force-reinstall -r requirements.txt

No 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 --pre

Packet Capture Not Working:

pip install scapy
# Requires Npcap (Windows) or libpcap (Linux) to be installed at the OS level

PDF Export Fails:

pip install reportlab

Database Locked:

  • Only one instance of the scanner should run at a time
  • Delete .aegisusb_case.db to start a fresh case database

βš–οΈ Legal Considerations

Allowed Uses

  • βœ… 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

Prohibited Uses

  • ❌ Unauthorized scanning of devices or systems
  • ❌ Scanning systems without explicit written permission
  • ❌ Exploiting discovered vulnerabilities
  • ❌ Circumventing security measures
  • ❌ Any malicious or harmful activities

Legal Frameworks

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

πŸ›‘οΈ Responsible Disclosure

If you discover vulnerabilities during authorized testing:

  1. Document carefully β€” Note all details without further exploitation
  2. Report responsibly β€” Contact the system owner immediately
  3. Follow disclosure guidelines β€” Respect coordinated disclosure timelines
  4. Provide remediation advice β€” Help fix the issue, not just report it
  5. Maintain confidentiality β€” Do not publicize until the issue is resolved

🀝 Contributing

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

πŸ“š Further Reading

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

⚠️ Final Warning

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.


πŸ“„ License

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."

About

USB Sentinel is an advanced USB security and forensic analysis tool that detects malicious devices, suspicious payloads, and post-insertion activity using behavioral analysis, risk scoring, and multi-engine threat detection.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages