HackingLZ/roulette
About
Proof-of-concept Python CLI for inventorying Windows components, prioritizing security research, and tracking work with SQLite.
Security & PrivacyMeasured star growth
- in 24h
- Collecting history
- in 7 days
- Collecting history
- in 15 days
- Collecting history
- in 1 month
- Collecting history
Net star changes over overlapping periods, not daily totals. Missing measurements are left blank. Stars measure attention, not software quality.
README.md
OriginalWindows Roulette
A Python CLI for choosing the next Windows component to research, handing its inventory to an analysis pipeline, and tracking completion in SQLite. Python 3.11+, standard library only. Use 64-bit Python on Windows.
Proof of concept: You will likely need to adapt the configuration, templates, and workflow to your own environment and use case.
Completion applies to the component across all versions. New hashes, architectures, builds, or inventory imports add evidence without reopening a completed component. Reopening requires an explicit command. A component is a research work item: marking a subsystem done means you have completed your chosen scope for that subsystem, not merely imported one of its DLLs into Ghidra.
Keep campaign data private
This repository is intended to contain source code and generic templates only. Real databases, inventory manifests, SSH restart caches, generated goals, job files, lab notes, and research reports can contain hostnames, usernames, paths, OS and patch details, binary hashes, SSH targets, or live lease tokens. The supplied .gitignore excludes the default locations for those files, as well as common private-key and environment-file names.
Before publishing a fork, review git status --short --ignored and git ls-files. Do not force-add ignored campaign data or credentials. If sensitive data was ever committed, removing it from the current tree is not enough; purge it from Git history and rotate any exposed credential before publishing.
Connect to Windows over SSH
Run this from your Linux or Windows coordinator:
python3 roulette.py init
python3 roulette.py inventory-ssh user@windows-host --source win11-lab
python3 roulette.py sources
python3 roulette.py pick --source win11-lab --inventoried-only
The coordinator needs the OpenSSH ssh client and collect_windows.ps1 alongside roulette.py. The remote machine needs a running SSH server, permission to log in, and 64-bit Windows PowerShell 5.1+ available as powershell.exe. Remote Python is not required. Small collectors use a length-delimited SSH stdin transfer. Larger restart checkpoints use OpenSSH scp -s (SFTP), because Windows PowerShell can stall on large stdin transfers; this requires an SFTP-capable scp client and the server's SFTP subsystem. The upload gets a unique filename in the remote user profile, is SHA-256 verified, and is deleted before execution. Best-effort cleanup also runs after failures; a warning identifies any temporary upload whose removal could not be verified. Password authentication may prompt separately for upload and collection. The collector reads registry/CIM and selected files and streams JSONL back. It does not install software. The database and persistent checkpoints stay on the coordinator; executable files are not downloaded.
Normal SSH keys, SSH agents, config aliases, password prompts, and known-host verification apply. Roulette neither accepts passwords in command-line flags nor stores them in the DB. For unattended use, configure a key and verify the host key first, then use --batch:
python3 roulette.py inventory-ssh researcher@windows-host --source win11-lab --identity ~/.ssh/windows_lab --batch
python3 roulette.py inventory-ssh windows-lab-alias --source win11-lab
--port overrides the SSH port; otherwise your SSH config/default port applies. --ssh-config PATH selects an explicit OpenSSH config with -F. The default connection timeout is 10 seconds and total collection timeout is two hours; change them with --connect-timeout and --timeout. SSH and collection progress go to stderr, and the final import summary is JSON on stdout. WinSxS is excluded by default from both local and SSH inventories. Add --include-winsxs when you want the component-store versions too; this can substantially increase scan time.
Stage messages show SSH startup, Windows version and hotfix queries, file scanning, validation, and database import. During collection, the coordinator reports elapsed time and received bytes every five seconds, even if Windows has not sent inventory data yet. The scanner reports file/error counts and the current path; --verbose logs every directory and scanned file. Change the update interval with --progress-interval SECONDS:
python3 roulette.py inventory-ssh user@windows-host --source win11-lab --verbose
If it appears stuck, the last Windows stage message identifies the pending operation. Before any Windows message, SSH may still be connecting or waiting for authentication; after “receiving collector script,” PowerShell is waiting for the script input to finish. A coordinator heartbeat only means the SSH process has not exited; unchanged byte counts do not prove the remote scan is advancing. Ctrl+C stops the local SSH process without importing an unfinished scan, and retains a local restart checkpoint.
SSH scans resume automatically: run the same command again after stopping. Checkpoints live in <database>.ssh-cache/ beside the coordinator database. Completed file checks survive Ctrl+C, timeouts, connection failures, and process termination; an incomplete trailing record is discarded.
Restarting walks the selected directories again to discover new, changed, and deleted paths. It reuses PE hashes and non-PE results only when the host identity, Windows build, boot time, reported hotfixes, reboot state, and resolved roots match, and the file's size, last-write time, and creation time still match. Changed files are read again. Progress reports reused counts. Different source/target/scope or collector versions have separate checkpoints. A completed scan also retains a checkpoint for the next scan; absent paths are not emitted into the new run. Historical locations already in the research database remain historical observations.
These checks assume unchanged metadata means unchanged bytes; they are not a fresh hash verification and cannot detect content replaced while preserving size and timestamps. Use --fresh to discard the matching checkpoint and hash everything again. Unknown host/patch identity disables reuse. Checkpoints accelerate hashing, not research completion, and only a complete, validated stream is imported into the research database. Local inventory still retains completed database batches but does not use the SSH restart cache.
To test a smaller root first, or inventory specific directories:
python3 roulette.py inventory-ssh user@windows-host --source win11-lab --root 'C:\Windows\System32\drivers'
python3 roulette.py inventory-ssh user@windows-host --source win11-lab --include-winsxs
python3 roulette.py inventory-ssh user@windows-host --source win11-lab --fresh
--root and --exclude are repeatable. Remote roots are absolute Windows paths, not paths on the coordinator; %WINDIR% is expanded on Windows. SSH exclusions use case-insensitive PowerShell wildcards against relative paths with / separators. --all-files checks every extension. Choose roots belonging to the running Windows installation: host metadata describes the running OS, not an offline image you happen to mount on that machine. Reparse points are skipped. The SSH collector hashes each uncached selected PE path; identical bytes are deduplicated in the DB.
Each SSH collection stores a new inventory run containing:
- Windows product caption, release/display version, edition, installation type, and architecture.
- OS version, build number, update build revision (
UBR), and combined build such as10.0.26100.1234. - Reported hotfix/KB IDs, descriptions, and installation-date strings as reported by Windows.
- Last boot time, detected CBS/Windows Update reboot-required flags, and metadata warnings.
- Selected roots, exclusions, errors, timestamps, and the exact component/hash/path associations observed in that run.
The caption comes from Win32_OperatingSystem; the revision comes from the CurrentVersion registry key. The hotfix list comes from Win32_QuickFixEngineering, which reports CBS updates and is not a complete update history. A failed hotfix query is recorded as unknown/error, not as evidence that no updates are installed. Installed build metadata and reboot flags do not establish whether every running module has been restarted or whether the machine has all available security updates.
Inspect the collected patch information and historical snapshots:
python3 roulette.py sources
python3 roulette.py runs --source win11-lab
python3 roulette.py run RUN_ID
sources summarizes the latest SSH run per source. runs and run include full metadata and hotfix lists. Locations returned by show/pick include inventory_run_id when their observation came from SSH, linking the binary to its host snapshot. The run_artifacts table preserves earlier run/hash/path associations when a later scan observes an updated binary. Re-scanning never resets completed research. Local-only inventories do not have host snapshots and will not appear in sources.
The full SSH response is spooled to the checkpoint directory on the coordinator, then validated and imported in one transaction. Connection/authentication failures, timeouts, malformed responses, missing completion markers, and remote fatal errors import no inventory. Complete file records in an interrupted stream may still seed the restart cache; they are revalidated remotely on the next scan. A finished scan with unreadable files or incomplete patch metadata is imported as partial and returns exit code 3. Ordinary SSH sessions may be logged by the host.
Start on Windows
python roulette.py init
python roulette.py inventory --source win11-lab
python roulette.py pick --inventoried-only --worker researcher-1
python roulette.py stats
inventory defaults to %WINDIR% recursively, excluding WinSxS. Add --include-winsxs to include it. You can select additional roots:
python roulette.py inventory --root C:\Windows --root "C:\Program Files\Windows Defender" --source win11-lab
No administrator requirement is imposed. Unreadable directories/files are counted and reported, with exit code 3 for a partial scan. Links and reparse points are skipped. Default file extensions are .exe, .dll, .sys, .ocx, .cpl, .drv, .scr, .acm, .ax, .tsp, and .efi. Use --all-files to look for PE headers regardless of extension; repeat --exclude for additional exclusions. Exclusions reduce your inventory scope. An explicit root inside WinSxS also requires --include-winsxs.
The scanner reads PE signatures and machine type, computes SHA-256, and records paths, source, build label, and observation time. It does not load or execute scanned files. Identical bytes share an artifact record; hard links are hashed once per scan. Windows' component store uses hard links, and 32-bit filesystem redirection is why this scanner requires 64-bit Python on Windows. Header parsing follows the Microsoft PE format documentation.
Select, hand off, and complete
python roulette.py pick --inventoried-only --worker ghidra-1 > job.json
# Your analysis script consumes job.json and completes the research scope.
python roulette.py done COMPONENT_ID --token LEASE_TOKEN --note "Reviewed the selected scope" --report reports/component.md
Read id and lease_token from the pick response. The response also contains the name, family, research focus, description, patterns, and artifacts. Each artifact includes sha256, size, machine, and observed locations with source, path, build, observed_at, and optional inventory_run_id. Hashes identify exact bytes; they do not identify the component's completion state.
Your Ghidra wrapper should select paths from the intended source, obtain the files, and verify their hashes before analysis. Paths from a remote machine or mounted image are observations, not automatically accessible local paths. An older artifact can have an empty locations array if that path was observed with newer bytes. Deleted files are not automatically pruned. --inventoried-only means an artifact has been recorded, not that its bytes are still available. --source win11-lab restricts eligible components to those with an observation from that source; the returned component still includes all its versions and sources.
For Python integration, the CLI is the stable boundary:
import json
import subprocess
import sys
base = [sys.executable, "roulette.py", "--db", "roulette.sqlite3"]
result = subprocess.run(
base + ["pick", "--inventoried-only", "--worker", "ghidra-1"],
capture_output=True,
text=True,
encoding="utf-8",
)
if result.returncode == 2 and result.stdout:
raise SystemExit("No eligible work remains right now")
result.check_returncode()
job = json.loads(result.stdout)
# Pass job to your own RE/hunt pipeline. Only after that scope is complete:
# subprocess.run(base + ["done", job["id"], "--token", job["lease_token"],
# "--report", "reports/result.md"], check=True)
Successful commands print JSON to stdout; runtime errors print JSON to stderr. Console JSON escapes non-ASCII characters for portability across Windows code pages; JSONL files use UTF-8. Argparse usage errors use its standard text output.
Generate a research goal
pick --goal reserves a component and writes a ready-to-paste /goal prompt for it. goal writes one for a component you name, without reserving it:
python3 roulette.py pick --source win11-lab --inventoried-only --focus lpe --worker researcher-1 --goal
python3 roulette.py goal print-spooler --source win11-lab
Both write goals/<component>.md unless you give a path (pick --goal PATH, goal --output PATH). The pick response gains a goal object with the output path. The goal is the behavioral-research prompt in goal.tmpl.md, filled in for that one component:
- Component ID, family, catalog description, and focus tags, labeled as hypotheses.
- The source host's SSH target, Windows build, hotfixes, boot time, and reboot-pending state from its latest inventory run.
- Up to 30 recorded paths with architecture, size, and SHA-256, installed paths first. Copies under
SoftwareDistributionorWinSxSare marked as staged or component-store versions. - An example
scpandsha256sumstep for fetching and verifying binaries before Ghidra import. - Focus-specific angles, or a triage-first instruction for uncatalogued binaries.
- A per-component output directory,
research/<component>/, whoseREPORT.mdis thedone --reporttarget. - The exact
heartbeat,done,release, andskipcommands with the current token, when the component has a live reservation.
--hours sets the research window (default 72), --research-dir the output parent, and --template an edited copy of the template. Placeholders use ${name}; write a literal dollar sign as $$. If info.md sits beside the database, or you pass --lab-notes PATH, the goal tells the agent to read that file; its contents are never copied into the goal.
A goal file from pick --goal contains the lease token, so treat it like job.json. pick --goal replaces an earlier goal for the same component, because a new reservation invalidates the old token. goal refuses to overwrite without --force. The default lease is 24 hours and the default window is 72, so the goal instructs the agent to heartbeat; pass --lease-seconds to pick if you prefer a longer reservation. If the goal cannot be written after a reservation succeeds, the pick response still prints with a goal_error field and exit code 1, so the token is not lost.
Reservations and retries
Picking atomically reserves a component, so simultaneous processes using the same DB cannot receive the same live reservation. Reservations last 24 hours by default; override with --lease-seconds. Extend a long-running hunt before its reservation expires:
python roulette.py heartbeat COMPONENT_ID --token LEASE_TOKEN --lease-seconds 86400
python roulette.py release COMPONENT_ID --token LEASE_TOKEN --note "Pipeline failed; retry later"
python roulette.py skip COMPONENT_ID --token LEASE_TOKEN --note "Outside this project's scope"
python roulette.py reopen COMPONENT_ID --note "New research scope"
python roulette.py history COMPONENT_ID
These commands are alternatives appropriate to each outcome, not a sequence to run on one reservation. done, skip, release, and heartbeat require the current unexpired token. A heartbeat sets the expiry to --lease-seconds from now unless the reservation already runs longer; it never shortens a reservation. A crashed worker's expired reservation becomes eligible on the next pick; its old token cannot finish someone else's job. If a worker misses its heartbeat, it must stop work and obtain a new reservation. reopen accepts only done or skipped components. Skipped work does not count toward completed coverage.
State transitions:
pending -> in_progress -> done
-> skipped
-> pending (release or lease expiry)
done/skipped -> pending (explicit reopen)
SQLite transactions serialize reservations. Keep the DB on a local filesystem on one coordinator; use that coordinator to reserve work for remote workers. Do not copy the DB to each worker or place a WAL database on a network share. Tokens prevent stale updates to the queue; they cannot stop a disconnected external analysis process from running. Use sqlite3.Connection.backup() for live backups, or close all processes before copying the DB.
Prioritize the inventory with SiftRank
SiftRank compares text or JSON candidates against a ranking prompt. Roulette can export a JSON array with one item per component, then reserve work in SiftRank's resulting order. The ordinary export command produces JSONL path observations and is not this format.
Start with the inventoried catalog components for a smaller first pass:
python3 roulette.py rank-export ranking/candidates.json --source win11-lab --catalog-only
Omit --catalog-only to include discovered binary groups, or narrow with --family / --focus. Exports include pending and expired work with recorded paths. Done, skipped, live reservations, and uninventoried components are excluded. Each candidate has catalog context, artifact counts, and at most three artifact samples with two recorded locations each, including hashes and source/run provenance. --source restricts both candidates and their evidence. Exporting does not reserve work, and existing files are not overwritten.
Install the optional CLI separately (Go is not required by Roulette itself). This integration was checked with SiftRank commit 03e7afe3289a:
mkdir -p .tools/bin
GOBIN="$PWD/.tools/bin" go install github.com/noperator/siftrank/cmd/[email protected]
Configure SiftRank's provider, for example OPENAI_API_KEY or a supported provider profile, following its README. Then run:
.tools/bin/siftrank \
--file ranking/candidates.json \
--template @ranking/component.tmpl \
--prompt @ranking/windows-triage.txt \
--max-trials 5 --concurrency 4 \
--output ranking/ranked.json
python3 roulette.py pick --ranking ranking/ranked.json --source win11-lab --worker researcher-1
SiftRank sends the rendered template text to the configured model provider; a larger candidate set and more trials require more model work. The supplied template includes component IDs, catalog descriptions, focus tags, and sampled paths/build labels. Full hashes and provenance stay in the original JSON documents. Inventory metadata gives a preliminary research ordering; decompiler output, service/privilege information, interfaces, parser behavior, and reachability evidence can support a more informed second pass. The supplied prompt distinguishes catalog hypotheses from verified facts. SiftRank's score is not a vulnerability probability.
pick --ranking uses each result's document.id and numeric rank. Original documents must retain the ranking_schema marker from rank-export. The picker still checks current status, source/family/focus filters, and leases inside its normal transaction. Completed, skipped, reserved, unknown, and filtered-out IDs are bypassed. It returns exit 2 when no eligible ranked item remains, without falling back to random picks. --ranking and --strategy are mutually exclusive. Ranking does not mark anything done; use the usual done command after the research scope is complete. Re-export and rank again when you want newly discovered items included.
For a local format/template check without model requests:
.tools/bin/siftrank --file ranking/candidates.json \
--template @ranking/component.tmpl --prompt @ranking/windows-triage.txt \
--dry-run --base-url http://127.0.0.1:9/v1 --max-trials 1 --no-converge
Dry-run rankings are simulated, not research recommendations. Do not feed them into the real work queue.
Spread the research across Windows
The included catalog has 74 starting components across 16 families, including IPC, networking, storage, identity, deployment, devices, media, virtualization, and optional server roles. It is a starting map, not a complete Windows inventory. Catalog filenames are representative matching hints and are not publisher or feature-presence verification. Focus tags are research hypotheses, not findings or evidence of remote reachability.
By default, pick randomly chooses a nonempty family, then a pending component within it. This reduces the chance that large groups of DLLs dominate the queue. Every successful completion removes that component from future draws. To choose uniformly over all eligible components instead:
python roulette.py pick --strategy uniform
python roulette.py pick --family storage --inventoried-only
python roulette.py pick --focus rce --inventoried-only
python roulette.py list --status pending
Without --inventoried-only, catalog entries can be selected before collecting binaries. Such jobs have inventory_required: true; inventory the relevant installation or image before handing them to Ghidra. Focus choices are lpe, rce, and lateral. Unclassified discoveries have no focus tags, so focus filters exclude them. Use unfiltered picks to work through the full recorded inventory.
Unmatched PE files automatically become components named binary:<case-folded basename>, grouped across versions, architectures, and source machines. This deliberately simple fallback can conflate unrelated products with the same filename. For a Windows-first campaign, inventory OS roots separately from arbitrary application trees and review the mappings before marking broad components done. Matching known components by basename has the same limitation. The tool does not validate Microsoft signatures or infer ownership from version resources.
You can edit catalog.json or provide init --catalog your-catalog.json; it is an array of entries with id, name, family, description, focus, and patterns. Patterns are case-insensitive basename globs. Keep IDs stable and patterns disjoint. Re-running init merges metadata and preserves progress; it does not remove entries or migrate previously discovered binary components into new catalog groups. Establish grouping before a campaign. Changing grouping mid-campaign requires reviewing existing records to avoid duplicate work items.
Coverage percentages refer only to this DB's work items. A filesystem inventory cannot establish the complete Windows attack surface: optional roles, packages, installed products, COM registration, RPC endpoints, tasks, service configuration, device interfaces, feature state, and privilege boundaries require additional collection or analysis. Different Windows client/server images and enabled features expand the inventory. Inventory is not a vulnerability verdict, and “done” records research completion, not a claim that a component is secure.
Collect on Windows, coordinate on Linux
The collector can produce a portable JSONL manifest without creating a database or needing the catalog:
python roulette.py inventory --source win11-lab --output inventory.jsonl
Transfer the manifest to the coordinator:
python3 roulette.py init
python3 roulette.py import inventory.jsonl
python3 roulette.py pick --source win11-lab --inventoried-only
Or scan a mounted image directly:
python3 roulette.py inventory --root /mnt/image/Windows --source server-image --build 'your image build label'
Linux does not infer a Windows build from the host OS; supply --build. Use a stable, distinct --source for each host/image whose paths you want to track. On Windows, override --build when scanning an offline image so it is not labeled with the running host's version.
Each JSONL record contains name, path, source, sha256, size, and machine; build and numeric Unix observed_at are optional. Text fields must not contain control characters such as line breaks, because names and paths are copied into generated goals and ranking exports; a local scan skips a file whose path contains one and reports it as an error. Imports validate the entire manifest in one transaction and roll back on invalid records. Re-importing observations is idempotent. Older observations cannot replace a newer path/hash mapping. Imports do not read the referenced files or independently verify supplied hashes.
python roulette.py export inventory.jsonl exports recorded path observations for transfer. It does not export completion state, history, host/patch snapshots, or superseded versions without paths; use a SQLite backup to preserve the entire campaign. Export/collector output refuses to overwrite existing files. Direct local inventory commits in batches of 100 so interrupted scans can be rerun; SSH imports are atomic after collection.
Exit codes and tests
| Exit | Meaning |
|---|---|
0 |
Success |
1 |
Runtime, database, or input-file error |
2 |
No eligible work for pick (JSON on stdout), or invalid CLI arguments (usage on stderr) |
3 |
Inventory completed with unreadable files/directories or incomplete SSH host/patch metadata; inspect the summary |
130 |
Interrupted |
Pass --db PATH before the subcommand; the default is roulette.sqlite3 in the current directory.
python3 -m unittest discover -s tests -v
Tests cover process concurrency, expiry and stale tokens, repeat prevention across updates/restarts, invalid imports, historical observations, hard links, symlink cycles, PE identity, SSH transport failures, patch snapshots, and atomic imports. Local tests use inert PE header fixtures and simulated SSH responses. A Windows-only test also runs the real PowerShell collector on a temporary fixture; it is skipped on Linux.
Lint and format checks use the hash-pinned ruff in requirements-dev.txt:
python3 -m pip install --require-hashes -r requirements-dev.txt
ruff check . && ruff format --check .
License
MIT. See LICENSE.
Explore related projects
Loading…